-1

Okay I can't seem to find a definitive answer to my problem.

I need a program in java that can return a value that the user enters, that is a positive integer.

To differentiate this to many other similar questions, I need to program to not crash upon entering a string. The program will need to repeated prompt the user for a input until a positive integer is inputted. The script would be something like this:

Input: 7.2
Error, try again: -5
Error, try again: -2.4
Error, try again: 3.77777
Error, try again: -1
Error, try again: 0
Error, try again: -33
Error, try again: microwave
Error, try again: -1
Error, try again: 4.2
Error, try again: hello
Error, try again: 3.14159
Error, try again: 4
4 is a positive integer.

It is important that the program does not crash when something like a word is entered. I can't figure out a way for the program to do something like this. I could use hasNextInt with the scanner, but then I don't know how to check if its greater than zero as the input could be a string in another case.

Could someone help me out with a program that would return the above script? Hugely appreciated.

EDIT: Okay I finally found the answer I was looking for in a different question. This solution does not use parseInt(), nor does it use try/catch, which was what I was looking for. Nice and simple. So here is the solution code:

    Scanner in = new Scanner(System.in);
    int num;
    System.out.print("Input: ");
    do {
        while (!in.hasNextInt()) {
            System.out.print("Error, not integer. Try again: ");
            in.next(); 
        }
        num = in.nextInt();
        if (num<=0){
            System.out.print("Error, not positive. Try again: ");
        }
    } while (num <= 0);
    System.out.println(num + " is a positive integer.");
kcarew98
  • 17
  • 1
  • 4
  • 2
    read in `nextLine`, use a `try-catch` and parse to `Integer`, catch the Exception. If no exception occured, check if `num<0`? – SomeJavaGuy Dec 23 '16 at 11:38
  • @KevinEsche Not too familiar with `try-catch`, could you elaborate a little and show me how it's used in code? Sorry, I'm not very smart :( – kcarew98 Dec 23 '16 at 11:45

5 Answers5

1

Try it this way:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int value = -1;
    do {
        System.out.print("Input: ");
        String input = scanner.next();
        try {
            value = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Error, try again: " + input);
        }
    } while (value < 1);
    System.out.println(value + " is a positive integer.");
}
Harmlezz
  • 7,524
  • 23
  • 34
0

Here is a link to exception handling in java. Generally you need to just put your code to a try block. Then if expected exception occures in that block, your program will execute code in catch block and continue it's work.

0

You need to somehow validate the input. If you input is a Integer. then you need to print it to the screen, if your input is a Long then you need to print the error message Try again.

In this example below I created a method that is an derivative of the C# TryParse method. C# TryParseInt

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        while (true)
        {
            @SuppressWarnings("resource")
            Scanner reader = new Scanner(System.in); 
            System.out.println("Enter a number: ");

            String input = reader.next();
            tryParseInt(input);
        }
    }

    private static void tryParseInt(String input) {  
        try {  
            int val = Integer.parseInt(input);
            System.out.println(val + " is a positive Integer");
        } catch (NumberFormatException e) {
            System.out.println(input + " Is not a number/positive Integer, " + e.getMessage());
        }  
    }
}

What this does is it parses the input to a Integer, if it fails to do so because the input is a String or not a valid positive Integer the an NumberFormatException is thrown. I can then print the error message I want.

Good Luck!

Igoranze
  • 1,376
  • 10
  • 30
0

Below are for 2 scenarios:

Scenario 1:
- I assume Positive Integers refers to Integers 1,2,3,4, etc...
- Values such as 4.00 will NOT be treated as an integer

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int value = 0;
        System.out.print("Input: ");

        while (value < 1){
            String input = scanner.next();
            try {
                value = Integer.parseInt(input);
                if(value < 1){
                    System.out.print("Error, try again: ");}
            } catch (NumberFormatException e) {
                System.out.print("Error, try again: ");
            }
        }
        System.out.println(value + " is a positive integer.");
    }
}

Scenario 2:
- I assume Positive Integers refers to Integers 1,2,3,4, etc...
- Values such as 4.00 will be treated as an integer

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Input: ");
        String value = "";
        boolean positiveIntegerNoDecimals = false;
        while (positiveIntegerNoDecimals == false) {
            value = scanner.next();
            positiveIntegerNoDecimals = isPositiveIntegerNoDecimals(value);

            if (positiveIntegerNoDecimals == false)
                System.out.print("Error, try again:");
        }
        System.out.println(value + " is a positive integer.");
    }

    private static boolean isPositiveIntegerNoDecimals(String input) {
        try {
            int value = -1;
            BigDecimal decimal = new BigDecimal(Double.parseDouble(input));
            int scale = decimal.scale();
            if (scale == 0)
                value = decimal.stripTrailingZeros().intValue();

            if (value > 0)
                return true;
        } catch (NumberFormatException e) {}
        return false;
    }
}
-1

Integer.parseInt(String s)

is written just for this.

Azodious
  • 13,385
  • 1
  • 32
  • 68