Java error, duplicate local variable

痞子三分冷 提交于 2019-11-28 12:48:57

replace

String input = keyboard.next();

with

input = keyboard.next();

If you put a String before the variable name it is a declaration. And you can declare a variable name only once in a scope.

npinti

You have declared the input variable twice. You will need to change this line:

String input = keyboard.next();

to this:

input = keyboard.next();

Also, this code will most likely not work:

((input != "a") || (input != "b"))

In Java, Strings are compared using the .equals() method, so this line:

((input != "a") || (input != "b"))

needs to be changed to this:

((!input.equals("a")) || (!input.equals("b")))

Yoy've duplicated String input declaration. Once is enough.

public static void main(String [] args){
    Scanner keyboard = new Scanner(System.in);
    String input = null;
    do
    {
      System.out.println("Enter 'A' for option A or 'B' for option B.");
      input = keyboard.next();
      input.toLowerCase();
      input.charAt(0);  
    }
    while ((input != "a") || (input != "b"));
}

The problem is you are declaring input inside do{} again. So it should just be

input=keyboard.next();

As far as I know, this is not how you hide the variables.

Here is what I mean

private static String input = null;    
public static void main(String [] args){
    Scanner keyboard = new Scanner(System.in);
    do
    {
      System.out.println("Enter 'A' for option A or 'B' for option B.");
      String input = keyboard.next();
      input.toLowerCase();
      input.charAt(0);  
    }
    while ((input != "a") || (input != "b"));
}
user1355253

You have declared the input variable twice . Inside the main method declare input only once. Use the following code inside do {}:

input = keyboard.next(); instead of  String input = keyboard.next();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!