2016-05-23 113 views
-4

我需要帮助解决我的布尔,我对编程非常陌生,我的教授的英文很差。简易Java布尔

我需要5添加到mpg如果highwaytrue和减去2时cityfalse

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

布尔截至目前增加3到MPG,但我需要的,如果真的是加5或减2,如果假 – Pexing

+0

请至少格式正确启动码。缩进至关重要;这东西真的很难读**。你想要别人帮忙;所以至少可以让他们的工作尽可能简单。 – GhostCat

+0

不,它增加5,然后减2。就像你指定的。条件不是相互排斥的。结果是+3的变化。 – zapl

回答

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; 
} 
+0

你是对的,我保持他的格式,但更好地显示如何格式也:) – JohannisK

+0

最终的解决方案,即使他们输入假只是增加5的MPG – Pexing

+0

检查下面的一个...这不是唯一的错误,在您码。我的观点是......如果你需要检查某人是否在城市或高速公路上,可以用一个布尔值来做这件事,因为它有2个值。 布尔公路=真;如果highway == false,那么城市 – JohannisK

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; 
} 
+0

这是正确的答案,我的不完整。 OP的if语句的位置也不正确。 – JohannisK