简体   繁体   English

减法程序中的一个非常简单的错误

[英]A very simple error in subtraction program

I am facing a very simple error in the following program at the last print statement. 我在最后一个打印语句的以下程序中遇到一个非常简单的错误。 But I dont know the exact reason behind it. 但我不知道背后的确切原因。 Even the logic is correct and syntax too. 甚至逻辑是正确的,语法也是如此。

Please let me know the exact reason for the error. 请让我知道错误的确切原因。

Thanks 谢谢

import java.util.Scanner;
public class main
{
    public static void main(String args[])
    {
        int c,d;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the first number : ");
        c = s.nextInt();
        System.out.print("Enter the second number : ");
        d = s.nextInt();

        System.out.println("The sub is : "+ c-d);

    }
}

You need parentheses around the subtraction: 您需要在减号周围加上括号:

System.out.println("The sub is : " + (c - d));

This is because without parentheses, the + and - operators have the same priority and associate left-to-right. 这是因为没有括号, +-运算符具有相同的优先级,并且从左到右关联。 So the compiler tries to parse it as if it were written: 因此,编译器将尝试对其进行解析,就像编写它一样:

System.out.println(("The sub is : " + c) - d);

The first part is okay and is an expression that produces a String result. 第一部分是可以的,并且是一个生成String结果的表达式。 Unfortunately, there is then no way to apply the - operator to an expression where the left side is a String and the right side is an int . 不幸的是,然后无法将-运算符应用于左侧为String且右侧为int的表达式。

that's because, you are trying to do string concatenation, as your first operand is a string. 这是因为,您尝试进行字符串连接,因为您的第一个操作数是字符串。

try this: 尝试这个:

System.out.println("The sub is : "+ (c-d));

notice that (cd) in brackets. 注意括号中的(cd)。

compiler would complain that - operator is un-defined for string and int. 编译器会抱怨-字符串和整数未定义运算符。

The operator - is undefined for the argument type(s) String, int 未定义参数类型的运算符-字符串,整数

Note that the Sub is:+ c the result would be a string. 注意Sub is:+ c结果将是一个字符串。 now 现在

`Sub is:+ c` - d;
^^String     - int

use 采用

System.out.println("The sub is : "+ (c-d));

instead of 代替

System.out.println("The sub is : "+ c-d);

and check if its working now. 并检查其是否可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM