scanner next()输入异常匹配..在nextInt()之后使用nextLine()

时间:2015-07-27 12:15:24

标签: java java.util.scanner next

我无法找到错误。我在阅读nextLine()后使用了nextInt()但仍然next()没有读到这个词("更新")。我错过了什么?

输入阅读:

    2
    4 5
    UPDATE 2 2 2 4
    QUERY 1 1 1 3 3 3
    UPDATE 1 1 1 23
    QUERY 2 2 2 4 4 4
    QUERY 1 1 1 3 3 3
    2 4
    UPDATE 2 2 2 1
    QUERY 1 1 1 1 1 1
    QUERY 1 1 1 2 2 2
    QUERY 2 2 2 2 2 2

我的代码:

   Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for(int i=0 ; i<t ; i++){
            int n = sc.nextInt();
            int m = sc.nextInt();
            sc. nextLine ();
            System.out.println(n+ " " + m);
            for(int j=0 ; j<m ; j++){
                String Q = sc.next(); // tried (String)sc.next(); also

                if(Q == "UPDATE"){
                    int x = sc.nextInt();
                    int y = sc.nextInt();
                    int z = sc.nextInt();
                    int val = sc.nextInt();
                    sc.nextLine();
                    System.out.println(x+ " " + y + " "+ z + " "+ val);
                }
                else if(Q == "QUERY"){
                    int x1 = sc.nextInt()-1;
                    int y1 = sc.nextInt()-1;
                    int z1 = sc.nextInt()-1;

                    int x2 = sc.nextInt();
                    int y2 = sc.nextInt();
                    int z2 = sc.nextInt();
                    sc.nextLine();

                  System.out.println(x1+ " " + y1 + " "+ z1 + " "+ x2+ " " + y2 + " "+ z2);
                }


            }
        }

2 个答案:

答案 0 :(得分:2)

java中的字符串比较是使用.equals

进行的

替换

的代码
if(Q.equals("UPDATE")){

答案 1 :(得分:1)

你应该使用equals比较这里的字符串。

if(Q.equals("UPDATE")){

if(Q.equals("QUERY")){