2012-03-28 5 views
1

Я хочу, чтобы пользователь мог искать этот короткий список, но я не хочу, чтобы JOptionPane закрывался, если был введен неправильный номер. Также как бы я установил слово terminate, т.е. если пользовательский тип «quit» цикл закончится, и программа выйдет. Я бы использовал цикл while?Могу ли я использовать цикл while?

int key, list[] = {8,22,17,24,15}; 
    int index; 

    key = Integer.parseInt(JOptionPane.showInputDialog(null,"Input the integer to find")); 

    index = searchList(list, key); 

    if(index < list.length) 
     JOptionPane.showMessageDialog(null,"The key " + key + " found the element " + index); 
     else 
     JOptionPane.showMessageDialog(null,"The key " + key + " not found"); 

    System.exit(0); 


} 

private static int searchList(int[] n, int k) { 
    int i; 
    for (i = 0; i < n.length; i++) 
     if(n[i] == k) 
      break; //break loop if key found 
    return i; 
+0

Пожалуйста, поставьте фигурные скобки ('{}') на вашем if-то еще заявлении, просто чтобы сэкономить головные боли. –

+0

Спасибо, ребята, я заработал! –

ответ

1

Я считаю, что цикл while в идеале подходит для таких циклов ввода-вывода, потому что вам нужен хотя бы один IO. Generic псевдокод:

Var command; 
do { 
    command = input(); 
    switch(command){ 
    case opt1 : 
     // do something 
    case opt2 : 
     // do something 
    case default : 
     // unexpected command 
    } 
} while(command != "quit"); 
+0

Псевдоэ код в порядке, Java будет лучше. Есть пара ошибок с этим кодом, если OP пытается наивное преобразование. –

2

Вы могли бы попробовать что-то вроде этого:

import javax.swing.JOptionPane; 


public class Key { 

    public static void main(String[] args){ 

     int key, list[] = {8,22,17,24,15}; 
     int index; 

     String userOption = "null"; 

     while(!userOption.equals("quit")){ 
      userOption = JOptionPane.showInputDialog(null,"Input the integer to find"); 

      //Take the cancel action into account 
      if(userOption == null){ 
       break; 
      } 

      //Try to get valid user input 
      try{ 
       key = Integer.parseInt(userOption); 

       index = searchList(list, key); 

       if(index < list.length){ 
        JOptionPane.showMessageDialog(null,"The key " + key + " found the element " + index); 
        //uncommented the break below to exit from the loop if successful 
        //break; 
       } 
       else 
        JOptionPane.showMessageDialog(null,"The key " + key + " not found"); 

      } catch (Exception e){ 
       //Throw an exception if anything but an integer or quit is entered 
       JOptionPane.showMessageDialog(null,"Could not parse int", "Error",JOptionPane.ERROR_MESSAGE); 
      } 
     } 
     System.exit(0); 
    } 

    private static int searchList(int[] n, int k) { 
     int i; 
     for (i = 0; i < n.length; i++) 
      if(n[i] == k) 
       break; //break loop if key found 
     return i; 

    } 
} 

Это не совершенный код, но он должен делать эту работу. Если у вас есть какие-либо вопросы, я был бы более чем счастлив помочь.

Счастливый Coding,

Hayden

Смежные вопросы