How to make a number invalid - java

Create a new program called minusSentinel2.
Prompt the user to enter whole numbers between 1 and 100. Allow the user to enter as many numbers as desired.
If an invalid number is entered, print "Invalid entry." Prompt the user again until a valid number is entered.
Once -1 is entered, the program stops and prints the largest number entered with the text "The largest number entered is: "
I am having some trouble on the "Invalid entry." part. When I type a number greater than 100, "Invalid entry." does not get printed. How do I fix this? Thank you!
import java.util.*;
public class minusSentinel2
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter a number between 1-100 (type -1 to quit):");
int number = console.nextInt();
int max = number;
if (number < 1 && number > 100)//chekcs if value is valid
{
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
console.next();
}
while (number != -1)
{
number = console.nextInt();
if (number > max)
{
max = number;
}
}
System.out.print("The largest number entered is: " + max);
}
}

Firstly, I suggest you to don't copy and paste what we ask you to do, and just reformulates with only necessary parts for us.
For your issue, this condition is wrong:
if (number < 1 && number > 100)
It correspond to "lower than 1 and bigger than 100".
So, instead of && (and) operator, use || (or) operator like that :
if (number < 1 || number > 100) {
// it's not valid because lower than 1 or greater than 100
}
Finally, what you are doing seems to have another issue.
If you enter an invalid number, it will ask again only one time, and not same the new value. So, I suggest you to use while loop like that :
int number = 0;
while(number < 1 || number > 100) {
number = console.nextInt();
if (number < 1 || number > 100) {
System.out.println("Invalid entry.");
System.out.println("Enter a number between 1-100 (type -1 to quit).");
}
}
int max = number;
To conclude, this is the full code:
Scanner console = new Scanner(System.in); // create scanner
int number = 0; // create new variable that will be used outside of while loop
while (number < 1 || number > 100) { // while the number isn't valid
System.out.println("Enter a number between 1-100 (type -1 to quit):");
number = console.nextInt(); // wait for user input
if (number == -1) { // stop program
console.close();
return;
} else if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
}
}
System.out.println("Now enter all number that you want. End with -1.");
int max = number; // create new max value
while (number != -1) {
number = console.nextInt();
if (number < 1 || number > 100) { // number invalid
System.out.println("Invalid entry.");
} else if (number > max) { // if number is upper than current one
max = number;
// here you can do something like that:
// System.out.println("New max value: " + max);
} else {
// the value is value but not upper than current one, so we can write:
// System.out.println("This value isn't upper to " + max);
}
}
System.out.print("The largest number entered is: " + max);
console.close();

Related

Trying to return user to scanner to re enter a number if value falls out of range (<25)

Im trying to configure my code to tell the user to re enter a number, taking them back to the scanner if it falls outside of my specified range of 25
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0)
System.out.println("Positive numbers only");// if number entered is negative
else if (number > 25)
System.out.println("Number to large to print");
else if (number <= 1)// if number entered is 0 or 1
System.out.printf("The factorial of " + number+ " is equal to " + factorial);
else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial*mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and storing again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
}
To simplify the logic, you could extract it to the separate method. The logic itself is pretty strightforward:
in loop
ask a number
check if the number within the bounds
if not repeate or return if yes
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int num = getNumberWithin(scan, 1, 25);
}
private static int getNumberWithin(Scanner scan, int lo, int hi) {
while (true) {
System.out.format("Enter a number between %d and %d: ", lo, hi);
int num = scan.nextInt();
if (num >= lo && num <= hi)
return num;
System.err.format("The number should be between %d and %d\n", lo, hi);
System.out.println();
}
}
boolean correctInputn = false;
while(!correctInputn)
{
long number;// declares variables for storing number
long factorial = 1;// declare variable for storing factorial
System.out.println("Enter a number between 1 and 25"); // tells user to enter number
number = scanner.nextLong();
if (number <0) {
System.out.println("Positive numbers only"); // if number entered is negative
correctInputn = false;
continue; // if user enters number less than 0 loops back to code start
} else if (number > 25) {
System.out.println("Number to large to print");
correctInputn = false;
continue; // if user enters number over 25 loops back to code start
} else {
// if user enter 10, counter starts at 10 and runs to two
for(long mynumber = number; mynumber >= 1; mynumber--) {
factorial = factorial * mynumber; // mynumber would contain different values and that is multiplied by value present in factorial value and stored again in factorial variable
}
System.out.println("The factorial of " + number +" is equal to " + factorial);
break;
}
}

Java keeping highest number

int number = 0;
int score = 0;
while (true) {
Scanner input=new Scanner(System.in);
System.out.println("Please enter mark :");
number = input.nextInt();
Scanner mark=new Scanner(System.in);
score = mark.nextInt();
if (number > score ) {
System.out.println("Highest mark:" + number);
}
else if (number > 100) {
System.out.println("Invalid enter number 0-100");
}
else if
(number < 0){
System.out.println("Invalid enter number 0-100");
if(input.equals("quit")){
break;
Greetings, I would like to know how to keep the highest mark and the lowest mark after the student enters the number. and only to allow to enter numbers between 0-100. Thank you
You'll need two variables to keep track of the highest and lowest marks. Since you want your marks to be between 0 and 100, you can give starting values of the two variables -1 and 101 respectively:
int max = -1;
int min = 101;
-1 is not a reachable value and is lower than all the reachable values so any value in the given range is bigger than it which makes it perfect for a starting value for the max variable. If it starts from 101, no value in the range is bigger so the variable won't change. If the variable is 50 for exmaple, the values in the range 0-50 aren't bigger than 50 and they will be missed. The same logic can be done to see why I chose the value of 101 for the min variable.
Now you can enter marks and keep track of the highest and lowest one:
Scanner sc = new Scanner(system.in);
while (true) {
int mark = sc.nextInt();
if (mark > max) {
max = mark;
}
if (mark < min) {
min = mark;
}
}
Now the highest and lowest marks will be kept in the max and min variables respectively.
To implement the exit logic you can have the user to input a value outside the range and this will exit from the loop:
if (mark < 0 || mark > 100) {
break;
}
This if statement has to be put before the checking for highest and lowest mark because you don't mant to keep trak of such values.
This is the final code:
int max = -1;
int min = 101;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a value between 0 and 100. If the number is outside this range, the entering will stop.");
int mark = sc.nextInt();
//Exit logic
if (mark < 0 || mark > 100) {
//Closing the Scanner object (Not necessary but recommended)
sc.close();
break;
}
//Comapring
if (mark > max) {
max = mark;
}
if (mark < min) {
min = mark;
}
}
To update the score you just need to update your score.
if (number > score ) {
score = number; //update your score
System.out.println("Highest mark:" + number);
}
You should be able to solve this yourself tho.

how to check in java that input is an integer and is in certain range by using hasNextInt()

I want a user to enter a number which is an int and is between 1 and 8. I want to keep prompting the user until the number is between 1 and 8 and it is an integer.
What I've tried:
System.out.println("Enter number between 1 and 8");
while(!console.hasNextInt())
{
System.out.println("not valid try again between 1-8");
console.next();
}
int number = console.nextInt();
while (number < 1 || number > 8)
{
System.out.println("number is not between 1 and 8 try again ");
number = console.nextInt(); // the problem is here because user might enter string or double.
}
how can I make my program more robust?
Many thanks,
something like:
int number;
System.out.println("enter a number between 1 and 8");
do {
while (!console.hasNextInt()) {
console.nextLine(); // consume input
System.out.println("not an integer. try again");
}
number = Integer.parseInt(console.nextLine());
if(number < 1 || number > 8)
System.out.println("number is not between 1 and 8 try again ");
} while (number < 1 || number > 8);
// do something with number

How to Pass This Test Case?

I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.

Loop user input until conditions met

I need to ask the user to input a number to be used as the start of a range, and then input another number that is the end of the range. The start number has to be 0 or greater and the end number cannot be larger than 1000. Both numbers must be divisible by 10. I have found a way to meet these conditions, however if they are not met my program just tells the user that their input was incorrect. Is it possible for me to code it so that after the user inputs it will check to make sure the conditions are met, and if they are not loop back and make them input again. Here is the code I have so far.
Scanner keyboard = new Scanner(System.in);
int startr;
int endr;
System.out.println("Enter the Starting Number of the Range: ");
startr=keyboard.nextInt();
if(startr%10==0&&startr>=0){
System.out.println("Enter the Ending Number of the Range: ");
endr=keyboard.nextInt();
if(endr%10==0&&endr<=1000){
}else{
System.out.println("Numbers is not divisible by 10");
}
}else{
System.out.println("Numbers is not divisible by 10");
}
Easy with do-while:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
boolean good = false;
do
{
System.out.println("Enter the Starting Number of the Range: ");
startr = keyboard.nextInt();
if(startr % 10 == 0 && startr >= 0)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
good = false;
do
{
System.out.println("Enter the Ending Number of the Range: ");
endr = keyboard.nextInt();
if(endr % 10 == 0 && endr <= 1000)
good = true;
else
System.out.println("Numbers is not divisible by 10");
}
while (!good);
// do stuff
You need to use a while, something like:
while conditionsMet is false
// gather input and verify
if user input valid then
conditionsMet = true;
end loop
should do it.
The all-purpose procedure is:
Read the input in an infinite loop.
Use a break; statement to exit the loop when the conditions are met.
Example:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
for (;;) {
System.out.println("Enter the starting number of the range: ");
startr = keyboard.nextInt();
if (startr >= 0 && startr % 10 == 0) break;
System.out.println("Number must be >= 0 and divisible by 10.");
}
for (;;) {
System.out.println("Enter the ending number of the range: ");
endr = keyboard.nextInt();
if (endr <= 1000 && endr % 10 == 0) break;
System.out.println("Number must be <= 1000 and divisible by 10.");
}
If after invalid input you want to display just the error message without repeating the initial prompt message, move the initial prompt message just above/outside the loop.
If you do not have need for the separate error message, you can re-arrange the code to use a do-while loop to check the conditions, which is just a little shorter:
Scanner keyboard = new Scanner(System.in);
int startr, endr;
do {
System.out.println("Enter the starting number of the range.");
System.out.println("Number must be >= 0 and divisible by 10: ");
startr = keyboard.nextInt();
} while (!(startr >= 0 && startr % 10 == 0));
do {
System.out.println("Enter the ending number of the range.");
System.out.println("Number must be <= 1000 and divisible by 10: ");
endr = keyboard.nextInt();
} while (!(endr <= 1000 && endr % 10 == 0));

Categories