在while循环中将字符串和整数添加到不同的ArrayLists

我被困在一个练习中,我应该接受一个单词和数字(由空格分隔),然后将它们放入一个 ArrayList(数字和名称的不同列表)。


例如,如果我写“Jordan 19”,Jordan 的名字应该放在名为“listNames”的 ArrayList 中,而数字 19 应该放在名为“listNumbers”的 ArrayList 中。


如果键入字母“q”,则应该中断 while 循环。我遇到的问题是当我尝试从 ArrayList 中获取名称和编号时,我只得到一个空行和输入的数字。即用于数字的 ArrayList 有效,但不适用于名称。


可能有什么问题?谢谢您的帮助!


ArrayList<String> listNames = new ArrayList<String>();

ArrayList<Integer> listNumbers = new ArrayList<Integer>();


Scanner in = new Scanner(System.in);

System.out.println("Write a name and number (separate with blankspace), end with 'q'");


boolean go = true;

while (go) {

    String full = in.nextLine();

    if (in.next().equals("q")) {

        go = false;

    }

    int len = full.length();

    int blank = full.indexOf(" ");


    String nameString = full.substring(0, blank);

    String numberString = full.substring(blank + 1, len);

    int number = Integer.parseInt(numberString);


    listNames.add(nameString);

    listNumbers.add(number);

}


System.out.println(listNames.get(1));

System.out.println(listNumbers.get(1));


郎朗坤
浏览 176回答 3
3回答

慕桂英546537

我认为您的逻辑应该是从扫描仪读取整个输入行。然后,进行完整性检查以确保它只有两个由空格分隔的术语。如果是这样,则将单词和数字分配给它们各自的数组。System.out.println("Write a name and number (separate with blankspace), end with 'q'");while (true) {&nbsp; &nbsp; String full = in.nextLine();&nbsp; &nbsp; if ("q".equals(full)) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; String[] parts = full.split("\\s+");&nbsp; &nbsp; if (parts.length != 2) {&nbsp; &nbsp; &nbsp; &nbsp; // you could also just break here as well, but throwing an exception&nbsp; &nbsp; &nbsp; &nbsp; // is something you might actually do in a production code base&nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("Wrong number of input terms; use 2 only");&nbsp; &nbsp; }&nbsp; &nbsp; listNames.add(parts[0]);&nbsp; &nbsp; listNumbers.add(Integer.parseInt(parts[1]));}

Qyouu

使用 String.split() 函数会更容易得到你想要的。正如您所提到的,输入由空格分隔。假设输入是“Jordan 19”,那么您可以使用如下内容:String [] data = full.split(" "); //split the input by a blank spacelistNames.add(data[0]); //data[0] = JordanlistNumbers.add(Integer.parseInt(data[1])); //data[1] = 19如果您的所有输入都是一个字符串,然后是一个数字,这应该可以工作

qq_遁去的一_1

ArrayLists 从索引 0 开始。因此,如果要输出 ArrayList 中的第一个 Item,则必须编写System.out.println(listNames.get(0));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java