2017-04-25 47 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; –