Want to bullet proof while loop with try-catch - java

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.

Related

While loop is not looping back to the start with a new input from the user

I have been trying to perfect this program on my own, and I just can't see what I'm doing wrong. The aim of this program is to do these things.
1) ask user for number
2) if the number is positive, print out the number
3) if the number is also a prime number, print that it's also a prime number
4) keep doing the above things until a negative number is inputed by the user.
The problem is, the program only works and determines if a number entered is a prime number or not, at the beginning. After that, when the user is asked for another number (if it's greater than 0), the program just doesn't loop back to the beginning to determine if the number is prime. Instead, it just sticks to what the value at the beginning was determined to be (prime or not prime) and prints out the same statement as what you would get for the first value, for the second. I want it to reevaluate the value every time to see if the number is prime or not, until the user inputs a negative number.
P.S. This is my first year going for a C.S degree. I find programing really fun and challenging (the concept). But I embrace it that challenge and find a sense of accomplishment every time I work through these problems.
import java.util.Scanner;
public class Prime3 {
public static void main(String[] args) {
int userNum;
int i = 2;
boolean isPrime = true;
Scanner input = new Scanner(System.in);
// Ask user for initial number
System.out.println("Please enter a number.");
userNum = input.nextInt();
// Determining whether or not number entered is prime
while (i <= userNum/2) {
System.out.println("Checking if " + i + " is a multiple of n");
if (userNum%i == 0) {
System.out.println(i + " is a multiple of " + userNum);
isPrime = false;
break;
}
i++;
}
// Print out user number if the number is positive.
while (userNum > 0) {
System.out.println("You entered the number, " + userNum);
if (isPrime) { // If it's a prime, state that it's a prime
System.out.println("No even multiples found. " + userNum + " is a prime number");
}
userNum = input.nextInt();
}
System.out.println("Invalid input. Program now ending.");
System.exit(0);
}
}
Well, I see the problem. You should move while (userNum > 0) to the top. So your final code should look something like this:
public class Prime3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Ask user for initial number
System.out.println("Please enter a number.");
int userNum = input.nextInt();
while (userNum > 0) {
int i = 2;
boolean isPrime = true;
// Determining whether or not number entered is prime
while (i <= userNum / 2) {
System.out.println("Checking if " + i + " is a multiple of n");
if (userNum % i == 0) {
System.out.println(i + " is a multiple of " + userNum);
isPrime = false;
break;
}
i++;
}
// Print out user number if the number is positive.
System.out.println("You entered the number, " + userNum);
if (isPrime) { // If it's a prime, state that it's a prime
System.out.println("No even multiples found. " + userNum + " is a prime number");
}
userNum = input.nextInt();
}
System.out.println("Invalid input. Program now ending.");
System.exit(0);
}
In general construction of this code is error prone. You should do something like:
set userNum = 0
enter while (userNum >=0)
Call method which check if userNum is positive, if yes print
Call method which check if userNum is prime, if yes print
get new value from input console into userNum
end body of loop.
If you follow there should be no problem.

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

Checking for negative numbers in Array and re-prompting for correct input

The idea is to create an average for money made in a week by day and my average must be calculated in a method that is called in the main method. That is the easy part, but the part I'm stuck on is if a number less than zero is entered it should give me an error message and re-prompt the user for a better value. I'm not looking for a handout here just for someone to tell me what I've been doing wrong if it is simple and easy or a pointer in the right direction.
import java.util.*;
public class weeklyAveragesClient2
{
public static void main(String [] args)//output averages in format
{
averageCash();
}
public static double averageCash()//use array and loop to calculate weekly average
{
double [] cashMoney;
cashMoney = new double[7];
Scanner scan = new Scanner(System.in);
int j = 0;
String s = "ERROR";
while (j < 7)
{
double num = cashMoney[j];
if (num == 0)
{
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
}
else if(num > 0)
{
System.out.print("Please enter an amount for day " + (j+1) +": ");
cashMoney[j] = scan.nextDouble();
j++;
}
else
{
System.out.println("Error: negative number please enter a number > 0");
}
}
System.out.println("Calculating...");
double sum = 0;
for (int i = 0; i < cashMoney.length; i++)
{
sum = sum + cashMoney[i];
}
double average = sum / (double)cashMoney.length;
System.out.println("Average: " + average);
return average;
}//end averageCash
}//end class
I've added some comments that will hopefully provide food for thought.
// This will *always* be zero at first because you haven't called scan.nextDouble() yet
// and zero is the default value. So when you run the program, it will output "Error
// please enter a number > 0" before doing anything else
if (num == 0) {
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
System.out.print("Please enter an amount for day " + (j + 1) + ": ");
cashMoney[j] = scan.nextDouble();
j++;
} else {
// If we get into this state, the user will never be invited to enter
// another number, since the last entered number was negative, so
// num == 0 is false, and
// num > 0 is false, so
// we'll end up back here. In fact, you'll enter an infinite loop and
// this message will be printed over and over again.
System.out.println("Error: negative number please enter a number > 0");
// cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}
Please also consider indenting your code correctly. It will greatly increase readability. If you're using an IDE like Eclipse, you can select Source > Format.

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