Nested loop if statement help
Right now my code is generating half of what it is supposed to.
Program asks the user to enter a number from 1 to 10.
Enter 7
output will be $$$$$$$
I'm having issues with my if statement. Once you put in the wrong number it should ask for another number and so on.
If statement:
Code :
if( num < 1 || num > 10)
{
System.out.print("The number you entered is invalid");
}
Code :
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
int num;
int num_of_rows = 1;
System.out.print("Enter a number from 1 to 10: ");
num = keyboard.nextInt();
for (int row = 1; row <= num_of_rows; row++)
{
for ( int column = 1; column <= num; column++)
{
System.out.print("$");
}
}
System.out.println();
System.exit(0);
}
Re: Nested loop if statement help
So you want to ask for different input *while* their input is invalid, right?
Re: Nested loop if statement help
Yes, that is correct.
So, a while loop would be the thing to use?
Re: Nested loop if statement help
Quote:
Originally Posted by
CSUTD
Yes, that is correct.
So, a while loop would be the thing to use?
What happened when you tried it?
Re: Nested loop if statement help
Not working, I may have done it wrong.
I enter 2 it prints out "$$" and the "The number you entered is invalid". Even if I enter 20 it says the same thing. But it doesn't ask for the user to enter another number.
My while loop
Code :
while(num < 1 || num > 10)
{
// nested loop in here
System.out.println("\nThe number you entered is invalid");
}
Re: Nested loop if statement help
Without an SSCCE I can only guess at what your code is doing. But in that while loop, I don't see a place where you're asking for user input.
Re: Nested loop if statement help
Quote:
Originally Posted by
KevinWorkman
Without an
SSCCE I can only guess at what your code is doing. But in that while loop, I don't see a place where you're asking for user input.
Code :
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
int num = 0;
int num_of_rows = 1;
while(num < 1 || num > 10)
{
System.out.print("Enter a number from 1 to 10: ");
num = keyboard.nextInt();
for (int row = 1; row <= num_of_rows; row++)
{
for ( int column = 1; column <= num; column++)
{
System.out.print("$");
}
}
System.out.println("\nThe number you entered is invalid");
}
System.out.println();
System.exit(0);
}
Re: Nested loop if statement help
I'm really not sure what you expect the program to do- look through it line by line, and it should become pretty clear what's going on.
You're asking for a number, and regardless of its value you're printing out "$" a certain number of times. Then, regardless of its value, you're telling them the number is invalid. Then, if the number is indeed valid, you're repeating the process.