yhware
yhware

Reputation: 532

checking if scanner input as positive integer

I know there are a lot of questions already on the website about this issue but i still cant get the hang of it in my program.

import java.util.Scanner;
public class time {
public static void main (String[] args) {
    int a, sec, min, hour;

    System.out.println ("Please enter the number of seconds");
    Scanner user_input = new Scanner (System.in);
    a = user_input.nextInt();

    while (!user_input.hasNextInt()) {
        System.out.println ("Error: INVALID INPUT, please try again");
        System.out.println("Please enter the number of seconds");
        a = user_input.nextInt();
    }

    hour = a/3600;
    min = ((a%3600)/60);
    sec = ((a%3600)%60);

    System.out.println(hour + " hours "+ min+ " minutes " + sec + " seconds");

}
}

so the above is my program. I am just starting to learn JAVA so I tried my best but every time i run this program, it gives me nothing.

I input a number and nothing comes up but the program is still running.

The strange thing is.. when I change the

!user_input.hasNextInt() 

with a<0, it works but that isn't good enough for me because it cant check for double inputs nor empty inputs.

Upvotes: 0

Views: 4209

Answers (5)

Bohemian
Bohemian

Reputation: 425083

You need to read user input as a String - theres no getting around that, because you have to be able to handle invalid input. So, you'll need to:

String input = scanner.next();

As for checking, it depends what you mean by "integer".

If it means the usual meaning of "whole number", you can test that like this:

if (input.matches("\\d+"))
    // it's a (positive) whole number

If it means a valid java int value, that's more complicated due to the range of values of the type. Use:

try {
    int i = Integer.parseInt(input);
    if (I > 0) 
        // input is valid
} catch (NumberFormatException e) {
    // input is not a valid java int
}

Upvotes: 0

Omar Mainegra
Omar Mainegra

Reputation: 4184

Try instead:

import java.util.Scanner;

public class time {
    public static void main(String[] args) {
            long sec, min, hour;

            System.out.println("Please enter the number of seconds");
            Scanner user_input = new Scanner(System.in);

            sec = -1;

            while (user_input.hasNextLong() && (sec = user_input.nextLong()) < 0) {
                    System.out.println("Error: INVALID INPUT, please try again");
                    System.out.println("Please enter the number of seconds");
            }

            if (sec > 0) {
                    hour = sec / 3600;
                    min = ((sec % 3600) / 60);
                    sec = ((sec % 3600) % 60);

                    System.out.println(hour + " hours " + min + " minutes " + sec + " seconds");
            }

    }
}

Upvotes: 1

Dom
Dom

Reputation: 1722

Try this instead. By calling nextLine() instead of nextInt() and try to parse the result we eliminate any bad inputs and keep the program running in any input case.

import java.util.*;
public class time
{
    public static void main (String[] args) 
    {
        int time, sec, min, hour;
        String inputString;
        System.out.println ("Please enter the number of seconds");
        Scanner user_input = new Scanner (System.in);
        time = -1;
        inputString = user_input.nextLine();

        try
        {
            time = Integer.parseInt(inputString);
        }
        catch(NumberFormatException e)
        {
            time = -1;
        }

        while (time < 0)
        {
            System.out.println ("Error: INVALID INPUT, please try again");
            System.out.println("Please enter the number of seconds");
            inputString = user_input.next();

            try
            {
                time = Integer.parseInt(inputString);
            }
            catch(InputMismatchException e)
            {
                time = -1;
            }
       }


      hour = time/3600;
      min = ((time%3600)/60);
      sec = ((time%3600)%60);

      System.out.println(hour + " hours "+ min+ " minutes " + sec + " seconds");

  }
}

Edit: IsEmpty() didn't work right, but removing it and just initializing time as -1 fixed it.

Upvotes: 0

TwoThe
TwoThe

Reputation: 14269

You can often make things simpler by using the "Divide & Conquer" approach. In this case using a function to read the user input properly simplifies the task a lot:

  static int getSecondsFromUser() {
    final Scanner userInput = new Scanner(System.in);

    while (true) {
      System.out.println("Please enter the number of seconds:");
      try {
        return userInput.nextInt();            
      } catch (InputMismatchException e) {
        userInput.skip(".+");
      }
    }
  }

  public static void main(String[] args) {
    final int a = getSecondsFromUser();

    final int hour = a / 3600;
    final int min = ((a % 3600) / 60);
    final int sec = ((a % 3600) % 60);

    System.out.println(hour + " hours " + min + " minutes " + sec + " seconds");
  }

The expression userInput.skip(".+"); uses a regular expression .+ that means "everything".

The "contract" with the function is, that it will return a proper int value, therefore your main function doesn't need to worry about that, it can just use the value and assume that it is correct. You can as well add further checks like >0 if you want, I skipped these for simplicity. As the scanning happens inside a function, you can "jump out" by using return as soon as you have the correct value, which solves a lot of complexity.

In addition this makes your code more easy to read, fix and reuse.

Upvotes: 0

Muhammed Refaat
Muhammed Refaat

Reputation: 9103

This Will Work With You In All Conditions :

import java.util.InputMismatchException;
import java.util.Scanner;

public class time{
public static void main (String[] args) {
    int a = 0, sec, min, hour;
    boolean cond = true;

    while(cond){
    boolean mis = false;
    System.out.println ("Please enter the number of seconds");
    Scanner user_input = new Scanner (System.in);
    try{
    a = user_input.nextInt();
    }
    catch(InputMismatchException e){
        System.out.println ("Error: INVALID INPUT, please try again");
        cond = true;
        mis = true;
    }
    if ((a<0 || a != (int)a) && mis == false) {
        System.out.println ("Error: INVALID INPUT, please try again");
       cond = true;
    }
    else if(mis == false){
        cond = false;
    }
    if(cond == false){
        break;
    }
    }
    hour = a/3600;
    min = ((a%3600)/60);
    sec = ((a%3600)%60);

    System.out.println(hour + " hours "+ min+ " minutes " + sec + " seconds");

}
}

Upvotes: 0

Related Questions