I / O不匹配(JAVA)int / String

时间:2018-02-13 16:36:16

标签: java string if-statement while-loop int

我必须写一个用户写一个项目价格的程序,当用户按下ctrld时,程序将打印较低的价格(没有项目的名称)。 该程序不会打印任何思考或不匹配。我该怎么办?

这是错误。如何修改代码以便可以读取字符串?

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at StampaMinimoParola.main(StampaMinimoParola.java:12)

这应该是输出:

INPUT

apples 10
pears 20
grapes 5

输出

5

以下是代码:

import java.util.Scanner;
public class StampaMinimoParola {
    public static void main(String[] args) {
        Scanner s=new Scanner (System.in);
        String name="";
        int lower=Integer.MAX_VALUE;
        int price;

        while (s.hasNext()) { //start of the while loop
            name=s.nextLine(); //name of the article
            price=s.nextInt();//price of the article

            if (price<lower) {
                System.out.println(price);

            }
            //end of while cycle
        }

    }

}

1 个答案:

答案 0 :(得分:0)

只需将s.nextLine()更改为s.next()

即可

nextLine()吃整行,所以当你尝试nextInt()时,你已经在梨了