我正在进行Java分配,每当我在扫描仪中插入小数时,代码都会返回错误。我走得足够远,意识到它不是因为数字是小数,而是因为每当输入任何不是数字的字符时都会返回此错误。
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.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at population.main(population.java:14)
如果有人可以帮助我获得小数点,那将是很酷的,这是我的错误代码。
import java.util.Scanner;
public class population {
public static void main(String[] args) {
System.out.print("Enter the amount of years:"); // Prompts the user
Scanner input = new Scanner(System.in); // Defines the scanner
double value = input.nextInt(); // Defines the variable
double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
double B = ((60.0 / 7.0) * A); // Births per year
double C = ((60.0 / 13.0) * A); // Deaths per year
double D = ((60.0 / 45.0) * A); // Immigration per year
double E = (B + D - C); // Change per year
double F = ((E * value) + 312032486.0); // Change in population after 5 years
System.out.println(F);
}
}
答案 0 :(得分:2)
input.nextInt();
接受整数。将其更改为input.nextDouble()
答案 1 :(得分:0)
Scanner#nextInt() - 将输入的下一个标记扫描为int。
并抛出 InputMismatchException - 如果下一个标记与Integer正则表达式不匹配,或者超出范围
input.nextInt()
接受int
使用
input.nextDouble()
答案 2 :(得分:0)
由于输入无效而发生异常。你可以添加try catch块。请参阅以下代码。
有关详细信息,请参阅this
public static void main(String[] args) {
try
{
System.out.print("Enter the amount of years:"); // Prompts the user
Scanner input = new Scanner(System.in); // Defines the scanner
double value = input.nextInt(); // Defines the variable
double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
double B = ((60.0 / 7.0) * A); // Births per year
double C = ((60.0 / 13.0) * A); // Deaths per year
double D = ((60.0 / 45.0) * A); // Immigration per year
double E = (B + D - C); // Change per year
double F = ((E * value) + 312032486.0); // Change in population after 5 years
System.out.println(F);
}
catch(Exception e)
{
System.out.println("Invalid Input");
}
}