Java error, duplicate local variable

2020-02-06 10:09发布

I'm trying to debug a portion of code for an assignment (I'm still very new to Java) and have combed through many resources to solve this conflict but still can't quite work it out.

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.");
      String input = keyboard.next();
      input.toLowerCase();
      input.charAt(0);  
    }
    while ((input != "a") || (input != "b"));
}

I always get a Duplicate Local Variable error with the input String.

Any help would be greatly appreciated!

6条回答
萌系小妹纸
2楼-- · 2020-02-06 10:46
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();

查看更多
太酷不给撩
3楼-- · 2020-02-06 10:46

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();
查看更多
该账号已被封号
4楼-- · 2020-02-06 10:48

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.

查看更多
We Are One
5楼-- · 2020-02-06 10:55

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"));
}
查看更多
唯我独甜
6楼-- · 2020-02-06 11:01

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")))
查看更多
冷血范
7楼-- · 2020-02-06 11:03

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

查看更多
登录 后发表回答