Home > Mobile >  Avergae of 3 integers input by user
Avergae of 3 integers input by user

Time:03-03

I'm struggling in my intro to Java course. Practicing actually writing coding as reading the textbook is not doing me so well.

Currently working on a program that will take 3 integers from the user and average them.

I have

import java.util.Scanner;
public class PPrac {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    
    int num1;
    int num2;
    int num3;
    int avg= (num1 num2 num3)/3;
            
System.out.println("Enter first integer");
int num1=input.nextInt();

System.out.println("Enter second integer");
int num2=input.nextInt();

System.out.println("Enter thrid integer");
int num3=input.nextInt();

System.out.print(avg);


}}

I am getting duplicate local variables on

int num1=input.nextInt();
int num2=input.nextInt();
int num3=input.nextInt();

CodePudding user response:

You are creating (or declaring) duplicate local variables, hence your error. This is what int num1 does. You only need int num1 once to create a variable called num1 of type int. Afterwards, you can assign new values to it via num1 = <value>.

CodePudding user response:

You are redeclaring your variables. To solve the duplicate variables issue, remove the int on the following three lines:

From:

int num1=input.nextInt();
int num2=input.nextInt();
int num3=input.nextInt();

To:

num1=input.nextInt();
num2=input.nextInt();
num3=input.nextInt();

Please do the avg calculation after initializing the 3 values or encapsulate it into an own method.

Later you can make the program a bit smarter ;-)

  •  Tags:  
  • java
  • Related