0

I am a beginner in java and trying to create a program that recieves input numbers in terminal, and will continuously ask for a new numbers until 0 is entered. After 0 has been entered I want the program to summarize all of the numbers and plus them together. But when I try to compile the program I get this error:

enter image description here

Heres the code:

import java.util.Scanner;

public class SumTall {
    public static void main(String[] args) {
        Scanner tallscanner = new Scanner(System.in);
        int tall = 0;
        int tall1;

        System.out.println("Write a number:");
        tall1 = Integer.parseInt(tallscanner.nextLine());

        while(tall1 > 0) {
            System.out.println("Write another number:");
            tall1 = Integer.parseInt(tallscanner.nextLine());
            int tall2 = tall + tall1;
        }
        if(tall1 == 0) {
            System.out.println(tall2);
        }
    }
}
px06
  • 2,256
  • 1
  • 27
  • 47
Knut Eriksen
  • 27
  • 1
  • 8
  • 3
    Cannot find symbol means that the variable you're trying to access doesn't exist in this case. The reason for this is that your variable `tall2` is defined inside the `while` loop while you're accessing it outside. – px06 Sep 07 '16 at 12:36
  • 1
    Format your code properbly and you will see what's wrong – Jens Sep 07 '16 at 12:37
  • Take a look at accepted answer in duplicate question (you may need to reload this page to see it) and search for examples with "scope" problem. – Pshemo Sep 07 '16 at 12:41
  • If you use an IDE like Eclipse or IntelliJ rather than a simple text-editor and the command-line, then these problems would show themselves before you attempted to run the code. – OneCricketeer Sep 07 '16 at 23:07

1 Answers1

1

You declared tall2 in while block declare it outside while. it will stick to that block only in your case it belong to while block but you are trying to access that variavle tall2 out side while that's the reason you can see that error. hope it will help you.

I changed the declaration part out side.

import java.util.Scanner;

public class SumTall {
    public static void main(String[] args) {
        Scanner tallscanner = new Scanner(System.in);
        int tall = 0;
        int tall1,tall2;

        System.out.println("Write a number:");
        tall1 = Integer.parseInt(tallscanner.nextLine());

        while(tall1 > 0) {
            System.out.println("Write another number:");
            tall1 = Integer.parseInt(tallscanner.nextLine());
            tall2 = tall + tall1;
        }
        if(tall1 == 0) {
            System.out.println(tall2);
        }
    }
}
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52