java初学者 - 找不到符号

时间:2016-09-07 12:35:21

标签: java

我是java的初学者并尝试创建一个在终端中收到输入数字的程序,并且会一直询问新的数字,直到输入0。在输入0之后,我希望程序汇总所有数字并将它们加在一起。但是当我尝试编译程序时,我收到了这个错误:

enter image description here

下面是代码:

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您在tall2块中声明while声明它在外面。它会坚持到那个块只在你的情况下它属于while块但是你试图访问那个变量tall2,而这是你可以看到错误的原因。希望它会对你有所帮助。

我改变了声明部分。

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);
        }
    }
}