austrianpainter
JCHJava Community | Help. Code. Learn.
•Created by austrianpainter on 1/17/2025 in #java-help
Scanner Bug (Tried Everything)
So I ask users through input through these two methods:
The error occurs in the switch statement below, I think it happens when I ask for a byte, then a string, or vice versa (I forget):
bytInput also used a method switch is in a loop, if you need code more pls ask
public static String whileLoopInputString (Predicate<String> checkCase, String inputMessage, String errorMessage, Scanner scanner) {
String input = "";
while (!checkCase.test(input)) {
System.out.println(inputMessage);
input = scanner.nextLine();
if (!checkCase.test(input)) {
System.out.println(errorMessage);
}
}
return input;
}
public static byte whileLoopInputByte (Predicate<Byte> checkCase, String inputMessage, String errorMessage, Scanner scanner) {
byte input = -1;
while (!checkCase.test(input)) {
try {
System.out.println(inputMessage);
input = scanner.nextByte();
scanner.nextLine();
if (!checkCase.test(input)) {
System.out.println(errorMessage);
}
} catch (InputMismatchException e) {
System.out.println(errorMessage);
scanner.nextLine();
}
}
return input;
}
public static String whileLoopInputString (Predicate<String> checkCase, String inputMessage, String errorMessage, Scanner scanner) {
String input = "";
while (!checkCase.test(input)) {
System.out.println(inputMessage);
input = scanner.nextLine();
if (!checkCase.test(input)) {
System.out.println(errorMessage);
}
}
return input;
}
public static byte whileLoopInputByte (Predicate<Byte> checkCase, String inputMessage, String errorMessage, Scanner scanner) {
byte input = -1;
while (!checkCase.test(input)) {
try {
System.out.println(inputMessage);
input = scanner.nextByte();
scanner.nextLine();
if (!checkCase.test(input)) {
System.out.println(errorMessage);
}
} catch (InputMismatchException e) {
System.out.println(errorMessage);
scanner.nextLine();
}
}
return input;
}
switch (bytInput) {
case 1:
System.out.println("Rules");
break;
case 2:
strCreatedPlayerName = Logic.whileLoopInputString(
conditions);
break;
case 3:
strUsernameToLoadIn = Logic.whileLoopInputString(conditions);
case 4:
method();
break;
case 5:
bolIsInProgram = false;
break;
}
switch (bytInput) {
case 1:
System.out.println("Rules");
break;
case 2:
strCreatedPlayerName = Logic.whileLoopInputString(
conditions);
break;
case 3:
strUsernameToLoadIn = Logic.whileLoopInputString(conditions);
case 4:
method();
break;
case 5:
bolIsInProgram = false;
break;
}
9 replies