Java代码:Word数组

时间:2016-03-18 03:09:47

标签: java

我正在尝试执行一个代码,要求用户输入一个单词。用户可以输入最多99次的单词,如果他输入单词“停止”,该程序将结束并计算他输入的单词数量。

现在我已经陷入困境,我真的很想得到一些帮助。谢谢。

    public static void main(String[] args) {

    String [] newSentence = new String [100] ;
    String inputword = null;
    Integer numberofWords= 0;

    inputword = JOptionPane.showInputDialog("Please enter a word: ");

    while (inputword.compareTo("stop") !=0 && numberofWords <99){
      newSentence[numberofWords] =inputword;
    }

   inputword = JOptionPane.showInputDialog("Please enter another word: ");
    numberofWords++ ;

     }
}

1 个答案:

答案 0 :(得分:1)

您必须在循环中询问用户输入

试试这个:

public static void main(String[] args) {

  String [] newSentence = new String [100] ;
  String inputword = null;
  Integer numberofWords = 0;

  for (;;){
    // merge two call for dialog into one
    inputword = JOptionPane.showInputDialog(
      numberofWords == 0 ? "Please enter a word: " : "Please enter another word: ");

    if (!inputword.equals("stop")){
      newSentence[numberofWords++] =inputword; // increment numberofWords here
      if (numberofWords >=99){
        // exit the loop because it reached to the maximum number
        break;
      }
    } else{
      // exit the loop because "stop" is entered
      break;
    }
  }
}