Java中{方法}中的循环错误

时间:2017-11-03 22:32:34

标签: java arrays

大家好,这是我在本网站的第一篇文章,我还是Java的新手。这是我正在处理的代码。

 public static void main(String[] args) throws Exception {
    // debug
    if ($DEBUG) System.out.println("starting\n");
    //read data from text file into arrays w,p
    String[] wArr = new String[50];
    String[] pArr = new String[50];
    String fileName = "homs.txt";
    readFile(fileName, wArr, pArr);
//main control loop
    while (true) { 
    //use input dialog to get 2 words from user
    String input = JOptionPane.showInputDialog(null,"Enter two words: ");
    String[] words = input.split("\\s+");
    String w1 =  words[0];
    String w2 =  words[1];
    //check each word if in dictionary
    int w1ix = chkFound(wArr, w1);    
    boolean isFound = (w1ix >= 0);
    System.out.println(w1 + " is found: " + isFound);
    int w2ix = chkFound(wArr, w2);
    boolean isFound2 = (w2ix >= 0);
    System.out.println(w2 + " is found: " + isFound2);
      if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 + 
      "\n\tare in dictionary";
         else { msg = "one or more words not in dictionary: ";
            if (w1ix <0) msg += w1 + " ";
            if (w2ix <0) msg += w2 + " ";
       System.out.println(msg);
  //check if homonyms
     boolean isHom = chkHom(pArr, w1, w2);
  //output result
     String line = msg + 
     "\nWord 1: " + w1 +
     "\nWord 2: " + w2 + 
     "\nWord 1 in dictionary: " + isFound + 
     "\nWord 2 in dictionary: " + isFound2 +
     "\nHomonyms: " + isHom;

     JOptionPane.showMessageDialog(null, line);
  //ask user to continue Y/N?
     int cont = JOptionPane.showConfirmDialog(null, "Continue?");
     if (cont > 0)
     break;//exit loop or continue
   }
 //end main
 }
 }

     public static int chkFound(String[] wArr, String w) {
     for (String a : wArr) {       
        if(a.equals(w))
           return 1;               
        }                   
           return -1;

     }//end chkFound

我对此代码的问题是,当我运行它时,它会保持循环

    String input = JOptionPane.showInputDialog(null,"Enter two words: "); 

我认为这个问题的原因是代码的这一部分。我虽然没有想出解决方案。

    public static int chkFound(String[] wArr, String w) {
     for (String a : wArr) {       
        if(a.equals(w))
           return 1;               
        }                   
           return -1;

     }//end chkFound

1 个答案:

答案 0 :(得分:0)

https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION

public static final int     OK_OPTION   0

你的休息时间不起作用

if (cont > 0)
     break;//exit loop or continue

将其更改为:

final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?",  JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}