我试图让我的代码重复,我试图输入“时间”,但它说:
非法表达的开始。
如能提供任何帮助,我们将不胜感激。
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 );
}
}
发布于 2016-02-21 19:40:02
你可能试图做的事情的例子(下面的详细信息)
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将自动退出该循环。这些条件要么为真,要么为假(布尔值)。我注意到您没有在while循环中指定您想要的内容。如果你能为我们提供更多关于你还想做什么的信息,那会很有帮助的。
2)请确保在打印语句中包含问句和引号之间的空格,否则输出将被打包成如下所示:
不良做法:
System.out.print("How many miles were driven?");
输出:使用了多少加仑?5
良好做法:
System.out.print("How many miles were driven? ");
输出:使用了多少加仑?5
注意间距。
3)我给你的代码可能看上去很模糊,但这是因为我没有具体的条件。确定代码的哪个部分需要继续运行,直到满足某个条件为止。在我的示例中,我将布尔变量命名为"stillInLoop“,但通常情况下,这对任何阅读您的代码的人都是非常没有帮助的,您最好给它命名一些更有用的东西。
希望这能帮上点忙。祝好运!
发布于 2016-02-21 19:20:15
您可能没有在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 );
}
}
这将循环您的程序,直到您强制它停止,让程序停止,否则您将需要将while循环中的“true”更改为由代码中的某些内容触发的内容。
https://stackoverflow.com/questions/35540660
复制相似问题