为什么我会得到java.util.InputMismatchException?

时间:2015-09-17 08:05:21

标签: java boolean java.util.scanner

//***************************************************************
//File: weight.java
//
//Purpose: Computes the ideal weight for both males and females.
//***************************************************************
import java.util.Scanner;

public class weight
{
    public static void main(String[] args)
    {
    Scanner scan = new Scanner(System.in);
    boolean answer1;
    System.out.println ("Are you a male (m) or female (f)?");
     boolean m=true;
    boolean f=false;
    answer1=scan.nextBoolean();

    int feet, inches;
    if (answer1=m)
    {
    System.out.println ("Enter your height in feet.  Inches will be asked later.");
    feet=scan.nextInt ();
    System.out.println ("Enter the remaining inches.");
    inches=scan.nextInt ();
    }
    if (answer1=f)
    System.out.println ("Enter your height in feet.  Inches will be asked later.");
    feet=scan.nextInt ();
    System.out.println ("Enter the remaining inches.");
    inches=scan.nextInt ();  
    }
    }

完整错误:

java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextBoolean(Unknown Source)
at weight.main(weight.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

我是'if'陈述和布尔的新手,所以如果有人能解释那就太好了! 基本上,我只想询问用户是男性还是女性,然后根据答案转发某些代码。

2 个答案:

答案 0 :(得分:2)

检查true的输入 使用false时,只允许nextBoolean()if (answer1=m)

顺便说一下,你有 if (answer1=f)=这是错误的。 ' =='是 分配 运算符和' if (answer1 == m)'是 布尔 运算符。

if (answer1 == f)boolean是正确的方法,可以帮助您解决问题。

你可以考虑使用char代替true,你可以尝试一下,因为当你要求用户输入男性女性但他必须输入他不知道的false<#assign foo={'bar':'go'}>

答案 1 :(得分:0)

如果您希望用户输入“&#39; m&#39;或者&#39; f&#39;对于性别,然后采用8.357963780872523e+31输入是最好的。以这种方式使用它:

char

然后为了比较,不要使用单char answer1; System.out.println ("Are you a male (m) or female (f)?"); answer1=scan.next().charAt(0); ,因为这是赋值运算符使用=进行比较。因此,请使用它:

==

if (answer1=='m' || answer1=='M') //taking care of both capital or small input