Could someone help me and explain what is wrong here?

Joined
Jul 1, 2022
Messages
2
Reaction score
0
Using java's scanner input the code needs to return certain output as such:

Expected Output
Download
  • String: Welcome to HackerRank's Java tutorials!

  • Double: 3.1415

  • Int: 42
Here is my code:
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int count = 1;
String typeCase = "";



while (count<4) {

if (!sc.hasNext("[0-9]+[\\.]?[0-9]*") || sc.hasNext(":ascii:")) {

typeCase = "String:";
count++;

} else if (sc.hasNextInt()) {

typeCase = "Int:";
count++;

} else if (sc.hasNextDouble()) {


typeCase = "Double:";
count++;

}

switch (typeCase) {
case "String:":
typeCase = "String: ";
System.out.println(typeCase + sc.nextLine());
break;
case "Int:":
typeCase = "Int: ";
System.out.println(typeCase + sc.nextInt());
break;
case "Double:":
typeCase = "Double: ";
System.out.println(typeCase + sc.nextDouble());
break;
}
}
}

Thank you guys in advance.
 
Joined
Mar 28, 2022
Messages
82
Reaction score
11
Please use the provided code block tool </> so the code is legible to your potential help
 
Last edited:
Joined
Jul 1, 2022
Messages
2
Reaction score
0
Code:
public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int count = 1;
        String typeCase = "";

        while (count<4) {

            if (!sc.hasNext("[0-9]+[\\.]?[0-9]*") || sc.hasNext(":ascii:")) {

                typeCase = "String:";
                count++;

            } else if (sc.hasNextInt()) {

                typeCase = "Int:";
                count++;

            } else if (sc.hasNextDouble()) {


                typeCase = "Double:";
                count++;

            }

            switch (typeCase) {
                case "String:":
                    typeCase = "String: ";
                    System.out.println(typeCase + sc.nextLine());
                    break;
                case "Int:":
                    typeCase = "Int: ";
                    System.out.println(typeCase + sc.nextInt());
                    break;
                case "Double:":
                    typeCase = "Double: ";
                    System.out.println(typeCase + sc.nextDouble());
                    break;
            }
        }
    }
 
Joined
Mar 28, 2022
Messages
82
Reaction score
11
The while statement requires count >= 4 to exit, but incrementing count isn't guaranteed to happen.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top