Check for value in array

前端 未结 4 1891
时光说笑
时光说笑 2021-01-29 03:14

I need to check the array to see if the user input is already present, and display a message as to whether it is or isn\'t there. The first part is working, but I tried to creat

4条回答
  •  离开以前
    2021-01-29 04:05

    Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.

    • Step one: You want to take some user input
    • Step two: Compare it with all previous user inputs to see if it's present.
      • If it is present, return a message indicating that value has been inputted.
      • otherwise ignore the input and continue execution
    • Repeat step one.

    The solution

    So, let's review what you've got, and how you need to change it.

    public static void main(String[] args)

    If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.

    Scanner scan = new Scanner(System.in);
    String array[] = new String[10];
    

    Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.

    Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.

    You will need some input, userInput, and a collection to compare it against, allInputs.

    allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.

    Then, because you're comparing userInput against all values, you're going to need a foreach loop:

    for(String s : allInputs)
    {
        if(s.equals(userInput))
        {
           // Output message code.
        }
    }
    

    Now the trick is fitting this inside a loop that works with this program. That is up to you, because we are not a code writing service. Hopefully my answer will put you on the right track :)

提交回复
热议问题