扫描方法:next()vs nextLine()

时间:2015-02-23 17:14:56

标签: java

我承认,我已经经历了很多(类似的)问题,但我似乎无法理解我为基础SPOJ编写的以下代码中的上下文用法问题(http://www.spoj.com/problems/ONP/):

import java.io.*;
import java.util.Stack; 
import java.util.Scanner;


public class onp1 {

    public static String postfixString(String expression) {

        // Stack <Character> valueStack = new Stack <Character>();
        Stack <Character> operatorStack = new Stack <Character>();
        String output = "";
        char[] tokens = expression.toCharArray();

        for(char c : tokens) {

            if(c == '('){
                continue;
            }

            else if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
                operatorStack.push(c);
                continue;
            }

            else if(c == ')') {
                output += operatorStack.pop();

                continue;
            }

            else {
                    output += String.valueOf(c);
                continue;
            }
        }
        return output;
    }
    public static void main (String [] args)throws java.lang.Exception {

        String inputString = "";
        int n1;
        Scanner in = new Scanner(System.in);
        try
        {
            n1 = in.nextInt();
            StringBuilder[] sb = new StringBuilder[n1];
            for(int i = 0; i < n1; i++) {

                sb[i] = new StringBuilder();



                inputString = in.next();

                sb[i].append(postfixString(inputString)); 

            }


            for(int i = 0; i < n1; i++) {
                System.out.println(String.valueOf(sb[i]));
            }
        }
        catch (Exception e) {
           // System.out.println("");
           System.out.println(e.getMessage());    
            // numberOfTestCases.next();
        }
        System.exit(0);
    }

}

如果我使用nextLine()而不是next(),SPOJ引擎会生成一个错误的答案&#39;响应。

此外,在postfixString函数中使用StringBuilder对象而不是String对象时似乎存在一些问题(我之前使用的是StringBuilder对象;使用&#39; toString()&#39返回一个字符串; 方法)。

请忽略逻辑上的不一致(我知道有一些)。我已经把它们(大部分)解雇了。让我疯狂的是nextLine() vs next()和StringBuilder vs String问题。

2 个答案:

答案 0 :(得分:1)

next()只会返回空格前的内容。 nextLine()返回当前行并将扫描仪向下移动到下一行。

答案 1 :(得分:1)

如果您的输入字符串之间有空格,如“(a + b)* c”,那么next方法将给出(然后是a然后+然后是b。

如果您使用nextLine,它会立即读取整行。

String是一个不可变类,而StringBuilder则不是。含义字符串一旦创建就无法更改。所以当你做“str1”+“str2”时,它会创建三个字符串对象,“str1”然后是“str2”,然后是“str1str2”。如果你使用StringBuilder的append方法,你只需继续添加到同一个对象,然后在完成附加字符串后的最后一次,你在StringBuilder上调用toString来创建最终的String对象一次。