IF statement isn't checking variable - java

Hello I'm trying to write a program that prints 3 numbers from a range being restricted to numbers from 0 to 99,but my If statement isn't double checking the variable.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0);
System.out.println("Outside range program terminated.");

Two problems that I see:
Your second input (within the first IF) is not checked with the code shown.
The else statement will NOT check the above mentioned problem because you've already passed that decision point when the original IF executed. The else is dependent on the IF's result. Here would be one way to fix.
Finally the 'else' needs brackets { }.
int input1 = 0;
Boolean myLoop = true; //Sets up our loop flag
while(myLoop){ //Loop while true
System.out.println("Please enter an integer between 0-99");
input1 = Input.nextInt();
if (input1>99||input1<0){ //If input is outside the range send msg.
System.out.println("Data range error");
}else{ //If input is in range, end loop.
myLoop=false;
}
}
This will continue to check until it get valid values.

While the others have given you a good code sample, I will like to point out where your code issue is. The code is not doing the double checking here because you have placed a semi-colon right at the end of the second if-else check, and the program will do nothing when it fulfill the if condition.I have replaced it with curly bracket. Try to compile and run it again.
System.out.println("Please input a interger between 0-99:");
int input1 = Input.nextInt();
if (input1>99||input1<0){
System.out.println("Outside range. Please enter an integer between 0-99");
input1 = Input.nextInt();
}
else if (input1>99||input1<0){
System.out.println("Outside range program terminated.");
}

Related

Java - How do I check if a Scanner input is an integer without using a while loop?

I have written a program for one of my assignments which asks for an input to assign to an integer variable. One of the parts of the assignment is, if the integer input is anything other than 1, 2, 3, or 4, the program should print a statement saying that is an invalid input, then end the program.
I have figured out how to get it to print this statement if the user enters an input higher than 4 or lower than 1, but I can not figure out how to get the same result when a double is entered.
I have managed to make it work by using a while loop that checks if the input is an integer or not,
while (!input.hasNextInt()){
System.out.println("Invalid choice. Good-bye.");
input.next();
}
int selection = input.nextInt();
I would like it to recognize it as an invalid input and then end the program right there. Instead, it waits for another valid input from the user
Expected result, per the assignment:
" If the user enters anything other than 1, 2, 3, or 4, the program should print, "Invalid choice. Good-bye." "
You did not mention what happens when a valid number is entered or the user enters anything other than an integer number.
So this code will exit the program when the user enters a non integer value or an integer not between 1 and 4:
Scanner input = new Scanner(System.in);
int number = 0;
boolean valid = false;
System.out.println("Enter number: ");
if (input.hasNextLine()) {
if (input.hasNextInt()) {
number = input.nextInt();
if (number >= 1 && number <= 4) {
valid = true;
System.out.println("Valid choice:" + number);
}
}
input.nextLine();
if (!valid) {
System.out.println("Invalid choice. Good-bye.");
System.exit(0);
}
}

Getting all possible odd numbers in the user input

I am having difficulties with finding all possible odd numbers for my program. I am required to use a while loop to find all the odd numbers but i am not sure how to print it out. I dont know if im doing anything wrong in this block while((num1+num2)%2==0) because that was just a guess. Outline of the program is to get the user to enter 2 numbers that is an even multiple of the other number. I am not sure how that part either. After finding 2 numbers that is an even multiple of the other number, i am supposed to display all the odd numbers between the two numbers. Thanks alot in advance.
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
How about something like this:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
Set current to equal num1, continue the loop while current is less than num2. For each iteration check if current is odd and output it if it is. Increment current by one.

How to verify that input is a positive integer in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create an input that will Verify the input is an Integer, and that it is positive. Right now i have this. How should i check if the integer is positive
EDIT: Also i need it to keep asking until you enter a positive integer
/**
* pre: none
* post: returns a positive integer as entered by the user
*/
public static int getInput(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
while (!scan.hasNextInt()){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
scan.next();
}
a = scan.nextInt(); //Assigns entered integer to a
return a; //replace with correct code
}
You can do this in a single loop, similar to the one that you have for skipping invalid input. However, since the loop needs to ensure two things (i.e. a number is entered, and that number is positive) you need to modify its body.
Since the input needs to be done at least once, a do/while loop is a better choice.
Start with a loop that satisfies the condition that you want, i.e. "I got a number, and that number is positive":
int num = -1;
do {
// We'll provide content of this in a moment
} while (num <= 0);
Once the loop exits, you know that num > 0, so the only task now is to write a body of the loop that takes us closer to that goal.
Inside the loop we need to check that the user entered a number. If he did, we harvest that number; otherwise, we tell the user to try again:
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scan.nextLine();
}
That's it - now you have a loop body that reads the value for you, and a loop condition that ensures that the value is positive on exit. Combine the loop with the loop body, and try it out. It should do the trick.
Simple:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
On a side note:
Check Math.signum()
Returns the signum function of the argument; zero if the argument is
zero, 1.0 if the argument is greater than zero, -1.0 if the argument
is less than zero.
You can try this:
public static int getInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
int a = scan.nextInt();
while (a < 0){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
a = scan.nextInt();
}
return a;
}

Java method stuck in endless loop while validating input

Somehow I am getting some funny play here and I just cant see why.
This method is supposed to make sure that the input is either y or n, and is NOT blank.
I should note this is for school, and the 2 separate error outputs are required.
When I enter a blank line, I get exactly that at the console- a blank line.
After that point, or after a time where I purposely enter bad data, such as x, the very next time I enter a valid data, like y or n, I continue to get the bad data in an endless loop.
What have I done wrong?
public static boolean getContinue(Scanner sc)
{
boolean decision = false;
System.out.println("Continue? Y/N: ");
String userChoice = sc.next();
boolean isValid = false;
while (isValid == false)
{
if (userChoice.equalsIgnoreCase("y"))
{
decision = true;
isValid = true;
}
else if (userChoice.equalsIgnoreCase("n"))
{
decision = false;
isValid = true;
}
else if (userChoice.equals(""))
{
System.out.println("Error! This entry is required. Try again.");
userChoice = sc.next();
}
else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
{
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
}
}
return decision;
}
NOTE:
Code was amended to include
New console outputs(Still wrong)
FORMATTED RESULTS
Loan amount: $5.00
Yearly interest rate: 500%
Number of years: 5
Monthly Payment: $2.08
Continue? Y/N:
b
Error! Entry must be 'Y' or 'N'. Try again.
y
Error! Entry must be 'Y' or 'N'. Try again.
y
Enter loan amount:
You don't set the variable userChoice to the new value. Change your last if clause to
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
Because userChoice never changes inside the loop (which is because you don't change it).
Please look at else if part:
else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
here you have done 2 errors:
you have used |, which is bitwise operator, not logical
the logic requires logical AND (&&) to get the cases when the input is not either y or n
SO the correct else-if:
else if (!userChoice.equalsIgnoreCase("y") && (!userChoice.equalsIgnoreCase("n")))
{
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
}
You have to use sc.nextLine() in order to catch the Empty Blank Line. So replace all the instances of sc.next() with sc.nextLine()

While Loop Continues Despite Condition Being Met

Hey everyone so I've been trying to write what should be a really easy counting program for my CS class, but for some reason it keeps spitting back out the "Please enter a number (0 to stop): " prompt and seems to completely disregard the while loop. If the condition inside the while loop is being met, why does the while loop not stop even if 0 is entered? I have done C# in the past, but I'm not really familiar with Java's caveats, so if there's anything weird that Java doesn't like me to do let me know. For a more detailed description of the program, it's supposed to read both negative and positive numbers from the user, output the sum of the negatives and the positives individually, and then take the average. (Obviously below is just the problematic piece of code.)
Scanner scanner = new Scanner(System.in);
double average;
double numPositive=0.0;
double numNegative=0.0;
double input = 0.0;
do
{
System.out.print("Please enter a number (0 to stop): ");
input = scanner.nextDouble();
if (input < 0.0)
{
numNegative += scanner.nextDouble();
}
else if (input > 0.0)
{
numPositive += scanner.nextDouble();
}
} while (Math.abs(input) > 1.0e-6); // make the tolerance whatever you want.
You never change input after the initial assignment; the loop will continue on forever. I think you forgot to call scanner.nextDouble() again.
You're not taking in input after initially retrieving it.
Your scanner.nextDouble() assigns to numNegative and numPositive- neither of which is checked by the while loop.
while (input != 0.0)
{
System.out.print("Please enter a number (0 to stop): ");
input = scanner.nextDouble();
if (input < 0.0)
{
numNegative += input;
}
else if (input > 0.0)
{
numPositive += input;
}
}
You are not assigning a value to input anywhere inside your loop. So, the initial value remains, and the loop won't exit.

Categories

Resources