2014-09-23 41 views
0

我正在处理Java分配,并且每当我向扫描器中插入小数点时,代码都会返回错误。我足够认识到这不是因为数字是小数,而是因为每当输入任何不是数字的字符时都会返回此错误。在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

'input.nextInt()'? – user2357112 2014-09-23 04:11:14

+0

由于您刚刚接触“论坛”,因此不适合完成作业:) – venkatKA 2014-09-23 04:12:31

+0

'java.util.InputMismatchException'是一个非常具有描述性的错误;)。使用'.nextDouble()'而不是'.nextInt()'。 – theGreenCabbage 2014-09-23 04:15:08

回答

2

input.nextInt();接受一个整数。将其更改为input.nextDouble()

+0

它突出显示红色并显示“Double()方法未定义类型扫描仪”。 没关系,我认为你编辑它,或者我误解了它。 – 2014-09-23 04:14:03

+0

其''nextDouble()' – venkatKA 2014-09-23 04:15:25

+0

如果我问我是否应该担心什么时候它说“资源泄漏”输入“永远不会关闭”? – 2014-09-23 04:17:40

0

Scanner#nextInt() - 将输入的下一个标记扫描为int。

并抛出 InputMismatchException - 如果下一个标记不匹配整数的正则表达式,或超出范围

input.nextInt()需要int类型的输入

使用

input.nextDouble()

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"); 
    } 
}