View Full Version : Printing only last line of for loop output
jbecks
05-23-2009, 02:32 AM
This is part of a homework assignment. I was given a while loop, and was told to convert it into a for loop that produced the same output. The last line of output is correct, but how do I eliminate every other line?
Here is my code:
String input = JOptionPane.showInputDialog(
"Please enter a number, 0 to quit:");
int n = Integer.parseInt(input);
for (int i = 1; n * n > Math.pow(2,i); i++)
{
System.out.println("2 raised to " + (i + 1) + " is the first
power of two greater than " + n + " squared");
}
Fou-Lu
05-23-2009, 08:02 AM
Technically, you just need to take the print out of the loop, put it below and remove the + 1 from the i. Since the value of n never changes, that would technically work.
This doesn't actually solve anything though, so I'm curious if thats what you're looking to do. This just... looks wrong for an assignment question:
String input = JOptionPane.showInputDialog(
"Please enter a number, 0 to quit:");
int n = Integer.parseInt(input);
for (int i = 1; n * n > Math.pow(2,i); i++)
{
}
System.out.println("2 raised to " + (i + 1) + " is the first power of two greater than " + n + " squared");
Especially since you can calculate i as the value of i * n.
Perhaps the best thing I can ask is what the original while loop is. If you can post that I can help direct you.
There's a couple of things I need to mention too. In the future, can you please wrap any code in tags or using the same but php instead of code? That formats it so its more easy to read (the php ones will add colour that for the most part matches any C type language syntax).
And the other thing I need to mention is homework. Although we can help direct you in specific questions, we cannot do it for you. Since it sounds like the actual conversion between the while and the for is a specific assignment criteria, I'm not certain how much I can help I'm afraid.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.