我需要为用户创建一种进入天气(下雪,下雨或晴天)的方式,并且在他们这样做之后它会影响汽车的MPG(每加仑英里数)。白雪皑皑4,阴雨2和阳光没有影响。我的提示是使用in.equals,但我知道我的代码很远。所以我的问题是我如何要求用户输入一个影响另一个变量并带有三个可能答案的输入?
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 city;
System.out.println("Enter true if trip is in the city false if the trip is on the highway");
city = in.nextBoolean();
if (city){
mpg = mpg - 2;
}
else {
mpg = mpg + 5;
}
boolean weather;
double snowy = 0;
double rainy = 0;
double sunny = 0;
System.out.println("What is the weather like?");
weather = in.equals(snowy);
{
mpg = mpg - 4;
}
weather = in.equals(rainy);{
mpg = mpg - 1;
}
weather = in.equals(sunny);{
mpg = mpg;
}
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 :(得分:0)
如果a和b是字符串,则用a.equals(b)比较java中的字符串。
CREATE VIEW IF NOT EXISTS exampledb.`ara_service` AS
SELECT T1.EntityId, T1.entityname AS EntityName,
T1.`xxx`,
T1.`yyy`,
COALESCE (T1.`aaa`, (SELECT `realvalue` FROM exampledb.`aba_service`
WHERE `id` = '333')) AS `CombinedValue`,
T1.`ddd`,
T1.`jjj`,
将测试a和b是否是同一个Object。所以你需要做的是:
以字符串形式读取天气(例如a == b
),然后您可以将其与:
String weather = in.readLine()
if(weather.equals("snowy"){..}
等等
答案 1 :(得分:0)
你可以做的是接受用户的输入并使用case语句(甚至是if语句)进行比较,如下所示:
System.out.println("What is the weather like?");
Scanner read = new Scanner(System.in);
string weather = read.next()
if (weather.equals("snowy")){
mpg -= 4;}
else if (weather.equals("rainy")){
mpg -= 2;}
答案 2 :(得分:-1)
这里有一个很好的例子Reading in from System.in - Java,我没有时间为你写出来。但基本上你需要为系统创建一个Scanner。这将阻止应用程序在那一点上等待System in的一些输入,然后再继续。在此之前做一个System.out.print是一个好主意,这样用户就知道他们需要输入一些内容。
答案 3 :(得分:-1)
您可以在if
对象next()
上使用Scanner
阅读用户输入后使用in
语句:
String weather = in.next();
if (weather.equals("snowy"))
mpg -= 4;
else if (weather.equals("rainy"))
mpg -= 1;
...
else System.out.println("Wrong input");
答案 4 :(得分:-1)
您无法使用in.equals
,但您可以阅读字符串,然后阅读.equals
:
String weather = in.next();
if("sunny".equals(weather)) {
mpg = mpg - 4;
} else if("rainy".equals(weather)) {
mpg = mpg - 1;
}