2

I am a beginner in Java so I wrote a program to understand the OOP concepts but it gives me an error when trying to use System.out.println(). Here's the code

public static void main(String[] args) {
    sampleClass ADD = new sampleClass();
    Scanner input = new Scanner(System.in);
    int fNum;
    int sNum;
    System.out.println("Enter the first number to Add");
    fNum = input.nextInt();
    System.out.println("Now enter the second number");
    sNum = input.nextInt();
    int sum;
    sum = ADD.add(fNum, sNum);
    System.out.println("The sum of " fNum " and " sNum " is " sum);
}
4

3 回答 3

2

Replace this line System.out.println("The sum of " fNum " and " sNum " is " sum); with

System.out.println("The sum of " +fNum+ " and " +sNum+ " is " +sum);

Please Note: In Java, the operator "+" normally acts as an arithmetic operator unless one of its operands is a String. If necessary it converts the other operand to a String before joining the second operand to the end of the first operand.

Examples:

If one of the operands is not a String it will be converted:

int age = 12; 
 System.out.println("My age is " + age); 
于 2013-04-16T17:59:17.143 回答
2

Sign "+" is used for concatenation and you missed it between your String.

The correct format is:

System.out.println("The sum of " + fNum + " and " + sNum + " is " + sum);

于 2013-04-16T18:11:01.697 回答
1

You're missing some +'s between things like "The sum of " and fNum, e.g. "The sum of " + fNum + ....

于 2013-04-16T17:58:53.087 回答