首页 > 解决方案 > 从用户获取字符串输入的替代方法

问题描述

我已经实现了以下代码,它将这些值作为输入:-

3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1

但是为了获取字符串输入,我尝试了 nextLine() 但在这种情况下它不接受输入。如果我使用 next() 则它将CLICKand1视为两个不同的字符串,所以ArrayIndexOutOfBoundsException当我拆分字符串并将其解析为 int时,我得到了. 处理此类输入的替代方法是什么?

import java.util.*;
    
public class TweetClose {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int open = 0;
        int a[] = new int[50];

        for (int i = 1; i <= n; i++) {
            a[i] = 0;
        }

        for (int i = 0; i < k; i++) {
            String s = sc.nextLine();
            if (s.equals("CLOSEALL")) {
                open = 0;
                for (int j = 1; j <= n; j++) {
                    a[j] = 0;
                }
            } else {
                String[] st = s.split(" ");
                int y = Integer.parseInt(st[1]);
                if (a[y] != 1) {
                    a[y] = 1;
                    open++;
                }
            }
            System.out.println(open);
        }
        sc.close();
    }
}

标签: javaarraysstring

解决方案


使用引起的问题nextLine()。您应该next()改用,因为您想处理下一个令牌。

处理完所有标记后,当前行的最终换行符仍在内存中。nextLine() 返回该换行符“\n”。然后你处理它:

String[] st = s.split(" ");
int y = Integer.parseInt(st[1]);

split 函数返回一个只有一个元素的数组(“\n”),因此您无法解析 st[1]。没有这样的元素,只有 st[0] 存在。

它将与 next() 而不是 nextLine() 一起使用,因为 next() 跳过换行符并继续下一行的下一个标记。

这是一个非常常见的错误,因为没有 nextString() 函数。


推荐阅读