Mit program, som løser problemet, er følgende:/* Læs et tal fra en linie af tegn, og retur det pågældende tegn som en int */
import java.io.*; // for at kunne anvende BufferedReader mv.
class talLaesning {
//et objekt, kaldet stdin, som tillader os at læse en tekst linie:
static BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
public static int readInt() throws IOException{
/* Read an integer from the keyboard, and return it as the result of this function */
String textLine;
char nextCifferChar;
int nextCiffer;
textLine = stdin.readLine();
int i, tal;
boolean positive = true; // the sign of the number
boolean cifferRead = false; // have we seen the first ciffer
tal = 0;
for(i=0; i<textLine.length(); i++){
nextCifferChar = textLine.charAt(i);
if (Character.isDigit(nextCifferChar)){
cifferRead = true;
nextCiffer = Character.digit(nextCifferChar,10);
tal = tal * 10 + nextCiffer;
}
else if (nextCifferChar == '-' && !cifferRead) {
positive = !positive;
}
else if (nextCifferChar == '+' && !cifferRead) {
// just ignore it
}
else System.out.println(nextCifferChar + " er et ulovligt tegn");
}
return positive ? tal : -tal;
}
public static void main (String[] ars) throws IOException{
System.out.println("Indlaes et tal");
int etTal = readInt();
System.out.println("Tallet var: " + etTal);
}
}