Conflicts between 'for' and 'switch'? - java

I want to try a little programming that can read user input continuously unless input is 0.
But the problem is whatever I enter (except 0), it always shows "Please choose one" (in default part). If I enter 4, it will show me this phrase twice!
I do not understand why. Is there a conflict between for and switch or something?
Here is code:
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0') {
switch(ch) {
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
}

The problem is char ch = (char)System.in.read();. Java does not support character based input very well, I recommend using a Scanner which fixes your output, however the user now has to press return after each input.
import java.io.IOException;
import java.util.Scanner;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
while (!s.equals("0"))
{
switch(s)
{
case "1":
System.out.println("The If");
break;
case "2":
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
s = in.nextLine();
}
}
}
If you don't want to press return, you can also read the character twice, although I can only speculate why this works is that there is a control character sent over the stream. Edit: I thought it could also be another byte of a UTF-16 character which is not used when typing in ASCII characters but System.in.read() returns integers not bytes.
import java.io.IOException;
public class Switch
{
public static void main(String[] args) throws IOException
{
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println("Choose one: ");
char ch = (char)System.in.read();
while (ch!= '0')
{
switch(ch)
{
case '1':
System.out.println("The If");
break;
case '2':
System.out.println("The Case");
break;
default:
System.out.println("Please choose one");
}
ch = (char)System.in.read();
ch = (char)System.in.read();
}
}
}

System.in.read() reads a byte from the InputStream and returns it. When you type 1 or any single digit number and press enter, it reads two characters.
Try tying multiple digit number to see how System.in.read() behaves.
You should use scanner for the console input:
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Related

infinite loop unable to close loop in Switch Statements

import java.util.Scanner;
class MenuFastFood {
public static void main(String[] args) {
String s;
char order;
Scanner keyboard = new Scanner(System.in);
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);
do {
switch(order) {
case 'A':
System.out.println("CheeseBurger");
System.out.println("Onion Rings");
System.out.println("Soda");
break;
case 'B':
System.out.println("Hot dog");
System.out.println("Fries");
System.out.println("Milk Shake");
break;
default:
System.out.println("error");
return;
case 'X':
System.out.println("EXIT");
break;
}
}while(order != 'X');
}
my program is suppose to pick an item based on the character enter in to keybaord and then loops back if another item is selected. when i run this and pick an item. it loops that item for ever. How do i get that to stop and makes it able for me to select another item?
Move your code for reading input to inside do..while
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);

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();

Switch statement loops through

I'm trying to make a simple Menu with the switch statement. However i'm having a problem with the switch:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException{
char selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char)System.in.read();
switch(selection){
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
}
}
while(selection != '3');
}
}
For some reason, when selecting either one or two, the result is that print menu gets printed twice, like this:
Program output:
Choose option:
1. opt1.
2. opt2.
3. opt3.
1
opt1 chosen
Choose option:
1. opt1.
2. opt2.
3. opt3.
Choose option:
1. opt1.
2. opt2.
3. opt3.
The question is, what causes this problem?
When you press a number and <Enter> this is two characters not one. i.e. you are typing
1\n
This is unavoidable, but you can chose to parse the input differently with Scanner which handles this differently, or you can ignore it. (or you can expect the user must type a \n after a number...
As Peter pointed out, the problem arises because of the way you are reading the 'selection' input. You can correct the functionality as follows:
public class main {
public static void main(String[] args) throws IOException {
printMenu();
}
public static void printMenu() throws IOException {
char selection = '0';
while (selection != '3') {
if (selection != '\n') {
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
}
selection = (char) System.in.read();
switch (selection) {
case '1':
System.out.printf("opt1 chosen\n");
break;
case '2':
System.out.printf("opt2 chosen\n");
break;
case '3':
break;
default:
break;
}
}
}
}
Peter Lawrey is right
I'm suggest using Scanner class :
public static void printMenu() throws IOException {
Scanner scanner = new Scanner(System.in);
int selection = 0;
do{
System.out.println("Choose option: ");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. QUIT");
System.out.println("\t\t\t");
selection = (char) scanner.nextInt();
switch(selection){
case 1:
System.out.printf("opt1 chosen\n");
break;
case 2:
System.out.printf("opt2 chosen\n");
break;
case 3:
break;
}
scanner.nextLine();
}
while(selection != '3');
}

nested switch case error with wrong output?

I am experiencing some problems with the output of my program. I am certain the error is logical but i just cant fix it. error should be somewhere around here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
I don't know how to fix it. At the moment if i insert A+ to the program it would give me the result for A-. Heres my full code.
public class SwitchCase {
public static void main(String[] args) {
System.out.println("Please enter your grade (ex.A+) to get the mark range");
/*This block of codes converts from string to
* char and it gets the plus or minus sign
*/
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
/*This set of code contains the nested switch statements
* that i will use to output the correct mark range
* to the user. It also contains a try statement to find runtime
* errors in the program.
*/
try{
switch(grade)
{
case 'A':
switch(modifier)
{
case '+': System.out.println("Your grade is 90-99.99%"); break;
case '-': System.out.println("Your grade is 80-84.99%"); break;
default: System.out.println("Your grade is 85-89.99%"); break;
}
break;
case 'B':
switch(modifier)
{
case'+': System.out.println("Your grade is 77.00 - 79.99%"); break;
case'-': System.out.println("Your grade is 70.00 - 72.99%"); break;
default: System.out.println("Your grade is 73.00 - 76.99%"); break;
}
break;
case 'C':
switch(modifier)
{
case'+': System.out.println("Your grade range is 67.00 - 69.99%"); break;
case'-': System.out.println("Your grade range is 60.00 - 62.99%"); break;
default: System.out.println("Your grade range is 63.00 - 66.99%"); break;
}
break;
case 'D':
switch(modifier)
{
case'+': System.out.println("Your grade range is 55.00 - 59.99%"); break;
case'-': System.out.println("-"); break;
default: System.out.println("Your grade range is 50.00 - 54.99%"); break;
}
break;
case 'F':
switch(modifier)
{
default: System.out.println("Your grade range is 0.00-49.99%"); break;
}
break;
}
}
catch (java.util.InputMismatchException e) { //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid grade!");
}
input.close(); //ends the user input
}
}
After
char grade = userInputString.charAt(0);
add
char modifier = ' ';
if( userInputString.length() > 1 ){
modifier = userInputString.charAt(1);
}
and remove the code dealing with plusorminus.
You should also add some code to avoid hiccups after reading the input line.
userInputString = userInputString.trim(); // maybe user hits space?
if( ! userInputString.matches( "^[A-F][-+]?$" ) ){
// error message...
}
Not sure whether there is E, and F+ or F-?? We have different grades. Perhaps the regex should be
"^[A-E][-+]?|F$"
You might be inserting
A+
but you're only consuming the A.
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
The modifier is assigned, deterministically, here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
The length of plusorminus will always be 2 which means that modifier will always be plusorminus.charAt(1), ie. -. You want to assign the second character of your input string as the modifier.

Do while Running more times

I have to get 1 to 3 answer if user puts invalid option do while should re run but problem is its re running three times. like if I put answer in 1 to 3 its giving correct result on other number it reprint loop three times.
char choice;
public void mainMartfunc() throws java.io.IOException{
do{
System.out.println("Login as:");
System.out.println(" 1. Customer");
System.out.println(" 2. Employee");
System.out.println(" 3. Owner");
choice = (char) System.in.read();
} while(choice < '1' || choice>'3');
switch(choice){
case '1':
System.out.println("\tCustomer Menu:");
break;
case '2':
System.out.println("\tEmployee Menu:");
break;
case '3':
System.out.println("\tOwner Menu:");
break;
}
}
When you press the enter key, two characters are generated: a carriage return '\r' and a line feed '\n'. And System.in.read() takes each character from the input, so you get three characters including the digit.
Trying using a Scanner instead. It will tokenize your input so you don't receive those whitespace characters.
java.util.Scanner input = new java.util.Scanner(System.in);
then change your choice assignment to something like this:
choice = input.next().charAt(0);

Categories