dead man's party
dead man's party

Reputation: 29

Adding the sum of three integer numbers in Java

Have to find the sum of 3 integers, the numbers are 10,15, and 20.

Tried using scanner, but it would not work for some reason. If I tried to close it, it would error.

import java.util.Scanner; //used for question 2
public class firstassignment {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //question 1: the Largest Number
        int num1 = 10;
        int num2 = 5; 
        int num3 = 20;

          if( num1 >= num2 & num1 >= num3)
              System.out.println(num1+" is the largest Number");
          //if num1 is greater or equal to both num2 & 3, then num1 is the largest number.
          // & compares both, does not go left to right like && will.

          else if (num2 >= num1 & num2 >= num3)
              System.out.println(num2+" is the largest Number");
          // otherwise, if num2 is greater of less than num1 and num3, then num2 is the greatest number.

          else
              System.out.println(num3+" is the largest Number");

          //if all else is false, then num3 is the greatest number.
          //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    {
      //question 2: sum of 3 numbers
        int num1=10;
        int num2=15;
        int num3=20;
        int finalResult=num1+num2+num3;
         System.out.println(finalResult+"is the sum of the three integers");

Although it shows there is no error in the code, it will not output the sum at all.

Upvotes: 1

Views: 3938

Answers (1)

AGATEVURE GLORY
AGATEVURE GLORY

Reputation: 21

if you have to use Scanner to get the sum of the three numbers your code should look like this

//question 2: the sum of 3 numbers

import java.util.Scanner;

public class SecondAssignment {

    public static void main(String[] args) {

        Scanner in  = new Scanner(System.in);
        System.out.println("Enter number 1");
        int num1 = in.nextInt();

        System.out.println("Enter number 2");
        int num2 = in.nextInt();

        System.out.println("Enter number 2");
        int num3 = in.nextInt();

        int finalResult=num1+num2+num3;


        System.out.println(finalResult+" is the sum of the three integers");
    }

}

Upvotes: 1

Related Questions