Control Flow Condition - java

I fail to understand why For loop keeps executing, if condition meet and break statement applied.
Code:
class ProgramControlStatements {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Menu: ");
System.out.println("Choice: ");
System.out.println("1: If/Else");
System.out.println("2: Switch");
for(int i = 0; i < 5; i++) {
chooseOption();
};
};
static void chooseOption() throws java.io.IOException{
char choice = (char) System.in.read();
switch(choice){
case 'a':
System.out.println("Computer control statement: If/Else");
break;
case 'b':
System.out.println("Computer control statement: Switch");
break;
default:
System.out.println("No valid option");
};
}
}
Expected result:
If char a chosen, print "If/Else" and expect next input until i<5
Computer control statement: If/Else
Actual result:
First Input -> a
Computer control statement: If/Else
No valid option
Second input -> b
Computer control statement: Switch
No valid option
Third input -> a
Computer control statement: If/Else
Program ends.
I expect default statement to be skipped since break statement is applied.
Is this happening as System.in.read() returns a new line?
I think same behaviour is to be expected from while; do-while loops?

It's not as easy as #Arvind Kumar Avinash says, depending on your OS you may encounter either a \r (carriage return), \n (new line) or both \r\n after every line.
So just adding another System.in.read() line is a workaround that may not always work.
I suggest using Scanner instead, as suggested here: Take a char input from the Scanner.
LE: As an answer to a request in the comment, I would like to specify that I always try to use Scanner when I want to parse my input and don't mind the performance. When I mind performance, I use BufferedReader. Never System.in directly. You can read more in the answers provided here https://stackoverflow.com/a/21698084/2477456.

I believe the answer is a combination between the 2 answers offered so far.
For a quick fix, #Arvind Kumar Avinash is very good.
Looking more in to the problem as #Valdrinium specifies alternatives might be considered.
I am sceptical on choosing #Arvind Kumar Avinash as definitive, although it solve the problem in this instance.
Can an admin help?

It's happening because of the dangling line break character. Just add System.in.read(); once again as shown below to consume dangling line break character e.g. (char) System.in.read() consumes just a but not the Enter character that you press after a.
public class Main {
public static void main(String[] args) throws java.io.IOException {
System.out.println("Menu: ");
System.out.println("Choice: ");
System.out.println("1: If/Else");
System.out.println("2: Switch");
for (int i = 0; i < 5; i++) {
chooseOption();
}
}
static void chooseOption() throws java.io.IOException {
char choice = (char) System.in.read();
System.in.read();// Add this line
switch (choice) {
case 'a':
System.out.println("Computer control statement: If/Else");
break;
case 'b':
System.out.println("Computer control statement: Switch");
break;
default:
System.out.println("No valid option");
}
}
}
A sample run:
Menu:
Choice:
1: If/Else
2: Switch
a
Computer control statement: If/Else
b
Computer control statement: Switch
a
Computer control statement: If/Else
b
Computer control statement: Switch
a
Computer control statement: If/Else

Related

Why terminal doesn't prompt another input for this JAVA code?

class test {
public static void main(String args[])
throws java.io.IOException {
char ch, answer = 'K';
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it: ");
ch = (char) System.in.read();
if(ch == answer) {
System.out.println(" *** YOU ARE RIGHT *** ");
else System.out.println("Please try again: ");
ch = (char) System.in.read();
}
}
}
I'm using command line to run this java program and I want the user to continuously be able to input something instead of having to run the program manually every time they guess it wrongly. Tried many ways but the second System.in.read() doesn't show a prompt instead the code just ends in terminal having to manually run the program again to play. I'm a beginner so I have trouble understanding.
For one, as #GhostCat mentioned, you should put brackets around your if and else cases, otherwise the second read will happen regardless of the if statement
if (ch == answer) {
// your if code here
else {
// your else code here
}
Second, if you want it run indefinitely until they give a right answer, you need some kind of loop. In this case, you probably want a while loop. This would replace the if statement
while (ch != answer) {
// ask for retry
}
// They were right!
The code after the closing bracket will only run once the condition of the while loop is false (in this case, when ch is equal to answer). Meaning, at this point you can handle the correct answer case. Meanwhile, if they input the wrong answer, the program will loop and they will be prompted to try again.
EDIT: As to why the original code wasn't waiting for a second input and just stopping, inputting the first character in the command line actually adds an extra carriage return/new line character to the end of input, so the second read immediately consumes this new line character and proceeds (which in the initial code there's nothing else to do, so it quits).
This will work:
import java.util.Scanner;
class test {
public static void main(String args[]) throws java.io.IOException {
char ch, answer = 'K';
Scanner s = new Scanner(System.in);
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it: ");
ch = s.next().charAt(0);
if(ch == answer){
System.out.println(" *** YOU ARE RIGHT *** ");
} else{
System.out.println("Please try again: ");
ch = s.next().charAt(0);
}
}
}
if(ch == answer)
System.out.println(" *** YOU ARE RIGHT *** ");
else System.out.println("Please try again: ");
ch = (char) System.in.read();
is the equivalent of
if(ch == answer) {}
System.out.println(" *** YOU ARE RIGHT *** ");
} else {
System.out.println("Please try again: ");
}
ch = (char) System.in.read();
Indentation has no effect semantically nor syntactically. It's just a convention but it has no effect on your program (in contrast to python).
You should loop the program:
while(ch != answer) {
ch = (char) System.in.read();
....
}
However, this lacks EOF handling. It's better to use something like this:
while(true) {
int ch = System.in.read();
if(ch < 0) {
System.out.println("Bye!");
}
if((char)ch == answer) {
System.out.println("YOU ARE RIGHT");
break;
}
System.out.println("Please try again: ");
}
Also, bear in mind that read() reads only one byte which depending on how you input the data can be confusing because terminals usually buffer input until you press enter... not all terminals do this but most do it. You might be better of with using System.console which provides a readLine method. However, System.console won't work if no console is attached to stdin (such as when piping input to stdin, but for your case that's not a problem because I don't think your program is intended to be used through pipes). You can use System.console.readLine() and then strip away unwanted characters using the trim method of String.

How to go back to upper position in a program

I am trying to make node based big integer calculator in Java, and I want to re print the menu of calculator after operations. I thought of using goto but it gives error saying goto byte expected.
I am new in java, so can any one help me with the below demo code-
up:
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result = 0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
default:
goto up;
}
Thank you, I just want to reprint the menu.
You should use a simple while-loop for that. Maybe create a boolean as the running condition and set it to false, when the user types something else than 1 or 2.
Java does not support goto, as it is a reserved keyword.
Also, IMHO, using goto is not a great way to write a program.
A better approach would be to write a function which displays the menu and call that function whenever you want. Or just use a do-while loop.
Here is a way to look at "goto" in a java environment, using your code as the example:
public void addUp() {
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result = 0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
default: addUp();
}
}
Java doesn't use goto as it doesn't really fit into the Object-Oriented concept (I faced the same problem years ago when I made the switch from Basic). So you'll have to reconsider your code's logic to implement a loop of some sort.
Something like:
do {
// add an exit option to the menu
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
System.out.println("3. EXIT");
// continue with the same logic you had before
} while (i !=3)
I hope that helps.
note: if you lookup the keyword goto in Java documentation, you'll see that it's reserved but it doesn't do anything. They probably reserved it as a placeholder for these situations

Trouble returning to command options using loops/ only one command is being run (JAVA)

This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.

break to lable as default case in switch statment not behaving logically

First thank you for reading. Also I'm very aware of how I can get this to work they way I want it to. I'm just experimenting and not getting expected results.
When I run this code I would expect that when I enter the letter X I would be asked
to try again and re-attempt to enter the letter B. Well, I am. However The program will then break to the start: label and process based on the new value of input we got in the
default case. If on my second attempt I enter the letter B, nothing gets executed in the
switch statement. If you enter the letter B on your second try, the program will print that you entered B and then the program will terminate. Why is this?
import java.util.Scanner;
public class Help
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the letter B: ");
char input = kb.nextLine().charAt(0);
start:
switch(input)
{
case 'B':
System.out.println("Nice Work!");
break;
default:
System.out.println("Try again: ");
input = kb.nextLine().charAt(0);
System.out.println(input);
break start;
}
}
}
The labeled break statement is meant for terminating loops or the switch statement that are labeled with the corresponding label. It does not transfer control back to the label. Your switch statement is simply falling through to the end of program, as it should.
A labeled break would only be helpful if you had nested switch statements and needed to break out of the outer one from the inner one.
See this for further information.
Use while cycle:
import java.util.Scanner;
public class Help
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter the letter B: ");
while(true)
{
char input = kb.nextLine().charAt(0);
switch(input)
{
case 'B':
System.out.println("Nice Work!");
break;
default:
System.out.println("Try again: ");
}
}
}
}

Multiple characters in a switch statement?

just to clarify this is hw.
In a project we're doing, a user isn't allowed to enter numbers or special characters (i.e ! # £ etc)
char letter;
String phonetic;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter: ");
letter = letter = kb.next().charAt(0);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
case '1,2,3,4,5,6,7,8,9,0':
{
System.out.println('No number input please!');
}
break;
}
The error is on
'1,2,3,4,5,6,7,8,9,0'
Eclipse says
invalid character constant
Isn't it really long winded if I have to enter all the numbers manually?
i.e. case '1': case '2':
even with
case 1,2,3,4,5,6,7,8,9,0:
It won't work.
Is there an shorter way to do this using switch statements?
Thank you!
Its because Case expression should be an int-compatible literal or a String from java 7.
case '1,2,3,4,5,6,7,8,9,0':
character literals are represented using single quotes. c, it should only be of one length, while your case doesn't reflect that, thus the error.
'1,2,3,4,5,6,7,8,9,0' this is not a legal character.
If you just wanna check if the character is only alpha, then use Charcter#isDigit(char) or Charcter#isLetter before the switch starts like in below code:
char ch= (Character.toUpperCase(letter);
if(!Character.isDigit(ch)) {
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
}
}
else {
System.out.println("no numbers please")
}
There's no easier way using case, what about?:
if ('0' <= letter && letter <= '9')
System.out.println('No number input please!');
Isn't it really long winded if I have to enter all the numbers manually?
Yes.
Is there an shorter way to do this using switch statements?
No.
Consider an if statement instead...
No, Java in this situation is not smart like C#. You need to write multiple lines for that. If you want to compare strings you need to use if statements. Also remember to use this code for comparision:
if("search".equals(string2)) {...}
You cannot compare by == this would only compare the memory addresses. Also note that I use the equals on the static string and not on the variable string2 because you code would break if string2 is null.
I hope this one enlighten you more.
Consider, your expression generates output as A , B, C, D, E, F, G, H, I, ...till Z. and you want to execute same method/function for all them.
Then, you can check the ascii values of the characters and modify your code to use if and for loop or else use switch as mentioned in the program in following example program.
Play around with code to learn more.
public class SwitchClass
{
public void method1()
{
System.out.println("Menthod 1");
}
public void method2()
{
System.out.println("Menthod 2");
}
public void method3()
{
System.out.println("Menthod 3");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
SwitchClass sw = new SwitchClass();
System.out.println("Enter the String:");
String input = in.next();
for(int i = 0; i<input.length(); i++)
{
switch(Character.toUpperCase(input.charAt(i)))
{
case 'A':
case 'B':
case 'C':
case 'U':
System.out.println(Character.toUppercase(input.charAt(i))+" Case calling");
sw.method1();
sw.method2();
sw.method3();
break;
default:
System.out.println("No number input please!");
break;
}
}
}
}

Categories