java - 摆脱数组中的 null。 java

标签 java arrays loops while-loop

我不太确定问题出在哪里。 代码工作正常,但是,在我输入几个单词后,即:

结束

它告诉我:

空。

我的猜测是字符串 k 或数组的大小。 所以我想,我需要以某种方式输入“结束”工作,对吗?

public static void main(String[] args) {
  Scanner sc = new Scanner(System. in );


  String type;
  String word;
  String words[] = new String[100];
  int i = 1;

  String k = "end";
  System.out.println("Type a word: ");
  word = sc.next();


  while (word.compareToIgnoreCase(k) != 0) {

    words[i] = word;
    i = i + 1;
    word = sc.next();
  }

  System.out.println("What type A,B,C:");
  typ = sc.next();

  if (typ.equals("B")) {
    int lenght = words.length;
    lenght = i + 1;
    i = 1;
    while (i < lenght) {
      System.out.print(words[i]);
      System.out.println();

      i = i + 1;
    }
  }
}
}

最佳答案

您只需将最后一个单词添加到数组中即可:

while (word.compareToIgnoreCase(k) != 0) {

  words[i] = word;
  i = i + 1;
  word = sc.next();
}
words[i] = word; // Add the last item entered

顺便说一下,我建议使用 List<String>而不是String[] ,并调用 words.add(word) 。一方面,这意味着您不必跟踪索引 ( i )。更重要的是,列表可以变得任意长,并且您将只使用所需的内存。

关于java - 摆脱数组中的 null。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309461/

相关文章:

java - 类别/子类别 : How to get all subcategories(their subcategories too) for given category?

c++ - 不使用循环 C++ 添加数组

java - 类型安全: Unchecked cast in generic class

java - 错误 : while connecting Google Cloud Storage using Java => java.net.UnknownHostException : oauth2. googleapis.com

javascript - 如何使用javascript映射将一个数组转换为另一个数组?

c++ - 从 txt 文件行中获取多维数组

c - 如何将字符串转换为二维数组

c# - while(true)/while(1) 与 for(;;)

Java - 对象的默认序列化

java - 使用 JTextPane 设置代码样式