user3524998
user3524998

Reputation: 25

check for positive integers only. no negative integer, no non-numeric strings

I have to write a java program that computes the greatest common divisor of two positive integers. Program has to check for the positive integers only. My problem is that when I enter a negative integer and then a non-numeric string, my program stops running. Bellow is my code:

import java.util.Scanner;
class GCD {
    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);
        int a, b, m, n, remainder;
        System.out.print("Enter a positive integer: ");
        while (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
        }
        a = sc.nextInt();
        while (a <= 0){
            System.out.print("Please enter a positive integer: ");
            a = sc.nextInt();
        }


        System.out.print("Enter another positive integer: ");
        while (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
        }
        b = sc.nextInt();
        while (b <=0){
            System.out.print("Please enter a positive integer: ");
            b = sc.nextInt();
        }

        m = a;
        n = b;
        while (n != 0){
            remainder = m%n;
            m = n;
            n = remainder;
        }
        System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
    }
}

Upvotes: 0

Views: 1798

Answers (4)

Basti
Basti

Reputation: 1186

In your first while you call next(), but in your second you use nextInt(). If you enter at the first time a negative Integer, you ll step to the next while with the nextInt(). So you ll get an exception if the user is entering a String with something else than numbers, because the scanner cant get the value of keys or something else. A smarter way would be to catch the exception and use it for a endless while like this:

while(true)
   System.out.print("Please enter a positive Number: ");
   try{
      a = sc.nextInt();
      if(a>-1){
         break;
      }
   }catch(Exception ignore){
   }
}

This code will run until the user enters a positive number. If he enters something else than numbers, the exception will come and will be ignored and the while will go on, if the number was not positive (bigger than -1 in this case) the while will not break.

Upvotes: 0

Eliott Roynette
Eliott Roynette

Reputation: 734

It shound work, even if i don't try it. I have just 2 advise as you look new in coding : -When you make code, try to use function. Normally, you should never copy/paste. -Try to put full name to your variable, particulary if you share your code on a forum, it would be more simple to people to understand what you did, and help you :)

     import java.util.regex.Pattern;
     import java.util.Scanner;
     class GCD {
        public static void main (String[] args){
          Scanner sc = new Scanner(System.in);
          int a, b, m, n, remainder;
          a=askInt();
          b=askInt();
          m = a;
          n = b;
          while (n != 0){
          remainder = m%n;
          m = n;
          n = remainder;
          }
          System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
       }

     private int askInt(){
          System.out.print("Enter a positive integer: ");
          String tampon = sc.nextLine();
          while(!Pattern.matches("\p{Digit}",tampon)){
              System.out.print("Please enter a positive integer: ");
              String tampon = sc.nextLine();
          }
          return Integer.valueOf(tampon);
     }
  }

Upvotes: 0

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

Try this:

import java.util.Scanner;
public class A {
    public static void main (String[] args){
        int a, b, m, n, remainder;
        a = validInput();
        b = validInput();
        m = a;
        n = b;
        while (n != 0){
            remainder = m%n;
            m = n;
            n = remainder;
        }
        System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
    }

    static int validInput() {
        Scanner sc = new Scanner(System.in);
        while(true){
            System.out.print("Please enter a positive integer: ");
            String tmp = sc.next();
            if (tmp.matches("^\\d+$")) {
                return Integer.parseInt(tmp);
            }
        }
    }
}

I suggest you to make your programs more modular, as you can see it's benefits in a simple program like this.

Upvotes: 1

Andrew Vitkus
Andrew Vitkus

Reputation: 817

/* prompt a */
String a = sc.next();

/* prompt b */
String b = sc.next();

if (isValid(a) && isValid(b)) {
    int ia = Integer.parseInt(a);
    int ia = Integer.parseInt(b);

    /* calculations and such */
}

boolean isValid(String num) {
    try {
        int i = Integer.parseInt(num);
        if (i < 0) {
            return false;
        }
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

Upvotes: 0

Related Questions