Home > Net >  trying to save multiple inputs from the same scanner in a while loop
trying to save multiple inputs from the same scanner in a while loop

Time:10-03

I'm trying to get multiple integer values from the same scanner inside a while loop. I need to store all the values so I can use them later. However I can only get the last value from the scanner when the while loop finishes.

int antalHeltal = Integer.parseInt(Antal);             
int noll = 1;                                          
int heltal = 0;                                        
String tal1 = "";                                      
Scanner tal = new Scanner(System.in);                  
while (noll <= antalHeltal) {                          
     noll  = 1;                                        
    heltal  = 1;                                       
    System.out.print("ange heltal "   heltal   ": ");  
                                                       
    tal1 = tal.next();                                 
                                                       
        try {                                          
            Integer.parseInt(tal1);                    
        } catch (NumberFormatException e) {            
            System.out.println("Ogiltigt värde");      
            noll -= 1;                                 
            heltal -=1;                                
        }                                              

My variables are written in Swedish so sorry in advance but I hope someone can help me with this. It would be much appreciated.

CodePudding user response:

Use a List since it can grow dynamically:

Scanner tal = new Scanner(System.in);                  

List<Integer> list = new ArrayList<>();   // *** Add this

while (noll <= antalHeltal) {                          
    noll  = 1;                                        
    heltal  = 1;                                       
    System.out.print("ange heltal "   heltal   ": ");  
                                                   
    tal1 = tal.next();                                 
                                                   
    try {  
        // **********************************
        int num = Integer.parseInt(tal1);                          
        list.add(num);     
        // **********************************
    } catch (NumberFormatException e) {            
        System.out.println("Ogiltigt värde");      
        noll -= 1;                                 
        heltal -=1;                                
    }    

To later access the List:

for (int i = 0; i < list.size(); i  ) {
    System.out.println(list.get(i));
}

or....

for (int val : list} {
    System.out.println(val);
}  
  • Related