1

So I've been trying to write a program where it will be able to get any integer from a string input despite it's length. I've only been able to get it if the length of the integer is 1. Here is my code so far with methods from another class I wrote.

Scanner input = new Scanner(System.in);
Object user1 = new Object();
String user1Input = null;
System.out.println("Please enter coins");
user1Input = input.nextLine();
while(!(user1Input.contains("end"))){
    if(user1Input.contains("Quarters")){
        user1.depositQuarters(Character.getNumericValue(user1Input.charAt(0)));
    }
}

So this code I have so far, say I enter "2 Quarters" it will return me the balance of $0.50 But if I enter "20 Quarters" it will return me $0.50 as well. I have tried another way of having declaring another variable

System.out.println("Please enter coins");
int coins = input.nextInt();
String user1Input = input.nextLine();

And then the same while loop with if-statements follows this and returns an error. Any help would be appreciated. Thanks

WuTang
  • 17
  • 1
  • 2
    Possible duplicate of [Get int from String, also containing letters, in Java](http://stackoverflow.com/questions/2338790/get-int-from-string-also-containing-letters-in-java) – Thomas Ayoub Oct 15 '15 at 14:36
  • 1
    It looks like the way you have your code made for this line: `user1.depositQuarters(Character.getNumericValue(user1Input.charAt(0)));` it is only changing the first index it sees. – ryekayo Oct 15 '15 at 14:37
  • 1
    Your second approach is hitting this: http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – khelwood Oct 15 '15 at 14:37
  • 1
    @Thomas Correct, but better not to input a string you have to take apart. That's what why there is Scanner. – laune Oct 15 '15 at 14:51

3 Answers3

0

If you want to stay with your first approach you can change user1Input to replace the " Quarters" portion. Something like this:

user1.depositQuarters(Integer.parseInt(user1Input.replace(" Quarters", "")));

Hope this helps.

gonzo
  • 2,024
  • 1
  • 12
  • 24
0

Please try this (I have tested the code); if it works, please then replace the second "System.out.println" to "user1.depositQuarters":

Scanner input = new Scanner(System.in);
Object user1 = new Object();
String user1Input = null;
System.out.println("Please enter coins");
user1Input = input.nextLine();
while(!(user1Input.contains("end"))){
    if(user1Input.contains("Quarters")){
        System.out.println(Integer.parseInt(user1Input.split(" ")[0]));
        break;
    }
}

Thanks!

Tsung-Ting Kuo
  • 1,153
  • 6
  • 16
  • 20
0

A Scanner might do all the work for you:

int ncoins = input.nextInt();
int coinName = input.nextLine().trim();

will, with an input of "40 Quarters" give you 40 in ncoins and "Quarters" in coinName.

This will work even with spaces preceding the number or following the name.

laune
  • 30,276
  • 3
  • 26
  • 40