import java.util.Scanner; public class inputParse { public static void main(Stri
ID: 3542764 • Letter: I
Question
import java.util.Scanner;
public class inputParse
{
public static void main(String[] args)
{
String input;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter any numbers or letters: ");
input = scanner.nextLine();
Scanner sc = new Scanner(input).useDelimiter(" ");
int count = 0;
while (sc.hasNextInt() == true)
{
System.out.println("Integer: " + sc.nextInt());
count ++;
System.out.println(count);
}
while (sc.hasNextDouble() == true)
{
System.out.println("Double: " + sc.nextDouble());
count ++;
System.out.println(count);
}
while (sc.hasNext() == true)
{
System.out.println("String: " + sc.next());
count ++;
System.out.println(count);
}
}
}
Well in this program the user inputs a "phrase" which the program detects if is a double int or string whick I am having a problem with that
It does detect the integer or double but at the first input for example:
432 vfdv 423 ferw 213 54
the output would be:
Integer: 432
and then the rest Strings
Any suggestions?
and also how can I count the integers doubles and string
in the output it shows every integer
for example integer: 3432
1
integer: 43543
2
integer 3: 654654
3
and so on ....
And finally how do I sum up the ints and the double and concatenate the string
thank you!!
Explanation / Answer
Your problem is that you are using three seperate while loops. So when it hits the first string, it stays in that while loop (because it isn't checking if it is an int or a double, and is just accepting them as strings). What may work better is to have a while loop that only checks that there is another token and use ifs to check for int/double/string. For your other question, add seperate counts for each variable type. So:
While(sc.hasNext()){
if(sc.hasNextInt() == true){
System.out.println("Integer: " + sc.nextInt());
count ++;
System.out.println(count);
intcount++;
}else if(sc.hasNextDouble() == true){
System.out.println("Double: " + sc.nextDouble());
count ++;
System.out.println(count);
dblcount++;
}else{
System.out.println("String: " + sc.next());
count ++;
System.out.println(count);
strcount++;
}
}
Hope this helps.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.