【发布时间】:2015-04-30 04:25:17
【问题描述】:
我是一名初级程序员,目前正在为这项任务撞墙。 我必须创建一个程序来“模拟”汽车的使用,所以它是:开车、停车和加油。它所做的第一件事是询问您的油箱可以容纳多少升汽油,以及目前油箱中有多少升。然后,它会询问用户是否想要 a) 开车、b) 加油或 c) 停车。我需要获取用户输入(我已经知道该怎么做),并且根据用户输入的是 a、b 还是 c,它会转到特定的代码块并运行它。
以下是关于 a、b 和 c 必须做什么的具体说明: a) 驱动器: 1.输入行驶公里数(用户输入这个) 2. 输出使用了多少升的气体,以及罐中剩余的气体量。 (我们假设汽车平均使用 0.1 L/Km)
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 是字符串,那么 abc 是什么?我从来没有见过你可以像这样连接字符串?!!! 你甚至可以运行你的代码吗?
-
让我建议您为变量添加更多描述性名称,例如,不要使用
a,而是使用类似driveSelected的名称。可以帮助您(以及您之后的其他人)记住 (a) 选项是用户想要驾驶的东西。 -
something else:
startingLitre - litresUsed = gasTotal;请记住,当您将某些内容分配给变量时,目标变量位于左侧,源(表达式、其他变量、执行的方法)位于右侧声明,像这样:gasTotal = startingLitre - litresUsed; -
我添加了我的最后一条评论作为答案,因为这会让你的代码运行一个方程式。顺便说一句,@KickButtowski 是对的,您的代码中没有循环。
-
@germanio 你的回答看起来像是一个评论,只是友好的观察;)
标签: java loops if-statement netbeans switch-statement