-3

when i try to input this integer i get an error -10 20 -40 << error the output should be 80

{ 
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] input = new String[n]; 
  for (String input1 : input) {
      input = in.readLine().split(" ");
      int x = Integer.parseInt(input[0]);
      int y = Integer.parseInt(input[1]);
      int z = Integer.parseInt(input[2]); 
      if (y - x == z - y)
      {
          System.out.println(z+ y - x);
      }
      else
      {  //-10 20 -40
          System.out.println(z / (x / y));
      }

2 Answers2

0

Consider using double instead of int since it only can store whole numbers. -10/20 becomes -0.5 but is converted to 0. Here is what you can do:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    String[] input = new String[3];
    for (String input1 : input) {
        input = "-10 20 -40".split(" ");
        double x = Double.parseDouble(input[0]);
        double y = Double.parseDouble(input[1]);
        double z = Double.parseDouble(input[2]);
        if (y - x == z - y) {
            System.out.println(z + y - x);
        } else {  //-10 20 -40
            System.out.println(z / (x / y));
        }
    }
}

Output:

80.0
libanbn
  • 260
  • 1
  • 8
0

z / (x / y) results in division by zero.

Why?

Because x / y == -10 / 20 == 0.

Why?

x and y are ints so the / in x / y means integer division. In integer division, 20 goes into -10 zero times, with a remainder of -10. The remainder is discarded and the result is the quotient of zero.

The solution: force (x / y) to be evaluated in double arithmetic by casting either x or y to double:

z / ((double)x / y)   
z / (x / (double)y)

Now, because (x / y) is a double, z / (x / y) is also evaluated in double math. And in double math, x / y == -0.5, -40 / -0.5 == 80

Kevin Anderson
  • 4,388
  • 2
  • 10
  • 20