【问题标题】:How to read String and input from a single line of input from scanner如何从扫描仪的单行输入中读取字符串和输入
【发布时间】:2015-09-18 11:21:59
【问题描述】:

语言:Java。

目标: 布尔数组 gridA[] 应该在从输入读取的任何索引上变为真(即,如果输入是“init_start 2 4 5 init_end”,则 gridA[] 索引 2,4 和 5 应该变为真)。我设法开始工作,但我有两个问题:

输入: init_start int int int int (...) int init_end 例如:init_start 2 6 12 init_end

问题: 输入中任何超过(实例变量)int L(确定数组的索引长度)值的整数都应被忽略,以防止来自数组 gridA[] 域之外的整数产生影响。 使用 if(scanner.nextInt != L){} 似乎不起作用。

我也需要这个方法,或者方法体在输入以“init_start”开始时开始,在输入以“init_end”结束时停止。 如何编写代码,使其可以从同一个输入中读取字符串和整数?

我打算使用 if(scanner.Next=="init_start") 后跟 a = 扫描仪.NextInt;正如我所怀疑的那样,这没有用。

尝试解决: 谷歌搜索后,我尝试将 String initialInputStart 放入扫描仪中: localScanner(initialInputStart); 但我没能做到这一点。我发现的其他信息建议我关闭并重新打开扫描仪,但我需要从单行输入中读取信息,所以我怀疑这会有所帮助。

代码:

java.util.Arrays.fill(gridA,false); 
java.util.Arrays.fill(gridB,false);
String initialInput;
String initialInputStart;
int a;
int i;//only for testing
i = 0;//only for testing

System.out.println("type integers"); //only for testing
while( scanner.hasNextInt() && i<5){ //I can't find a way to make loop stop without missing input so I'm using i temporarily
  a = scanner.nextInt();
  gridA[a] = true;
  System.out.print(a);
  System.out.print(gridA[a]+" ");
  i++;
}//end while    

【问题讨论】:

  • 一个简单的问题:什么?我真的不明白你的问题。请完全改写您的问题。
  • Appolgoies,我会把事情说得更清楚。
  • 你的意思是用户会一次性提供输入而你需要使用它吗?
  • 是的,这正是我的目标。虽然我可以暂时接受三个单独的输入。
  • 只是猜测 scanner.nextInt() 获取 int,但不会继续到控制台的下一行尝试:int yourVariable = Integer.parseInt(scanner.nextLine())

标签: java


【解决方案1】:

我写了一个小程序,它几乎可以达到你所说的目标;我逐行阅读并将每个拆分为我进一步处理的令牌。标记描述了数据的含义/我们所处的状态。实际数据在 switch(token) 块中的 default: 案例中解析并在行为中从一个状态分支到另一个状态(这仅仅是在这里可见,因为我们只有两个状态:“init”和“not init”,在关键字旁边):

public static void main(String[] args) {
    int L = 13; // not sure if this is needed
    boolean[] gridA = new boolean[L];

    Reader source;
    /**
     * from file:
     *     source = new FileReader("grid.csv");
     */
    /**
     * from classpath resource:
     *     source = new InputStreamReader(MyClass.class.getResourceAsStream("grid.csv"));
     */
    /**
     * from string:
     *     source = new StringReader("init_start 2 6 12 init_end");
     */
    /**
     * from std-in:
     *     source = new InputStreamReader(System.in);
     */
    try(BufferedReader stream = new BufferedReader(source)) {
        boolean init = false;

        // loop
        input_loop:
        while(true) {
            // read next line
            String line = stream.readLine();
            if(line == null) {
                // end of stream reached
                break;
            }
            if(line.trim().isEmpty()) {
                // ignore empty lines
                continue;
            }

            String[] tokens = line.split(" ");
            for (String token : tokens) {
                switch (token) {
                    // evaluate keywords
                    case "init_start":
                        init = true;
                        break;
                    case "init_end":
                        init = false;
                        break;
                    // for input from console
                    case "exit":
                        break input_loop;
                    default:
                    // parse input, based on state (expand "init" to an enum for more states)
                        if(init) {
                            // read init input
                            int index = Integer.parseInt(token);
                            if(index >= 0 && index < gridA.length) {
                                gridA[index] = true;
                            } else {
                                throw new RuntimeException("illegal grid index: " + index);
                            }
                        } else {
                            // read undefined input
                            throw new RuntimeException("unrecognized token: " + token);
                        }
                        break;
                }
            }

        }
    } catch(IOException ex) {
        throw new RuntimeException("an i/o exception has occurred", ex);
    }

    System.out.println(Arrays.toString(gridA));
}

【讨论】:

  • 是的,这就像我打算做的 80% 的事情:D,但赞成实际代码:P
【解决方案2】:

" 如何编写代码,使其可以从同一输入中读取字符串和整数?"

你想要这样的输入吗:“123, foo” 如果是这样,请使用:

String input = scanner.nextLine();
String[] parts = input.split(",");//" " to split it at an empty space
String part1 = parts[0]; // 123
int Number = Integer.parseInt(part1) // you could inline it, but i chose this version for better refference
String part2 = parts[1]; //foo

如果您的输入看起来像这样“123 或 foo” 您必须将输入读取为字符串,然后检查字符串是否为数字:

String input = scanner.nextLine();
if (text.contains("[a-zA-Z]+") == false){ //looks if the input does NOT contain any characters
int nummber = Integer.parseInt(input);
} else{
String text = input;
}

之后你可以比较你的文字:

对于第一个提到的情况:

 if("init_start".equals(parts[1])){ //*
yourMethod();
}

其他情况:

  if("init_start".equals(text)){ //*
yourMethod();
}

*还有: “我的意思是使用 if(scanner.Next=="init_start")”

*非常重要!要比较对象,例如字符串,请使用 .equals()。 "==" 仅适用于原始类型

编辑:我读过你的例子。你可以结合我的解决方案。在空格(“”)处拆分字符串并检查parts[x]是否为整数。但我不推荐这种方法!你为什么不把你的输入分成三个部分:init_start 会启动你的函数。之后,您的方法将期望在插入整数后输入像“int int int”这样的整数,您的函数可能会自动停止或等待输入“init_stop”。在我看来这更合理。如果您想使用单行解决方案,您可以通过获取 tingparts[].lenght()-2

来评估 int 的数量

【讨论】:

  • 您的评论很有帮助。 string.split 尤其让事情变得更容易。
【解决方案3】:

使用这个实现:

public static void main(String args[]){
    try{
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a line");
        String dat = in.readLine();
        System.out.println(dat);
    }
    catch(IOException e){
        System.out.println("IO ERROR !!!");
        System.exit(-1);
    }
}

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2015-05-27
    • 2019-12-11
    相关资源
    最近更新 更多