Wednesday, 28 August 2013

Trouble trying to restart my Java program

Trouble trying to restart my Java program

After looking up numerous ways to restart a Java program within itself, a
while loop seemed like the easiest option. Here's an example of a basic
calculator program I'm trying this with:
import java.util.Scanner;
class a {
public static void main(String args[]){
boolean done = false;
int oper;
Scanner input = new Scanner(System.in);
System.out.println("McMackins Calc v2.0 (Now with fewer crashes!)");
while (!done)
{
System.out.println("What operation? (0 for quit, 1 for add, 2 for
subtract, 3 for multiply, 4 for divide, 5 for divide with remainder, 6
for average, 7 for account interest):");
while (!input.hasNextInt()){
System.out.println("Enter a valid integer.");
input.next();
}
oper = input.nextInt();
switch (oper){
case 0:
done = true;
break;
case 1:
add addObject = new add();
addObject.getSum();
break;
case 2:
sub subObject = new sub();
subObject.getDifference();
break;
case 3:
times multObject = new times();
multObject.getProduct();
break;
case 4:
divide divObject = new divide();
divObject.getQuotient();
break;
case 5:
remain remObject = new remain();
remObject.getRemainder();
break;
case 6:
avg avgObject = new avg();
avgObject.getAvg();
break;
case 7:
interest intObject = new interest();
intObject.getInterest();
break;
default:
System.out.println("Invalid entry.");
break;
}
}
input.close();
}
}
However, this seems to throw out a NoSuchElementException at the end of
the first time through the loop, and crashes the program. The function of
this class is to take the initial input from the user to determine which
class to use, which will determine which mathematical operation to
perform. Everything works fine without the while (!done) loop.
I've also tried just having the other classes refer back to this one, but
since main is a static method, I cannot access it the way I intended.
Note that I'm a bit of a beginner at Java, which is why my program is
pretty simple, so try to keep it simple if it can be, or post code and
then in DETAIL explain what it means so I can not only fix this problem,
but future ones as well.
Thank you!

No comments:

Post a Comment