我是一名初学者程序员,目前我在这个任务上撞墙。 我必须创建一个'模拟'汽车使用的程序,所以它会:驱动,停车并填满。它所要做的第一件事是询问你的坦克能容纳多少升的气体,以及目前在坦克中有多少升。然后,它询问用户是否想要a)驾驶,b)填满,或c)停车。我需要获取一个用户输入(我已经知道该怎么做),并根据用户是输入a,b还是c,它会转到这个特定的代码块并运行它。if,else if,else语句:在代码块内
下面是关于什么的a,b的具体说明,和c具有做: 一个)驱动器: 1.进入公里的驱动量(用户输入此) 2.输出气体的许多升是如何使用情况以及储罐中剩余的气体量。 (我们假定该车采用的0.1L /公里的平均)
b)中填写好 1.用户必须输入他们希望添加在罐升 2.输出数升的数量。 (用户不能输入比罐容纳更多的公升)
c)公园 1.输出罐中的升数和总公里数。 2.这退出循环
我使用正确的循环?我如何获得运行公式的代码(查看红色下划线)?请帮助我,我很迷茫。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many litres of gas can your tank hold?");
int litreCap = scan.nextInt();
System.out.println("How much gas is currently in your tank?");
int startingLitre = scan.nextInt();
System.out.println("Ok! Do you want to \n a) Drive \n b) Fill up, or \n c) Park");
String abc = scan.next();
String a, b, c;
a = String.valueOf(1); //Wasn't sure if the problem had to do with the fact
b = String.valueOf(2); //That I hadn't identified a,b and c
c = String.valueOf(3);
double litresUsed, gasTotal;
if (abc .equals(a)) { //this is the drive section
System.out.println("Please enter the amount of Kilometers driven.");
int KmCount = scan.nextInt();
litresUsed = 0.1*KmCount;//underlined yellow
startingLitre - litresUsed = gasTotal;//this is underlined red
}
else if (abc .equals(b)){ //this is the fill up section
System.out.println("OK! Please enter how many litres you are going to add.");
int litresAdded = scan.nextInt(); //this is underlined yellow
litresUsed + litresAdded = gasTotal; //underlined red
}
else {
//enter c) Park code here
}
}
}
我没有在代码中看到任何循环?如果a,b和c是String,那么abc是什么?我从来没有看到你可以连接这样的字符串? **你甚至可以运行你的代码吗?** –
让我建议你把更多的描述性名称给变量,例如,而不是'a',使用'driveSelected'之类的东西。有些东西会帮助你(和其他人)记住(a)选项是用户想要驾驶的。 – germanio
别的东西: 'startingLitre - litresUsed = gasTotal;' 记住,当你给变量赋值时,目标变量在左边,源(表达式,其他变量,方法被执行)放在右边声明,如下所示: 'gasTotal = startingLitre - litresUsed;' – germanio