使用Scanner和.nextInt()时java.util.InputMismatchException

时间:2018-03-24 19:29:56

标签: java java.util.scanner inputmismatchexception

我只是想制作一个简单的程序来获得一些乐趣,但我在这里得到了这个代码:

import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class test5 {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(in);
        char reply;
        reply = (char) keyboard.nextInt();
        if (reply == 'y' || reply == 'Y') {
            out.println(":-)");
        } else {
            out.println(":-(");
        }
        keyboard.close();

    }

}

我得到了这个输出:

y
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 test5.main(test5.java:9)

1 个答案:

答案 0 :(得分:1)

Yint字符无法转换为Scanner,因此例外。不幸的是,nextChar()没有String reply = keyboard.next(); if (reply.equalsIgnoreCase("y")) { out.println(":-)"); } else { out.println(":-("); } 方法,但您可以使用字符串代替:

ImageView myImage = (ImageView) findViewById(R.id.imageView);

if (myImage.getDrawable() == null){

//The imageView is empty

} else{ 


// The imageView is occupied.

}
相关问题