Results 1 to 6 of 6
- 03-22-2011, 08:32 PM #1
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
MultiTable with a loop!! help please
can some one help me i have worked out the code i need using the if and else statements and a loop but im asking the user to enter a number between 1 and 100 and if they enter a number in hat range then it prints out a multi table for that number but if they enter a number out of range (say 101) i want the program to display a message just once but its not its repeating it 12 times !!
can some one help
this is my code
import java.util.Scanner;
/*
*/
class MultiTable
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int Count, chooseNumber; // variables things that change
System.out.println("Please enter a number between 1 and 100 ");
chooseNumber = input.nextInt();
for (Count = 1; Count <= 12; Count++)
{
if ( chooseNumber >= 1 && chooseNumber <= 100 )
System.out.println( Count + " * " + chooseNumber + " = " + (Count * chooseNumber));
else
System.out.println("The number you have entered is out of range" );
}
}
}
thanks
- 03-22-2011, 10:31 PM #2
It is because you have the if statement inside the for loop so it will execute it every time around the loop. Perhaps you should have it the other way around.
- 03-23-2011, 09:53 AM #3
Member
- Join Date
- Mar 2011
- Posts
- 2
- Rep Power
- 0
How do I rectify that then?
Thanks
- 03-23-2011, 10:07 AM #4
Senior Member
- Join Date
- Dec 2008
- Location
- Kolkata
- Posts
- 280
- Rep Power
- 5
Check the condition, before you start the loop. If the condition is satisfied, start the loop otherwise not.
Swastik
- 03-23-2011, 10:26 AM #5
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
You can also accomplish this with a break; after the error message, or set count so it won't meet the loops condition
- 03-23-2011, 12:55 PM #6
Member
- Join Date
- Mar 2011
- Posts
- 1
- Rep Power
- 0
Similar Threads
-
JTextField loop 2x for-loop WEIRD!
By Streetproject in forum AWT / SwingReplies: 2Last Post: 02-16-2011, 05:46 PM -
[Q] Loop issue (while loop)
By iriscience in forum New To JavaReplies: 9Last Post: 01-31-2011, 04:21 PM -
Convert do while loop to for loop
By sandeeptheviper in forum New To JavaReplies: 3Last Post: 01-03-2011, 12:37 PM -
How can I rewrite the following while loop using a for loop?
By gt11990 in forum New To JavaReplies: 5Last Post: 04-30-2010, 05:05 PM -
while-loop stopping on first loop
By davester in forum New To JavaReplies: 6Last Post: 06-26-2009, 08:46 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks