2017-04-25 26 views
0

我需要製作一個程序,允許我向用戶詢問一些數字並繼續這樣做,直到用戶輸入'q',但我似乎無法讓hasNextInt像我認爲的那樣工作。我對Java很陌生,並且在做地面課程。如何將一個掃描儀用於整數和文本?

這是我迄今所做的

public class Matte 
{ 
    public static void main (String[] args) 
    { 

     int r1 = 0; 
     int h1 = 0; 
     int r2 = 0; 
     int h2 = 0; 
     int level = 1; 

     String choice = new String(); 

     Scanner values = new Scanner(System.in); 
     values.useDelimiter("\\s"); 

     if (level == 1) 
     { 
      if(!values.hasNextInt()) 
       r1 = values.nextInt(); 
      else choice = values.nextLine(); 
      if(!values.hasNextInt()) 
       h1 = values.nextInt(); 
      else choice = values.nextLine(); 
      if(!values.hasNextInt()) 
       r2 = values.nextInt(); 
      else choice = values.nextLine(); 
      if(!values.hasNextInt()) 
       h2 = values.nextInt(); 
      else choice = values.nextLine(); 
     }  

    } 
} 

我要救什麼都文本掃描儀輸入在「選擇」可變

如何做呢?

+0

您能否提供樣品輸入和樣品輸出? –

+0

看起來很奇怪,你檢查下一個是否是int,如果不保存爲整數? 'String.valueOf(values.nextLine())' – cYrixmorten

+0

如何在'hasNextInt()'爲** false **時調用'nextInt()'? – shmosel

回答

0

我沒有真正理解你的問題,但是這裏有一個解決你的問題的方法,將這些整數添加到ArrayList中,並在用戶鍵入'q'時停止程序。希望它可以幫助你。乾杯!

public class Matte 
{ 
    public static void main (String[] args) 
    { 

     ArrayList<Integer> numbers = new ArrayList(); 
     int level = 1; 

     String choice; 

     Scanner values = new Scanner(System.in); 
     values.useDelimiter("\\s"); 

     if (level == 1) 
     { 
      while(true){ 
       choice = values.nextLine(); 
       if(choice.equals("q")) 
        break; 
       else 
        numbers.add(Integer.parseInt(choice)); 
      } 
     }  

    } 
} 
+0

'else {try {numbers.add(Integer.parseInt(choice)); } catch(Exception e){/ *忽略輸入,因爲它不是數字* /}}' – cYrixmorten

+0

如何訪問arraylist中的數字?不能像普通數組一樣工作。 – Mattias

+0

在這種情況下它將會是:「numbers.get(0)」來訪問索引0; –