Int, double and string parameter from string in Java
I need to make an assignment in my Java class with a method Scanner
to input integer (number of items), string (item name) and double (item value). We have to use Scanner.nextLine()
and then analyze from there.
Example:
System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();
The user enters something like: 3 Captain Crunch 3.5
The output would be: Captain Crunch #3 for $10.5
The problem I ran into was parsing int and double from string, but also storing the string value.
source to share
- First of all, split the string and get an array.
- Loop through the array.
- Then you can try to parse those strings in the array to the appropriate type.
For example: At each iteration see if it's integer. In the following example, the first element must be integer.
string[0].matches("\\d+")
Or you can use try-catch as follows (not recommended)
try{
int anInteger = Integer.parseInt(string[0]);
}catch(NumberFormatException e){
}
source to share
If I understand your question, you can use String.indexOf(int)
and String.lastIndexOf(int)
how
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
Captain Crunch #3 for $10.50
source to share
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 ) ;
source to share