检查类型和打印结果的三个整数值

时间:2016-04-10 13:19:55

标签: java

import java.io.*;
public class Test {
public static int ReadInt1(){
    int x;
    try {
    x = (int)System.in.read();
    return x;
    }catch (IOException e) { 
        System.out.println("Exception: " + e.toString()); 
        return 0; 
    }catch (NumberFormatException e) { 
        System.out.println("Exception: " + e.toString() + "\nReturned value: -1"); 

        return-1; 
    }
}    
public static int ReadInt2(){
    int y;
    try {
    y = (int)System.in.read();
    return y;
    }catch (IOException es) { 
        System.out.println("Exception: " + es.toString()); 
        return 0; 
    } catch (NumberFormatException es) { 
        System.out.println("Exception: " + es.toString() + "\nReturned value: -1"); 
        return-1;
    }
}
  public static int ReadInt3(){
   int z;
    try {
    z = (int)System.in.read();
    return z;
    }catch (IOException ed) { 
        System.out.println("Exception: " + ed.toString()); 
        return 0; 
   } catch (NumberFormatException ed) { 
   System.out.println("Exception: " + ed.toString() + "\nReturned value: -1"); 
   return-1; 
   }    
}  
public static void main(String args[]){
System.out.println("Type a number1");   
int x = ReadInt1();
System.out.println("Type a number2");   
int y = ReadInt2();
System.out.println("Type a number3"); 
int z = ReadInt3();
 if (x-3*z !=0){
    System.out.println((3*(x-2)*y)/(x-3*z));
 }else throw new ArithmeticException();
}
} 

我想要做的是输入3个整数,检查它们是否为整数,然后在检查分母后打印(3 *(x-2)* y)/(x-3 * z)的结果。问题是在我键入第一个数字后1.如果它不是int,程序打印'Type a number2'和3,不允许我给出任何数字并打印结果。 2.如果是int,则打印'Type a number2' '键入数字3',然后让我输入一个数字。我也不知道程序是如何得出这些结果的。

1 个答案:

答案 0 :(得分:0)

此方法System.in.read();只读取一个字节。例如,当您键入

1<enter>

1<enter>各一个字节。 1将是49,它是1的ASCII码,字节将是10,它是^ J或返回/输入的ASCII码。

您很可能想要将数字作为文本读取并将其解析为int值,如下所示

Scanner sc = new Scanner(System.in);
System.out.println("Type a number1");   
int x = sc.nextInt();
System.out.println("Type a number2");   
int y = sc.nextInt();
System.out.println("Type a number3"); 
int z = sc.nextInt();
System.out.println(3.0 * (x-2) * y / (x - 3 * z));

注意:我使用值3.0所以当你进行除法时,你得到一个浮点值而不是整数除法。