Java - Continuing if condition is met - java

Sorry if the code looks a bit messy from here. It's my first time posting, and wasn't sure how to format it for the site as I'm under a time constraint.
I'm in quite a bind here. I've been trying to figure this out for quite a number of hours now, but can't seem to get around to solve it. I'm new to Java, so don't mind the code if it's a bit out of order, messy, or if it's a bit too long for what it does. My problem lies in the first few lines, under:
"Scanner input = new Scanner(System.in);"
I was able to get the if statements working properly under the condition a number above or below 0 / 99 was entered, but if a number in between those two are entered, nothing happens. I searched in my textbook (Intro to Java Programming Comprehensive 10th edition), and can't seem to pinpoint the issue. Is there a way to have the program continue past the "if" statements and onto the lines of code that involve "input2"?
Thanks in advance!
package lab03;
import java.util.Scanner;
public class Lab03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer between 0-99: ");
int input1 = input.nextInt();
if (input1 < 0 || input1 > 99)
System.out.println(" Outside range. Please enter an integer between 0-99: ");
input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
System.out.println("Next, please enter another integer between 0-99: ");
int input2 = input.nextInt();
if (input2 < 0 || input2 > 99)
System.out.println(" Outside range. Please enter an integer between 0-99: `enter code here`");
input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);

I would put them in a while(scanner.hasNextInt()) loop and then if the condition is met call continue and it will go back to the beginning of the while loop.

The problem is that those statements aren't reachable because you call System.exit(). if statements execute the next line beneath them OR everything inside the braces. As you can see you have an open brace, but you don't actually post the code where the brace closes. That means that everything below the following line will execute, including System.exit().
if (input1 < 0 || input1 > 99) {
Your current program can be simplified to
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer between 0-99: ");
int input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: ");
}
input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
// everything below this will never execute
}
}

I think you are missing curly braces that define the scope of what happens as a result of your first if statement. You probably mean something like this
if (input1 < 0 || input1 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: ");
input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
}
}
but what is actually happening is that the program is waiting for a second try to input input1.

Basically, you've wrapped your "continued" condition within your "failed" condition if block...
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
// This is included within the failed block
// but will never execute because of the previous statement
System.out.println("Next, please enter another integer between 0-99: ");
int input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: `enter code here`");
}
input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
}
}
You should have a else condition which you want to execute when the if condition "fails" to be meet
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
} else {
// This is included within the failed block
// but will never execute because of the previous statement
System.out.println("Next, please enter another integer between 0-99: ");
int input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: `enter code here`");
}
input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
}
}
Remember {...} adds context to the code which it surrounds
Depending on what you want to achieve, you can also use a do-while loop to "trap" the user in a input loop, until they enter the correct value...
int input1 = -1;
do {
System.out.println("Please enter an integer between 0-99: ");
String text = input.nextLine();
try {
input1 = Integer.parseInt(text);
if (input1 < 0 || input1 > 99) {
System.out.print("Outside range. ");
}
} catch (NumberFormatException exp) {
System.out.println(text + " is not a valid numerical value");
}
} while (input1 < 0 || input1 > 99);
Now, remember, this will trap them until they enter a value between 0 and 99 inclusively, so you might want to consider adding a "escape" condition (ie "(type 'e' to exit) and then either break out of the loop or exit the program ;)

Your current code only works for numbers that are greater than 99 and less than 0. You need an else statement for numbers that are between 0 and 99 for the program to continue.
if (input1 < 0 || input1 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: ");
input1 = input.nextInt();
}else{
//Continue on with program
}
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);

Related

How to fix this random number guessing game use a do-while loop program?

Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}

Trouble appropriately constructing do while loops with correct conditions to run

I am struggling to correctly loop the code I have written to convert integers to roman numerals.
I have tried implementing a do while loop to run the code starting at "please enter an integer" and ending after my switch statement with the while part being: while(case "y" || "Y" == true )
Any help would be greatly appreciated. I have been searching through previous posts on stack overflow for a couple hours now and haven't been able to find anything that helps.
public class project8
{
/**
* Constructor for objects of class Project4
*/
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if (input < 0 || input > 3999){
System.out.println("Sorry, this number is outside the range.");
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
String userInput = in.next();
switch (userInput) {
case "N":
case "n":
System.exit(0);
break;
case "Y":
case "y":
break;
}
}
else if (input > 0 && input < 3999);
{ System.out.println(Conversion.Convert(input));
}
}
}
1) Your if - else if conditions are redundant. You can use a simple if - else as input can only be in that range or not. else if makes only sence if you had two or more ranges to check, e.g.
if(input > 0 && input < 3999){
...
}
else if (input > 4000 && input < 8000){
...
}
else {
...
}
2) You don't need a switch block instead use the user input in your while condition as you want to continue looping when user input is Y/y, i.e while(userChoice.equals("Y"))
3) Use a do - while loop as you want that your application to run at least on time
public static void main(String[] args) {
System.out.println("Welcome to my integer Roman numeral conversion program");
System.out.println("------------------------------------------------------");
System.out.println(" ");
Scanner in = new Scanner (System.in);
String choice;
do{
System.out.print("Enter an integer in the range 1-3999 (both inclusive): ");
int input = in.nextInt();
if(input > 0 && input < 3999){
System.out.println(Conversion.Convert(input));
}
else{
System.out.println("Sorry, this number is outside the range.");
}
System.out.println("Do you want to try again? Press Y for yes and N for no: ");
choice = in.next();
}while(choice.equals("Y") || choice.equals("y"));
}

Want to bullet proof while loop with try-catch

I have this hw problem - Write a program that reads a number and prints all of its binary digits: Print the remainder number % 2, then replace the number with number / 2. Keep going until the number is 0.
It successfully displays the binary digits, but I want to bullet proof it so that it won't crash when letters are used. It doesn't crash but I want to allow the user to enter another number without restarting the program. Any tips on how I can do this?
Scanner scanIn = new Scanner(System.in);
int number = 0;
System.out.print("Please enter a number: ");
try {
number = scanIn.nextInt();
} catch (InputMismatchException ime) {
System.out.println("Please only enter integers!");
number = 0;
scanIn.nextLine();
}
while (number > 0) {
System.out.println(number % 2);
number /= 2;
}
}
One approach is to surround your code in another while loop that iterates forever and breaks out of the loop when a certain condition is met. I also modified your code to repeatedly prompt for an integer if invalid input is entered.
Scanner scanIn = new Scanner(System.in);
int number = 0;
while(true) {
System.out.print("Please enter an integer, or 0 to quit: ");
// input verification
boolean valid = false;
while(!valid) {
try {
number = scanIn.nextInt();
valid = true;
} catch (InputMismatchException ime) {
System.out.println("Please only enter integers!");
System.out.print("Please enter an integer, or 0 to quit: ");
valid = false;
}
}
// break out of the loop if 0 is entered
if(number == 0) {
break;
}
while (number > 0) {
System.out.println(number % 2);
number /= 2;
}
}
You need 2 loops,
The first one will take an input until it is an integer (Integer.parseInt()) Surrounded by a try/catch
Then when you have confirmed an input that is an integer you begin your loop.

Multiple conditions for a Do..While Loop in Java

right basically I am implementing a do while loop. A user is asked to enter a value, and a value is returned back - this is using nested If statements within the do loop. At the end of the loop I am asking whether they want to enter another value, yes or no basically. Here is my code below, I essentially need a way of when the question is asked at the end to perform like...
"Would you like to enter another value?" - "no" - terminates
"Would you like to enter another value?" - "yes" - loop around
"Would you like to enter another value?" - any other value e.g. "maybe" - ask the question again.
The code:
import java.util.Scanner;
public class More_Grades {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String A = "Your grade is: ";
int grade = 0;
String y;
do {
System.out.println("Please Enter Your Grade: ");
grade = scan.nextInt();
if (grade < 40) {
System.out.println(A+"Fail");
}
else if (grade >= 40 && grade <= 49) {
System.out.println(A+"3rd");
}
else if (grade >= 50 && grade <= 59) {
System.out.println(A="2/2");
}
else if (grade >= 60 && grade <= 69) {
System.out.println(A+"2/1");
}
else if (grade >= 70 && grade < 100) {
System.out.println(A+"1st");
}
else if(grade >100) {
System.out.println("Invalid grade,Enter a value below 100.");
}
System.out.println("Would you like to Enter Another? Y/N");
y = scan.next();
}while (y.equals("yes"));
scan.close();
System.out.println("Thank-You.");
}
}
You just need another do-while inside your current loop to repeat the question:
do {
...
do {
System.out.println("Would you like to enter another? (yes/no)");
answer = scan.next();
} while (!Arrays.asList("yes", "no").contains(answer));
} while (answer.equals("yes");

how do i prevent the scanner from accepting strings, negative integers, or numbers less than 2?

How do i prevent negative numbers from being returned by this method?
I have tried setting the while loop to
(n < 0 && n != 0)
to no avail.
Here is my code for the method currently:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
I have also tried to put my if statement inside the try block like this:
public int getNumber() {
int n = 1;
while(n < 2 && n != 0) {
try {
System.out.print("Enter the upper bound(0 to exit): ");
n = scan.nextInt();
if(n < 0) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
n = scan.nextInt();
}
break;
}
catch(java.util.InputMismatchException e) {
System.out.print("Error, please enter a valid number greater than 0(0 to exit): ");
scan.next();
continue;
}
}
return n;
}
When i put the if statement inside the try block, i started to input negative numbers consecutively to test. It worked for the first time i entered a negative number, then gave me a blank scanner input line, and then finally allowed a negative number to return, which in turn screws the rest of my program up. Please help, im a first semester student in java. Thank you.
You input a negative number, then it goes into your n<0 if and you put in another one and then break out of the loop.
Try changing your if to:
while(n < 0)
Do not use while loop condition for validating input. Your loop condition does not give your program a chance to accept and check the number before making a decision to keep or to reject the entered value. As the result, your program starts prompting end-users with an error message even before they typed anything.
You should not call nextInt without first checking if the Scanner is ready to give you an int by calling hasNextInt.
Finally, you need a rejection loop to throw away non-integer input until hasNextInt succeeds. This is usually done with a nested while loop, which prints an error prompt, and throws away the entered value.
The overall skeleton for reading and validating an int looks like this:
System.err.println("Enter a number between 0 and 5, inclusive");
int res = -1;
while (true) {
while (!scan.hasNextInt()) {
System.err.println("Incorrect input. Please enter a number between 0 and 5, inclusive");
scan.nextLine(); // Discard junk entries
}
res = scan.nextInt();
if (res >= 0 && res <= 5) {
break;
}
System.err.println("Invalid number. Please enter a number between 0 and 5, inclusive");
}
// When you reach this point, res is between 0 and 5, inclusive
couldn't you just check for 'hasNextInt', then test the input.
int n = 0;
System.out.println("Enter a number between 0 and 5);
while (scan.hasNextInt()) {
n = scan.nextInt();
if (n >= 0 && n <= 5) {
break;
}else{
//prompt error message or handle however you wish
}
}
return n;
likewise you could also force with an unsigned integer.
Final code to not return negative integers or strings:
public int getNumber() {
System.out.print("Enter the upper bound(0 to exit): ");
int nums = 1;
while(true) {
while(!scan.hasNextInt()) {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
nums = scan.nextInt();
if(nums > 2 || nums == 0) {
break;
} else {
System.out.print("Error. Please enter a valid integer greater than 1(0 to exit): ");
scan.nextLine();
}
}
return nums;
}
Thanks a million you guys!

Categories

Resources