# Thread: How to loop this program??

1. Member Join Date
Sep 2010
Posts
4
Rep Power
0

## How to loop this program??

ok guys i need a little help here, i have made this program that inputs a fraction and give the output in its simplest forms, the only problem im having is that i nee to edit this coding to that if the user inserts a char, or 0 in the denominator, so the program should give an error message and return to the start until the user wants to exit the program...

here is my coding,

Java Code:
```public class Fraction {
private int numer = 0;
private int denom = 0;

public Fraction(int numer, int denom) {
if (denom == 0)
throw new NumberFormatException("denominator is zero");
this.numer = numer;
this.denom = denom;
this.reduce();
}

public int getNumerator() {
return this.numer;
}

public int getDenominator() {
return this.denom;
}

public void reduce()
{
int	d;

//while (true)
do{
d = this.gcd(this.numer, this.denom);
if (d == 1)
return;
this.numer /= d;
this.denom /= d;
}while(true);
}

private int gcd(int a, int b) {
int	t;

while (b != 0) {
t = a;
a = b;
b = t%a;
}
return (a);
}

public String output() {
return ( this.numer + "/" + this.denom );
}

public double doubleValue() {
return (1.0*this.numer/this.denom);
}
}```  Reply With Quote

2. ## Can you post the code where use the constructor?  Reply With Quote

3. Member Join Date
Sep 2010
Posts
4
Rep Power
0

## Java Code:
```                     public static void main(String[] args) {
Scanner in=new Scanner(System.in);

Fraction	f1;
int n,d;

System.out.print("Enter Numerator: ");
n=in.nextInt();
System.out.print("Enter Denominator: ");
d=in.nextInt();

f1 = new Fraction(n, d);
System.out.println("Fraction Output: " + f1.output());

}
}```
Last edited by 7auz; 12-31-2010 at 06:42 PM.  Reply With Quote

4. ## Using in.nextInt(); is inadvisable, you should read the next line and parse it to an integer:
Integer.parseInt(in.nextLine());
This will throw an exception if the line in not an integer.
Catch that exception and restart that part of the program; use a for( ;; ) or while loop.

If an exception was not thrown, just check if the denominator is 0.  Reply With Quote

5. Senior Member Join Date
Dec 2010
Posts
165
Rep Power
10

## you can use a while loop and a try catch in your main
Java Code:
```    public static void main(String[] args) {
Fraction    f1;
int n,d;
while(true){
try {
Scanner in=new Scanner(System.in);
System.out.print("Enter Numerator: ");
n=in.nextInt();
System.out.print("Enter Denominator: ");
d=in.nextInt();
break;
} catch ( InputMismatchException ex ){
System.err.println("Enter a valid integer");
}
}
f1 = new Fraction(n, d);
System.out.println("Fraction Output: " + f1.output());
}```  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•