我需要帮助修复我的布尔值,我对编程很新,而且我的教授的英语很差。
如果mpg
为highway
,我需要向true
添加5;如果city
为false
,则需要减去2。
import java.util.Scanner;
public class AdvancedTripCalc {
public static void main(String[] args) {
// New Trip Calc.
String firstname;
int mpg;
int miles;
double price;
double totalcost;
Scanner in = new Scanner(System.in);
System.out.println("Please enter your First Name");
firstname = in.nextLine();
System.out.println("Please enter the MPG of your car");
mpg = in.nextInt();
boolean highway = true;
boolean city = false;
if (highway == true) {
mpg = mpg + 5;
}
if (city == false) {
mpg = mpg - 2;
}
System.out.println("Enter true if trip is on the highway false if the trip is in the city");
in.nextBoolean();
System.out.println("Please enter the Miles to be traveled");
miles = in.nextInt();
System.out.println("Please enter the price per gallon of gas");
price = in.nextDouble();
totalcost = miles * price / mpg;
System.out.println("Your name is " + firstname);
System.out.println("Your MPG is " + mpg);
System.out.println("Your miles to be traveled is " + miles);
System.out.println("Your price per gallon of gas is " + price);
System.out.println("Your total cost is " + totalcost);
}
}
答案 0 :(得分:2)
创建一个布尔变量,例如boolean inCity;
将in.nextBoolean();
更改为inCity = in.nextBoolean();
然后,在输入值之后,您可以使用if
语句进行检查。在您的代码中,在获得输入之前检查if
语句。
所以你会有这个:
boolean inCity;
System.out.println("Are you in the city?(true/false): ");
inCity = in.nextBoolean(); //Store input in variable
if (inCity) { //If the condition is a boolean variable, you can type it like this(if (boolean) )
mpg -= 2;//Same as mpg = mpg - 2;
} else { //if inCity is false:
mpg += 5; //mpg = mpg + 5;
}
答案 1 :(得分:0)
if (highway) {
mpg = mpg + 5;
}
if (!city) {
mpg = mpg - 2;
}
应该是
if (highway) {
mpg = mpg + 5;
} else { //not highway, so city
mpg = mpg - 2;
}
现在你检查它是否是一条高速公路。如果是true
,则代码会添加5.然后您检查它是否不是城市。如果是false
,则代码会减去2。
此外,您只能在提交后检查布尔值:
System.out.println("Enter true if trip is on the highway false if the trip is in the city");
boolean highway = in.nextBoolean();
if (highway) {
mpg = mpg + 5;
} else { //not highway, so city
mpg = mpg - 2;
}