我想让我的代码重复,我尝试输入“while”,但它说:
非法开始表达。
任何帮助都将被视为在何处输入。
import java.util.Scanner;
public class GasMileage
{
public static void main(String[ ] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("How many miles were driven?");
int miles;
miles = keyboard.nextInt();
System.out.print("How many gallons were used?");
int gallons;
gallons = keyboard.nextInt();
int mpg;
mpg = miles / gallons;
System.out.println(" The Miles-Per-Gallon used in this trip are " + mpg );
}
}
答案 0 :(得分:2)
您可能尝试做的示例(详情如下)
import java.util.Scanner;
public class GasMileage
{
public static void main(String[ ] args)
{
Scanner keyboard = new Scanner(System.in);
boolean stillInLoop = true;
while (stillInLoop)
{
System.out.print("How many miles were driven? ");
int miles;
miles = keyboard.nextInt();
System.out.print("How many gallons were used? ");
int gallons;
gallons = keyboard.nextInt();
int mpg;
mpg = miles / gallons;
System.out.println(" The Miles-Per-Gallon used in this trip are " + mpg);
stillInLoop = false;
}
}
}
一些提示:
1)如果你使用while条件,那么你正在运行该循环,直到某些东西不再为真,在这种情况下java会自动退出循环。这些条件为true或false(布尔值)。我注意到你没有在while循环中指定你想要的内容。如果您可以向我们提供有关您正在尝试做的其他事情的更多信息,那将会非常有帮助。
2) 请务必在打印报表中的问题和引号之间加上空格,否则输出会像这样聚集在一起:
不良做法:
System.out.print("How many miles were driven?");
输出:使用了多少加仑? 5
良好做法:
System.out.print("How many miles were driven? ");
输出:使用了多少加仑?的 5 强>
注意间距。
3) 我给你的代码可能看起来很模糊,但这是因为我没有条件专门处理。确定代码的哪个部分需要继续运行,直到满足某个条件。我在我的例子中调用了布尔变量“stillInLoop”,但通常这对于阅读代码的人来说是非常无益的,你可能最好将其命名为更有用的东西。
希望这有点帮助。祝好运!
答案 1 :(得分:0)
您可能没有在while循环中使用正确的语法,它看起来应该是这样的:
//in your main method
while(true){
//here you ask the user questions
}
//end of your program
因此,当您在计划中填写此内容时,您将获得:
public class GasMileage{
public static void main(String[ ] args){
Scanner keyboard = new Scanner(System.in);
while(true){
System.out.print("How many miles were driven?");
int miles;
miles = keyboard.nextInt();
System.out.print("How many gallons were used?");
int gallons;
gallons = keyboard.nextInt();
int mpg;
mpg = miles / gallons;
System.out.println(" The Miles-Per-Gallon used in this trip are " + mpg );
}
}
这将循环你的程序,直到你强制它停止,让程序停止,否则你将需要更改' true'在while循环中,由代码中的某些内容触发