Home > other >  Parsing Integers in Java, making code continuous
Parsing Integers in Java, making code continuous

Time:03-11

I have a code that accepts String as an input and parses it into a number. Here, whenever user input consists of elements that is not a number it will throw a NumberFormatException. However, I want to make it continuous,such as if program ran one time, it does not terminate but rather waits for further input.

public class ParseNumbers {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);// reading from standard input
        
        String line = scan.nextLine(), word = null;
       
       
        scan = new Scanner(line); 
      
      
        int sum = 0, count = 0;
      while(scan.hasNextLine()){ 
           
           word = scan.next();
           sum  = Integer.parseInt(word);
           count  ;
          
      }
      try{
        if (count ==0)

            System.out.println("There are no VALID input provided!");
           
        else
        
         System.out.printf("Sum = %d\nCount = %d\nAverage = %.3f\n", sum, count, (float) sum / count);
         
        }catch(NumberFormatException e){
             System.out.println(e.getMessage());
             
         }
   


      
    
    }
}

CodePudding user response:

Make a function to check if given string can be converted to int:

public static boolean isInteger(String str) {
    if (str == null) {
        return false;
    }
    int length = str.length();
    if (length == 0) {
        return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
        if (length == 1) {
            return false;
        }
        i = 1;
    }
    for (; i < length; i  ) {
        char c = str.charAt(i);
        if (c < '0' || c > '9') {
            return false;
        }
    }
    return true;
}

Note: I copied this function from this thread

And than edit your code to something like this:

      while(scan.hasNextLine()){ 
           
           word = scan.next();
           if (isInteger(word)) {
              sum  = Integer.parseInt(word);
              count  ;
           } else {
              System.out.println("Not a number");
           }
      }

CodePudding user response:

As @Johnny Mopp said. You can use try/catch, and inside catch break the loop the get the output wanted:

        try {
            sum  = Integer.parseInt(word);
        } catch (Exception e) {
            break;
        }

output:

h
There are no VALID input provided!
  •  Tags:  
  • java
  • Related