我设置了Scanner
,要求用户输入数字或输入“EXAMPLE”以使用预设号码。如果他们输入一个数字,代码应该向他们提出更多问题,然后计算出来。这完美地执行。如果用户输入“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行遇到问题。
答案 0 :(得分:1)
显然你会得到一个不匹配的异常,因为如果用户输入的例子你正在将它读作浮动现在你告诉我可以将java转换为例子浮动。不对吗?
那么为什么不把输入数据作为字符串读取并检查它是否是示例然后使用您的预设值,否则如果它浮动使用则相应
我认为你应该明白我的观点。
欢呼声