简体   繁体   中英

Parse int, double, and String from a String in Java

I have to do an assignment in my Java class using the Scanner method to input an integer (number of items), a string (name of the item), and a double (cost of the item). We have to use Scanner.nextLine() and then parse from there.

Example:

System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();         

The user would input something like: 3 Captain Crunch 3.5

Output would be: Captain Crunch #3 for $10.5

The trouble I am having is parsing the int and double from the string, but also keeping the string value.

  1. First of all, split the string and get an array.
  2. Loop through the array.
  3. Then you can try to parse those strings in array to their respective type.

For example: In each iteration, see if it is integer. Following example checks the first element to be an integer.

string[0].matches("\\d+")

Or you can use try-catch as follow (not recommended though)

try{
   int anInteger = Integer.parseInt(string[0]);
   }catch(NumberFormatException e){

   }

If I understand your question you could use String.indexOf(int) and String.lastIndexOf(int) like

String input = "3 Captain Crunch 3.5";
int fi = input.indexOf(' ');
int li = input.lastIndexOf(' ');
int itemNumber = Integer.parseInt(input.substring(0, fi));
double price = Double.parseDouble(input.substring(li + 1));
System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
            itemNumber, itemNumber * price);

Output is

Captain Crunch #3 for $10.50
    Scanner sc = new Scanner(System.in);
    String message = sc.nextLine();//take the message from the command line
    String temp [] = message.split(" ");// assign to a temp array value
    int number = Integer.parseInt(temp[0]);// take the first value from the message
    String name = temp[1]; // second one is name.
    Double price = Double.parseDouble(temp[2]); // third one is price
    System.out.println(name +  " #" + number + " for $ "  + number*price ) ;

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