循环不识别变化的变量

时间:2016-01-31 09:41:42

标签: java loops

我试图询问用户是否要继续输入数字以添加总值

    int total=0; 

    char letter='y';

    while (letter == 'y');
    {
            Scanner userInput = new Scanner (System.in);
            System.out.println("Input your number");
            int number = userInput.nextInt();

            total=number+total;


            Scanner userInput1 = new Scanner (System.in);
            System.out.println("Would you like to continue? Input y/n");
            char letter = userInput1.next().charAt(0); //**This is where there is an error**

    }        
    System.out.println("The total of all the numbers inputted is "+total);
    }
}

3 个答案:

答案 0 :(得分:2)

  1. 您不应该在第5行(;行)上有while
  2. 在循环之外只初始化Scanner一次性能更高。
  3. 在循环的最后一行,使用letter = ***代替char letter = ***。您已经声明了变量letter
  4. 如果用户输入了非号码,也许您应该处理nextInt行。
  5. 可能的改进:

    int total=0;
    char letter='y';
    Scanner userInput = new Scanner(System.in);
    while(letter == 'y')
    {
        System.out.println("Input your number");
        int number = userInput.nextInt();
        total += number;
        System.out.println("Woud you like to continue? Input y/n");
        letter = userInput.next().charAt(0);
    }
    

答案 1 :(得分:1)

只需删除char,因为letter已经定义。而不是

char letter = userInput1.next().charAt(0);   

// char removed
letter = userInput1.next().charAt(0);

并且正如Pemap所说,在;

之后移除while

基本上,您的代码应与以下内容类似

while (letter == 'y') {
        Scanner userInput = new Scanner (System.in);
        System.out.println("Input your number");
        int number = userInput.nextInt();

        total = number + total;


        Scanner userInput1 = new Scanner(System.in);
        System.out.println("Would you like to continue? Input y/n");
        letter = userInput1.next().charAt(0); 
}        

答案 2 :(得分:1)

2个问题。 1)你有一个;在while语句行中。 2)你已经宣布了字母变量。在第二次要求输入后无需再次声明。希望能帮助到你。

for (var i=0; i<lines.length; i++) {
    var line = lines[i];
  (function(line) {
        $('#svg').before('<p id="l'+ i + '">line_' + i + '</p>')
    console.log($('l'+i))
    $('#l'+i).hover(function() {
        line.attr({'stroke':'#00F', 'stroke-width':8})
    }, function() {
        line.attr({'stroke':'#f00', 'stroke-width':5})
    })
  })(line)
}