简体   繁体   English

为什么我在这段代码中得到 Input MIsmatch Exception?

[英]why i am getting Input MIsmatch Exception in this code?

I am just trying to read integer, double , string values from keyboard.我只是想从键盘读取整数、双精度、字符串值。 it just working fine for integer and double.它只适用于整数和双精度。 but when it comes to string, it was throwing a Input Mismatch Exception, so i cant able to read string from keyboard.但是当涉及到字符串时,它抛出了一个输入不匹配异常,所以我无法从键盘读取字符串。

import java.util.Scanner;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        double d= scan.nextInt();
        String s=scan.nextLine();

        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

You have used double d= scan.nextInt();您已经使用了double d= scan.nextInt();

instead use而是使用

double d= scan.nextDouble();

Moreover String is working fine for following input and output: 1 1 Hello此外,字符串对于以下输入和输出工作正常:1 1 Hello

String: Hello字符串:你好

Double: 1.0双倍:1.0

Int: 1智力:1

First, you're doing a scan.nextInt() for a double.首先,您正在为 double 执行scan.nextInt() Not the best thing to do.不是最好的做法。 Second, try scan.next() to get an arbitrary type token.其次,尝试scan.next()以获取任意类型的标记。

        int i = scan.nextInt();
        double d= scan.nextDouble();
        String s=scan.next();

please check the below code.请检查以下代码。 it is working for me.它对我有用。

      public class Solution {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("enter i value ");
        int i = scan.nextInt();
        System.out.println("enter d value ");
        double d= scan.nextDouble();
        System.out.println("enter s value ");
        String s=scan.next();


        // Write your code here.

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }

}

I think String s=scan.nextLine();我认为String s=scan.nextLine(); consumes the newline character coming from the followed calling double d= scan.nextInt();使用来自随后调用的换行符double d= scan.nextInt(); . .

Here is my two cents.这是我的两分钱。

double d = scan.nextInt();
scan.nextLine();
String s = scan.nextLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM