gpt4 book ai didi

java - 如何根据输入类型执行某些命令

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:48 24 4
gpt4 key购买 nike

我设置了一个扫描仪,要求用户输入数字或输入“示例”以使用预设数字。如果他们输入一个数字,代码应该会问他们更多问题,然后进行计算。这执行得很完美。如果用户输入“EXAMPLE”,则应该将变量设置为预设数字并进行计算。输入 EXAMPLE 后,我无法使代码正常工作。我收到此错误:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at CarPool.main(CarPool.java:22)

这是我的代码:抱歉,如果它太困惑了。

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;

public class CarPool {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//inputs the scanner tool

float totaldistance;
float MPG;
float gasprice;
float gasused;
float totalpeople;
float totalcost;
//assigns variables

System.out.printf("Please type the total distance (miles) you are travelling, or type EXAMPLE for an example: ");
totaldistance = input.nextFloat();
if (isNan(totaldistance)) { //If the user types EXAMPLE, use preset numbers
totaldistance = 8;
MPG = 23;
gasprice = (float) 2.31;
totalpeople = 4;
} else if (isNumeric(totaldistance)); {
System.out.printf("Please enter the MPG of your vehicle: ");
MPG = input.nextFloat();
System.out.printf("Pleas enter the price of gas currently: $");
gasprice = input.nextFloat();
System.out.printf("Please enter how many people will be splitting the cost of gas:");
totalpeople = input.nextFloat();
//Prompts the user for some info that it can use for it's calculations. Sets them as floats for decimal numbers.
}
gasused = (totaldistance / MPG); //This finds how much gas the person is using by dividing the distance travelled by the mpg
totalcost = gasused * gasprice; //This calculates how much you will spend by multiplying the gas you use by the price of gas, given by the user
totalcost = totalcost / totalpeople; //splits the final cost amongst however many people are chipping in
NumberFormat formatter = new DecimalFormat("$" + "#0.00"); //Formats the price to two decimal places
System.out.println(formatter.format(totalcost)); //prints the final results
}

private static boolean isNumeric(float totaldistance) {
return false;
}

private static boolean isNan(float totaldistance) {
return false;
}
}

我在第 22 行遇到问题。

最佳答案

显然你会得到一个不匹配的异常,因为如果用户输入示例,你正在将其读取为 float ,现在你告诉我可以将示例转换为 float 。不对吗??

那么为什么不将输入数据作为字符串读取并检查它是否是示例,然后使用您的预设值,否则如果它 float 则相应地使用

我想你应该明白我的意思。

干杯

关于java - 如何根据输入类型执行某些命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28506001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com