I'm supposed to write a program where the user types in a number, and then the program either adds the number to the result (if the number typed was odd), or divides the result by the number typed in (if the number typed was even, and 0 is even). There are two types of errors that can occur:
- if the user types in 0 -> division by 0 (I got that to do what I want)
- if the user types in something other than a number (i.e. letters) -> the program should write out an error message and then quit
Right now if the user types in letters or something, they get a message "Error in number, try again." and then the program keeps going. Here is the code:
import java.io.*;
import javagently.*;
public class Uppg8_CS {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
int tal = 0;
Nummer resultat = new Nummer(0);
System.out.println("Resultatet är: " + resultat.varde());
// System.out.println("T E S T");
while (tal!=99) {
try {
// System.out.println("T E S T");
BufferedReader in = Text.open(System.in);
System.out.print("Mata in ett tal (99 avslutar): ");
tal = Text.readInt(in);
if (tal%2 == 0) {
resultat.dividera(tal);
} else {
resultat.addera(tal);
} // end of if-else
System.out.println("Resultatet är nu: " + resultat.varde());
} // end of try
/* takes care of when 0 is typed in */
catch (ArithmeticException a) {
System.out.println("Ojdå, division med noll! Nytt försök...");
} // end of catch
} // end of while
} // end of main
}
/* a class Nummer which I'm supposed to use */
class Nummer {
private int num = 0;
public Nummer(int tal) {
this.num = tal;
} // Nummer
public void addera(int tal) {
this.num = this.num + tal;
} // addera
public void dividera(int tal) {
this.num = this.num / tal;
} // dividera
public int varde() {
return this.num;
}
}
And the code for the package javagently:
public class Text {
/* some code irrelevant to this... */
public static int readInt (BufferedReader in) throws IOException {
if (T==null) refresh(in);
while (true) {
try {
return Integer.parseInt(T.nextToken());
}
catch (NoSuchElementException e1) {
refresh (in);
}
catch (NumberFormatException e2) {
System.out.println("Error in number, try again.");
}
}
}
/* some more irrelevant code... */
So my question is: how do I make so my error comes instead of the automatic one? and how do I make the program quit if that error comes?
Thanks a lot,
Christa
**Edit**
PS tell me if you need something translated...