简体   繁体   中英

How can I grab an integer of any length from a string input

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

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.

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM