Do while Running more times - java

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

Related

"How can I request an if-else input after a switch statement?"

After a switch statement I would like to request a 'Y' or 'N' statement and print out a statement for the respective response. How can I declare the input char, then provide a scanner input for that value?
I've tried using input as a char and an integer. I've also tried using the boolean method as well.
import java.util.*;
public class Dowhile {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
System.out.println("0,1,-1: ");
x = in.nextInt();
switch(x)
{
case 1:
System.out.println("Positive");
break;
case -1:
System.out.println("Negative");
break;
case 0:
System.out.println("Zero");
break;
default:
System.out.println("You're a bad person!");
break;
}
char input = (('Y'||'N'));
System.out.println("Enter 'Y' or 'N'");
in.nextInt();
if(input = 'Y')
System.out.println("OK");
else
System.out.println("wow");
}}
I expect the output to be the println response for the respective input.
I would try something like this:
System.out.println("Enter 'Y' or 'N'");
char input = in.next("Y|N").charAt(0);
if('Y' == input)
System.out.println("OK");
else
System.out.println("wow");
The in.next("Y|N") part requests either a 'Y' or a 'N' (the String "Y|N" is interpreted as a regular expression) and returns the result as a String. The charAt(0) function returns the first (and only) character from this String.
Note that this approach throws an exception if you enter neither 'Y' nor 'N'.
If you want to avoid the exception you can use the following code snippet:
System.out.println("Enter 'Y' or 'N'");
char input = in.next(".").charAt(0);
if('Y' == input)
System.out.println("OK");
else if ('N' == input)
System.out.println("wow");
else
System.out.println("You haven't entered a valid character");
But beware, because your first call to in.nextInt() will still fail if someone enters something that isn't an integer.
Assuming you don't need to expand your program to do anything other than print to the console, the following would be the approach I'd take:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("0,1,-1: ");
int x = in.nextInt();
System.out.println(
x == 1 ? "Positive" :
x == -1 ? "Negative" :
x == 0 ? "Zero" :
"You're a bad person!"
);
System.out.println("Enter 'Y' or 'N'");
System.out.println(in.next().equalsIgnoreCase("Y") ? "OK" : "wow");
in.close();
}
Ternary operators are used for checking the conditions and printing to the console without switch or if statements.

Scanner needs inputs twice before continuing

Hey guys i have got a small weird problem here, i am asking the user to input their menu choice and depending on what they choose it calls a certain method.
I have used scanner.next() after some googling but for some reason only when i enter 1 or 2, i press enter and then press say 1 again and then it actually works. But what is weird that it calls options 3, 4, 5 and 6, immediately without me having to input the number twice.
I have tried with scanner.nextLine() after the scanner.nextInt() and that just leaves me having to put my option 1 or 2 in with no result.
while(exit == 0)
{
System.out.println("\n");
System.out.println("Menu 1: Display fullname of the user \n");
System.out.println("Menu 2: Display of user information \n");
System.out.println("Menu 3: Change password \n");
System.out.println("Menu 4: List all of users in the library full name\n");
System.out.println("Menu 5: Search for a book\n");
System.out.println("Press 6 to search for a books location in the library\n");
System.out.println("Press 0 to exit\n");
System.out.println("Enter choice: ");
int menuChoice = scanner.nextInt();
scanner.next();
if(menuChoice == 1)
{
displayUserFullName();
}
else if(menuChoice == 2)
{
displayUserInformation();
}
else if(menuChoice == 3)
{
menuForChangePassword();
}
else if(menuChoice == 4)
{
displayAllUserInSystem();
}
else if(menuChoice == 5)
{
searchBookByISBN();
}
else if(menuChoice == 6)
{
searchBookLocation();
}
else if(menuChoice == 0)
{
exit = 1;
}
}
Thank you in advance!
int menuChoice = scanner.nextInt();
scanner.next();
Read the javadoc for scanner. It waits for user input:
public String next(): [..] This method may block while waiting for input to scan
So in your program, you say: wait for user to type and int, then wait for user to type something.
Remove the scanner.next(); and it should work.
Scanner is a class parsing single tokens, like nextInt, nextDouble, nextToken (String). With corresponding testing methods: hasNextInt and so on.
All this parsing you do not need, so use nextLine for an entered line, or an other Reader class (InputStreamReader, BufferedReader).
Also you may utilize switch instead of if else if.
String menuChoice = scanner.nextLine();
switch (menuChoice) {
case "1":
displayUserFullName();
break;
case "2":
displayUserInformation();
break;
case "3":
menuForChangePassword();
break;
case "4":
displayAllUserInSystem();
break;
case "5":
searchBookByISBN();
break;
case "6":
searchBookLocation();
break;
case "0":
exit = 1;
break;
default:
System.out.printf("Unknown choice: '%s'%n", menuChoice);
}
menuChoice will contain the entire line, without line ending.
You might use an int with Integer.parseInt(menuChoice) but this would throw a NumberFormatException on wrong input, aborting your program. Scanner.nextInt would hang too, actually needing an hasNextInt().

Conflicts between 'for' and 'switch'?

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

switch loops? while loops? currency converter program java

I am new to switch loops and am having multiple problems with this currency converter program I am trying to create.
First, I would like to loop the case 1 where the user keeps entering values until they type -1 so it stops and moves on. At the moment, it does not do this. Once I've entered the GPR values on switch 1 and then loop back to the menu keeping the original GPR stored values.
Code is here:
import java.util.Scanner;
public class Conversion {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int Choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
System.out.println("Please choose an option:");
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
Choice = input.nextInt();
switch (Choice) {
case 1:
while (!exchange.equals("-1"));{
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange (Type '-1' to stop) ");
}
case 2:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in euros are" + poundDollars);
case 3:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in euros are" + poundYen);
case 4:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in euros are" + poundRupees);
case 5:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in euros are" + poundEuro);
case 6:
break;
}
input.close();
exchange.close();
}
}
switch is not a loop. It's a branching statement like if. It has break, but that is only present because you can "fall through" to the next case statements. Currently you are falling through on most of them, because you've forgot putting in the break statements between the cases.
A switch statement isn't a loop. Consider it a replacement for a series of else-if statements. Your code actually reads more like this:
if(Choice == 1)
{
}
else if(Choice == 2)
{
}
else if(Choice == 3)
{
}
else if(Choice == 4)
{
}
else if(Choice == 5)
{
}
else if(Choice == 5)
{
}
However, your switch cases should be terminated with break statements. If one is not, unlike the else-ifs above, execution will fall-through to the next case and execute the code in that one too, until it finally reaches a break statement or goes through all the cases.
What you want is for your while-loop to wrap AROUND your switch statement, but you should fix your while-loop first, since you terminated it with a semicolon, it is infinite. While-loops don't need a semicolon at the end, unless you do not have a body for it but you do have some side-effect happening in the conditional check that will eventually cause it to end.
while( blah )
{
switch( blah )
{
case 1:
// Do stuff for this case
break;
case 2:
// Do stuff for this case
break;
default:
// Do stuff when no case is matched
break;
}
}
I think you're a bit confused. As noted by immibis in his comment, switch statements are not loops, so you need to enclose the switch statement inside a loop.
Then, you're missing the break statements at the end of each case. Quoting the Java tutorials:
Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Your program should be something like this:
public static void main(String[] args) {
// Variable definitions
while(true) { // This is a little trick to force the application to repeat
// a task until you explicitly break the loop
// Code to print your menu
choice = input.nextInt();
if(choice == -1 || choice == 6)
break; // Break the while loop if choice is -1 or 6
switch(choice){
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
If you don't put those break statements at the end of each case block, your program will fall through every option.
Please read:
The Java tutorials: The switch statement
The Java tutorials: The while statement
Another option would be something like this:
public static void main(String[] args) {
// Variable definitions
/*
Now let's use a labeled loop
*/
menu: while(true) {
// Code to print your menu
choice = input.nextInt();
switch(choice){
case -1: // Nothing goes here, so the execution will fall through
// to the next case
case 6:
break menu; // This will break the menu loop.
// Since the previous case simply falls through to
// this one, this will happen if choice is
// either -1 or 6
case 1:
// Your code for option 1
break;
case 2:
// Your code for option 2
break;
// More cases
default:
System.out.println("You must enter an option between 1 and 6!");
break; // Not strictly needed
}
}
}
More reading:
The Java tutorials: Branching statements

When I run my program i get the error java.lang.StringIndexOutOfBoundsException: String index out of range: 0

here is my code
import java.io.*;
import java.util.*;
public class weightOnOtherPlanets {
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine( );
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " " ;
switch(p){
case 'A':
case 'a':
System.out.println(answerPhrase +(.091*weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720*weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865*weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612*weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
}
I have used almost the exact same code for another similar practice project and it worked just fine. When i run the program it goes to the point where it asks for a weight input, then it displays the choice list, but with the error message exception in "main":
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at weightOnOtherPlanets.main(weightOnOtherPlanets.java:14)
I don't know why it gives this error before allowing keyboard input for String choice.
This is because of the way Scanner scans lines.
After you enter a double (the weight), you press Return. This tells System.in to take all the characters you entered and pass them to the scanner. The scanner then reads the part that interests it - the double number - but leaves everything else waiting for the next operation.
This means the Return you pressed - the end-of-line - is still there. Now, the next thing is nextLine(). The scanner sees it, and it reads all the characters it has until it finds an end-of-line. But as we said, the end-of-line is right there. So it reads that, and gives you all the characters it found before it. Which is none at all, because there were no other characters between the double number and the end-of-line.
This means you get an empty string. And an empty string doesn't have a character at position 0, because that would mean it was not empty.
So what you should do is, after receiving the double, you should add a kbReader.nextLine(); - just like that, without putting the value anywhere. This will skip the end-of-line you entered for the double, and then you'll get the next line properly.
When you do your menu reading, though, you should be checking that the string is not empty before you call charAt(0). After all, the user can decide to press Return rather than make a valid choice. So your system should either ignore that or tell him that it's not a legal input, rather than fail with an exception.
You call nextDouble(); and after that you call nextLine() to get your answer phrase. But that call to nextLine(); will only consume the rest of the line on which you entered your double and it will be empty, therefore choice.charAt(0); will throw an exception.
Try doing something like this to consume the rest of the line and then call the nextLine() to get the answer phrase.
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
kbReader.nextLine(); // Consume the rest of the line
// ...
String choice = kbReader.nextLine(); // Get the actual input
char p = choice.charAt(0);
try this:
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine();
if (choice.isEmpty()) {
choice = kbReader.nextLine();
}
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " ";
switch (p) {
case 'A':
case 'a':
System.out.println(answerPhrase + (.091 * weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720 * weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865 * weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612 * weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
You need to read for input differently. That's why you are throwing an exception.
char p = choice.charAt(0); // why not just do a string comparison instead?
is where the error comes up. This is because choice is null / has no charAt(0).
Irregardless I would use something like this instead
char p = ''
while(in.hasNext()) {
String input = in.nextLine();
if (p.length()>0){
p = choice.charAt(0);
}
//do whatever you wanted to with p
This should give you the behavior you are looking for.
Don't forget to consider changing the double input to work roughly the same though.

Categories