Default case is being executed before even entering switch-case - java

I run the program and it reaches while loop with input set on "" before the loop. When it enters the while loop it prints "Wrong input!" and then it asks to type in input = sc.nextLine(). Why? It hasn't even entered the switch-case statement.
Thank you in advance.
Scanner sc = new Scanner(System.in);
int size;
size = sc.nextInt();
String[] mem = new String[size];
int[] mem_index = new int[size];
String input = "";
while(!input.equals("quit")) {
input = sc.nextLine();
switch(input) {
case "Z": mem = memAlloc(mem, allocRequest);
memPrint(mem, mem_index);
allocRequest++;
break;
case "O": System.out.print("Type memory data id: ");
delRequest = sc.nextInt();
mem = memDel(mem, mem_index, delRequest);
memPrint(mem, mem_index);
break;
case "F": mem = memFrag(mem, mem_index);
memPrint(mem, mem_index);
break;
case "quit": break;
default: System.out.println("Wrong input!");
break;
}
}

You probably have something else in your scanner. Try adding this line:
sc.next();
before you go into the while loop or right in the beginning of your loop.

Related

How to choose and write a loop for this specific task?

I am pretty new to Java. Sorry if this is a lame question. I have this chunk of code. It is not the whole thing obviously.
char option = scan.next().charAt(0);
for (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
}
int lengthOne = stringOne.length(); //Getting the lengths for each string
int lengthTwo = stringTwo.length();
if (option == 'a'|| option == 'A') { //If the user inputs a
if (lengthOne == lengthTwo) { //If both lengths are equal
System.out.println("The strings are the same length");
}
Looking for some advice on which loop i should use for this code. The options will be A-F and then Q to quit.
The while loop can seem messy for what you are trying to accomplish. I would use a Switch statement inside a 'do while' loop.
If the user input doesn't match a 'case' then it will go to the default.
When a user enters 'q' to quit then boolean validSelection turns to true and you will exit the 'do while' loop.
public static void main( String[] args )
{
Scanner scan = new Scanner( System.in );
boolean validSelection = false;
do
{
System.out.println( "Please pick an option from the menu above" );
char option = scan.next().charAt( 0 );
switch( option )
{
case 'a':
break;
case 'b':
break;
case 'c':
break;
case 'd':
break;
case 'e':
break;
case 'f':
break;
case 'q':
validSelection = true;
break;
default:
System.out.println( "Choice invalid." );
break;
}
}
while( validSelection == false );
}
}
Add a scan inside the loop.
char option = scan.next().charAt(0);
while (option !='a'||option !='b'||option !='c'||option !='d'||option !='e'||option !='f'||option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
Try this
Scanner scan = new Scanner(System.in);
char option = scan.next().charAt(0);
while (option != 'a' && option !='b' && option != 'c'&& option !='d'&& option !='e'&& option !='f'&& option !='q') {
System.out.println("Please pick an option from the menu above");
option = scan.next().charAt(0);
}
You will need the ANDs instead of the ORs or it wont work

How to loop back to start of array after incorrect input

first post here.
I was instructed to change my code to loop back to the beginning of the array and ask the user for input again after they input something invalid (Like 0 or 5 for example).
If someone could point me in the right direction, I would be thankful.
package lepackage;
import java.util.Scanner;
public class SwitchItUp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter menu item:");
int input = scanner.nextInt();
String inputString;
switch (input) {
case 1: inputString = "User want to Enter data";
break;
case 2: inputString = "User want to Display sata";
break;
case 3: inputString = "User want to Print data";
break;
case 4: inputString = "User want to Exit";
break;
default: inputString = "Invalid Number";
break;
}
System.out.println(inputString);
}
}
I'd surround it with a do...while loop
do {
//your code here
} while (!(input > 0 && input < 5));
See it online!
how about using a label here. though It's not the cleaner approach compare to do.. while. see the code . Also don't forget to close the scanner !!
Scanner scanner = new Scanner(System.in);
int input;
badinput: while (true) {
System.out.println("Enter menu item:");
input = scanner.nextInt();
String inputString;
if ((!(input > 0 && input < 5)))
continue badinput;
else {
switch (input) {
//switch case
}
System.out.println(inputString);
break;
}
}
scanner.close();

i need to skip a part in my code i dont't know how

i wanna know how can i skip my try again part if my input in 'input' is invalid. for example, I enter 'o' as my choice. it should display "invalid input" and it should display the menu part (skipping the try again). help me please.
public class Menu {
public static void MainMenu() {
Part1 call1 = new Part1();
Part2 call2 = new Part2();
Part3 call3 = new Part3();
Part4 call4 = new Part4();
Scanner in = new Scanner(System.in);
String yn = null;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
do {
switch (input) {
case "I":
call1.one();
break;
case "II":
call2.two();
break;
case "III":
call3.three();
break;
case "IV":
call4.four();
break;
case "V":
System.exit(0);
break;
default:
System.out.println("invalid input");
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
} while (yn.equalsIgnoreCase("y"));
} while (yn.equalsIgnoreCase("n"));
}
}
public class Menu {
public static void MainMenu() {
Part1 call1 = new Part1();
Part2 call2 = new Part2();
Part3 call3 = new Part3();
Part4 call4 = new Part4();
boolean inputWasValid = false;
Scanner in = new Scanner(System.in);
String yn = null;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
do {
switch (input) {
case "I":
call1.one();
break;
case "II":
call2.two();
break;
case "III":
call3.three();
break;
case "IV":
call4.four();
break;
case "V":
System.exit(0);
break;
default:
inputWasValid = true;
System.out.println("invalid input");
break;
}
if (inputWasValid) {
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
} while (yn.equalsIgnoreCase("y"));
} while (yn.equalsIgnoreCase("n"));
}
}
as #Kevin say, you can try this.
My understanding is that you want something like this:
...
Scanner in = new Scanner(System.in);
String yn = null;
boolean retry;
do {
System.out.println("\t\t---HOMEWORK---");
System.out.println("\tI for PART 1");
System.out.println("\tII for PART 2");
System.out.println("\tIII for PART 3");
System.out.println("\tIV for PART 4");
System.out.print("\tEnter input: ");
String input = in.next();
retry = true;
switch (input) {
...
default:
System.out.println("invalid input");
break;
}
System.out.print("try again? -Y- || -N- : ");
yn = in.next();
// might want to do check & loop here to see if user enters just Y or N
if(retry && yn.equalsIgnoreCase("N")) retry = false;
} while (retry);
With this, you get the following results:
Input I try again Y will run through loop again
Input I try again N will terminate loop
Input P try again Y will run through loop again (invalid input displayed, but give user choice of continuing)
Input P try again N will terminate loop (invalid input displayed, user decides to not continue)

Scanner returning an error for no reason?

I'm trying to do this line of code. I want it to take a String, if it is 1,2,3,4,5,6,7,8,9 or 10 to parse it into a int and then check if it is between 0 and 9 (after a -1). The issue is right after the scanner happens I get an error no matter what I do...
public void guessEnter() {
Scanner scan = new Scanner(System.in);
String guessXS;
String guessYS;
boolean pass1;
boolean pass2;
do{
do{
System.out.println("Enter a value for the column!");
guessXS = scan.nextLine();
switch(guessXS){
case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9":case "10":
System.out.println("TRUE");
pass1 = true;
break;
default:
System.out.println("FALSE");
pass1 = false;
break;
}
}while(pass1 == false);
do{
System.out.println("Enter a value for the row!");
guessYS = scan.nextLine();
switch(guessYS){
case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10":
pass2 = true;
System.out.println("TRUE");
break;
default:
pass2 = false;
System.out.println("FALSE");
break;
}
}while(pass2 == false);
guessX = Integer.parseInt(guessXS) - 1;
guessY = Integer.parseInt(guessYS) - 1;
}while(guessX >= 0 && guessX <= 9 && guessY >= 0 && guessY <= 9);
}
Why this is happening is beyond me. I am fairly new to java and need this error sorted out.
The error is...
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at shipLocation.xyInput(shipLocation.java:11)
at battleShipMain.main(battleShipMain.java:53)
Thanks for the help.
Even if the question has already been answered (the error was in a different class) and the provided code caused no error you maybe want to improve your code a bit. To make it easier to read and understand in case you have to change it later.
You could for example wrap the input and validation part in a method:
private int readIntBetweenMinAndMax(String msg, int min, int max) {
Scanner scanner = new Scanner(System.in);
System.out.println(msg);
int userInput;
do {
try {
userInput = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.err.println("Please enter a valid integer");
continue;
}
if (userInput > max || userInput < min) {
System.err.println("Please enter a integer between " + min + " and " + max);
continue;
}
return userInput;
} while (true);
}
The method above prints a provided string msg and then reads in an integer. It checks if the user input is an integer and if it's greater or equals than min and less or equals than max. In case one of the three conditions fails the method will print an error message and prompt the user for a new input until its correct.
Note: You could of course also include the "TRUE" and "FALSE" outputs if you want
So you would only have to call the method two times in your guessEnter method:
public void guessEnter() {
guessX = readIntBetweenMinAndMax("Enter a value for the column!", 1, 10) - 1;
guessY = readIntBetweenMinAndMax("Enter a value for the row!", 1, 10) - 1;
}
This would accept one, ten and any number between the them. And subtract one as you did in your code.
As a said, it's just a suggestion and I'm not sure if a got everything form your code right but I hope it helps (:

Terminate Java Program on Ctrl+Z input from user

I have following code:
String inputString;
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("jcp>");
inputString = in.nextLine();
String[] tokens = inputString.split(" ");
switch (tokens[0]) {
case "new":
createNewInstance(tokens);
break;
case "call":
callMethod(tokens);
break;
case "print":
Object obj = hashMap.get(tokens[1]);
print(obj);
break;
default:
System.out.println("Illegal command!");
break;
}
}
I simply want the program to break out of while loop when user hits ctrl+Z
nextLine() will throw NoSuchElementException when the stream has reached its end. Or you can use in.hasNextLine().
Ctrl+Z to exit the program would be bad, Ctrl+C|Ctrl+D already ends the program execution on terminal, so it would be good the same way you expect users to type in commands, tell them to type exit as the command to EXIT your program and shortcuts like x or e can be used instead of complete word.
How about following code,
String inputString;
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("jcp>");
inputString = in.nextLine();
String[] tokens = inputString.split(" ");
switch (tokens[0]) {
case "n":
case "new":
createNewInstance(tokens);
break;
case "c":
case "call":
callMethod(tokens);
break;
case "p":
case "print":
Object obj = hashMap.get(tokens[1]);
print(obj);
break;
case "e":
case "x":
case "exit":
return;
default:
System.out.println("Illegal command!");
break;
}
}
If return; won't work you can replace that with System.exit(0);

Categories