Home > Software design >  How to ensure certain requirements are met in my Java Program
How to ensure certain requirements are met in my Java Program

Time:02-17

public class FileAddClient {

  public static void main(String[] args) throws FileNotFoundException {
    Scanner scanfile = new Scanner(System.in);

    System.out.println("What is the exact name of your file?");
    String doc = scanfile.next();

    Scanner scanint = new Scanner(new File(doc));

    int number1 = scanint.nextInt(), number2 = scanint.nextInt(),
    number3 = scanint.nextInt(), number4 = scanint.nextInt(),
    number5 = scanint.nextInt(), number6 = scanint.nextInt();

    int sum = number1   number2   number3   number4   number5   number6; 

    System.out.println("The sum of the numbers that typed is "   sum);

  }

}

How can I ensure that the user enters at least 2 numbers into the file and that the only data types in the file are numbers? I am not sure how to navigate through this problem. I tried making a while loop, but, unfortunately, that is not working. Any help would be appreciated.

CodePudding user response:

The method .nextInt() will throw an exception (specifically an InputMismatchException) in case the input is not an int or there is none. You can handle that exception with a try-catch block, like this:

try {
    // ... use nextInt ...
}
catch(InputMismatchException e) {
    // print error message
}

CodePudding user response:

My solution to this uses a while loop. The hasNextInt() function just checks if the input is of type int.

public class FileAddClient {

  public static void main(String[] args) throws FileNotFoundException {
    Scanner scanfile = new Scanner(System.in);

    System.out.println("What is the exact name of your file?");
    String doc = scanfile.next();

    Scanner scanint = new Scanner(new File(doc));

    int count = 0;
    int sum = 0; //total sum of numbers

    while ( scanint . hasNextInt() ) { //makes sure that the input is of type int
      count   ; //counts the number of correct inputs
      sum  = scanint.nextInt();
    }

    if ( count < 2 ) // file has one number or zero numbers
      System.out.println ( "File has less numbers than expected. Please fix it." );
    else if ( count > 6 ) //file has more than 6 numbers
      System.out.println ( "File has more than 6 numbers." );
    else // file has two numbers or more
      System.out.println("The sum of the numbers that typed is "   sum);
  }
}
 
  •  Tags:  
  • java
  • Related