This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm doing some basic homework, and it's honestly all stuff I know. But I decided to jazz it up a little, and something I'm missing is causing an unexpected error.
The idea is to use a while loop which asks if the user would like to do something. So long as they say yes, the loop continues the operations that it holds (in this case rounding a decimal to an int). However, as soon as I enter yes, or anything really, the loop breaks there and won't continue on to the rounding portion.
public class DecimalRounder {
//Main class method that starts and ends the program. It is prepared to throw an IO exception if need be.
public static void main(String args[])throws IOException
{
//Main initializes a new reader to take input from System.in
InputStreamReader rawInput = new InputStreamReader(System.in);
//Main then initializes a new buffer to buffer the input from System.in
BufferedReader bufferedInput = new BufferedReader(rawInput);
//Main initializes other used variable
double castInput = 0.0;
String contin = "yes";
//Program then sets up loop to allow user to round numbers till content
while (contin == "yes")
{
//Program asks user if they'd like to round.
System.out.println("Would you like to round? Type yes to continue... ");
contin = bufferedInput.readLine();
//If user says yes, rounding begins. ERROR FOUND HERE?
if (contin == "yes") //INPUT "yes" DOESN'T MATCH?
{
//Program then requests a decimal number
System.out.println("Please enter a decimal number for rounding: ");
String givenLine = bufferedInput.readLine();
//rawInput is worked on using a try catch statement
try {
//givenLine is first parsed from String into double.
castInput = Double.parseDouble(givenLine);
//castInput is then rounded and outputted to the console
System.out.println("Rounded number is... " + Math.round(castInput));
//Branch then ends restarting loop.
}catch(Exception e){
//If the data entered cannot be cast into a double, an error is given
System.err.println("That is not a roundable number: " + e.getMessage());
//And branch ends restarting loop.
}
}
}
System.out.println("Have a nice day!");
}
}
Use .equals instead of == to compare strings in JAVA.
Try this :
contin.equals("yes")
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}
This question already has answers here:
How to use .nextInt() and hasNextInt() in a while loop
(3 answers)
Closed 6 years ago.
I have this code that I want to run to solve a problem which needs a three user inputs, and I used Scanner class for this:
public static void main(String[] args) {
int M = 0;
int A = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please, insert the normal dose in ml:");
M = input.nextInt();
System.out.println("Please, insert the set of experiments (3 integers per line, stop by 0 0 0):");
try {
while (input.hasNextInt()) {
System.out.print(input.hasNext());
int i = input.nextInt();
A += i;
System.out.println(A);
}
} catch (Exception x) {
System.out.print(x.getMessage());
}
System.out.println("Loop ended");
}
The strange thing is that input.hasNextInt() gets stuck or something after I Insert the three values, It seem that it keeps looping or something even though there are no inputs in the console, can some one provide some help for me?
That's because input.hasNextInt() waits until a integer value is available. It would return false if an alphanumeric value was informed.
You have to define another way to break while loop, maybe with a counter or, like your message says, checking whether 3 values are equal to 0.
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am currently working on some Java code in Eclipse and trying to use a try-catch statement inside of a do-while statement. My current code is as follows:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
public class GG_HighLowInvalid{
public static void main(String[] args){
Scanner cg = new Scanner(System.in);
//Assign and define variables
int guess, rand;
guess = 0;
rand = 10;
//Create loop
do
try{
guess = 0;
//Ask for a guess
System.out.print("Enter your guess: ");
//Record the guess
guess = cg.nextInt();
}
catch(InputMismatchException exception){
System.out.println("Your guess must be an integer.");
}
while (guess != rand);
}
}
When I put in any number, the code works fine and will loop to ask for another input and when 10 is entered, the code stops as it is supposed to (because guess becomes equal to rand). However, if I put in anything that is not an integer (such as "No"), an infinite loop occurs where the output prints the following:
"Your guess must be and integer."
"Enter your Guess: Your guess must be an integer."
"Enter your Guess: Your guess must be an integer."
"Enter your Guess: Your guess must be an integer."
repeating forever until the program is externally terminated.
Since the while statement is (guess != rand), why is a non-integer causing this infinite loop? Shouldn't the manual input under the try-statement be called again? Any assistance in understanding this would be greatly appreciated. Also, I am pretty new to Java, so sorry in advance if I am having simple issues.
When a scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
Currently, your Scanner is not moving ahead to read the next input but reading the same continuously. You have to explicitly call some method which can read this incorrect value which was not expected. For example, scanner.next() call in catch block can avoid this infinite loop.
Use the following code:
catch(InputMismatchException exception){
cg.next();
System.out.println("Your guess must be an integer.");
}
After you have unsuccessfully read buffer its value isn't emptied and next time when it came to cg.nextInt() it tries to read same wrong value, and you went to loop. You need "to empty buffer", so next time it will read correct value.
You dont need to use a try catch statement. You just have to check if it is an integer or not with the hasNextInt() method of your object scanner. This is an example, it will solve your problem:
public static void main(String[] args) {
Scanner cg = new Scanner(System.in);
boolean valid = false;
//Assign and define variables
int guess, rand;
guess = 0;
rand = 10;
//Create loop
do{
System.out.println("Enter your guess: ");
if(cg.hasNextInt()){
guess = cg.nextInt();
valid = true;
}else{
System.out.println("Your guess must be an integer.");
cg.next();
}
}while (!valid || guess != rand);
}
Try resetting your variable "guess = 0" in catch block.
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am making a method in order to get how many numbers the user wants to sum together. aka if they want to sum the numbers 1 2 and 3. they would want to sum 3 numbers together. So when i ask them how many they want to sum together, I use a try - catch in order to catch if they enter a decimal place. Because you cant add together 3.5 numbers you can add 3 numbers or 4. problem is if the user enters a decimal, the program will infinite loop run everything but what is in the try statement. How can i fix this?
Here is the code for the method:
private static int requestMaxInputForFloat(Scanner scanner){
boolean appropriateAnswer = true; // assume appropriate catch not appropriate to loop again
int howManyInputs = 1000000; // hold value to return how many inputs. if this value we will not run.
//request an appropriate number of inputs until appropriate answer = true;
do
{
appropriateAnswer = true; //if looped again reset value to true
try{
System.out.print("How many decimal place numbers would you like to sum? ");
howManyInputs = scanner.nextInt();
}catch(Exception e){
System.out.println("Sorry but you can only request to average a whole number set of data.\nTry Again.");
appropriateAnswer = false;
}//end of try-catch
if (howManyInputs <= 0) //invalid answer
{
System.out.println("Sorry but " + howManyInputs + " is equal to or below 0. Please try again.");
}else{
appropriateAnswer = false;
}
}while(!appropriateAnswer);//end of while loop
return howManyInputs; //return the value
}// end of getMaxInput
Add scanner.nextLine(); in the catch block. I think the problem is that if nextInt() gets an error, the scanner's "pointer" is still pointing at a bad character, and if you just try nextInt() again, it will try to scan the same bad character over again. You have to do something to make the scanner skip over it. Here, you want to just throw away whatever the user typed in, so nextLine(), which skips over the entire remainder of the input line, is the most appropriate.
One other thing: I'd change
if (howManyInputs <= 0) //invalid answer
to
if (appropriateAnswer && howManyInputs <= 0) //invalid answer
Otherwise, if the user types in -1, then the loop will go back and howManyInputs will still be -1; then if the user types 3.5, you'll get the exception but you'll get a second error message because howManyInputs is still -1 left over from the previous loop. You don't need to test howManyInputs if you already know there was an input error.
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don't get an error if a letter is entered. I tried this:
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
try
{
choice = stdin.nextInt();
validResponce = true;
}
catch (java.util.InputMismatchException ex)
{
System.out.println("I did not understand what you said. Try again: ");
}
}
but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.
And yes, I am new to Java
nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().
Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.
Try using
boolean isInValidResponse = true;
//then
while(isInValidResponse){
//makes more sense and is less confusing
try{
//let user know you are now asking for a number, don't just leave empty console
System.out.println("Please enter a number: ");
String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user
//test if user entered a number in that line
int number=Integer.parseInt(lineEntered);
System.out.println("You entered a number: "+number);
isInValidResponse = false;
}
//it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception
catch (Exception e){
System.out.println("I did not understand what you said. Try again: ");
}
}
Because of common topic of avoiding negative conditionals https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/