lbux_
lbux_

Reputation: 13

Checking if a user inputed string is in an array

So this is more than just checking if a user input string in an array because if the string is actually in the array and the bool returns true I want it to write some custom text.

{
    static void Main(string[] args)
    {
        string[] name= {"Bob","Bob2","Bob3","Bob4"};

        bool exists = name.Contains(string userName= Console.ReadLine());

        if (exists == true)
            Console.WriteLine("Hi " + userName);

        Console.ReadLine();
    }
}

I know I can't run the code like this but I'm looking for a similar way to run it but I'm not sure how to store user input and still have the bool check if the user inuputed string is in the string array.

Upvotes: 0

Views: 146

Answers (3)

Callum Sim
Callum Sim

Reputation: 1

I came up with this...

import java.util.Scanner;


public class inp {
public static void main (String args[]) {
    String[] name = new String[] {
    "Ben",
    "Sam"
    };
    int max = name.length;
    int current = 0;
    boolean is = false;

    System.out.println("What name tho?");
    Scanner inp = new Scanner(System.in);
    String nameInq = inp.next();

    while(is == false && current<max) {
        if(name[current].equals(nameInq)) {
            is = true;
        }else {
           current++;

        }
    }
 if(is) {
    System.out.println("They are in the list");
 }else {
    System.out.println("nah");
 }

 }
 }

Not quite as efficent but gets the job done.

Upvotes: 0

Mobigital
Mobigital

Reputation: 759

you almost had it, just move the userName assignment up to its own line:

static void Main(string[] args)
{
    string[] name = { "Bob", "Bob2", "Bob3", "Bob4" };

    string userName = Console.ReadLine();
    bool exists = name.Contains(userName);

    if (exists == true)
        Console.WriteLine("Hi " + userName);

        Console.ReadLine();

}

here is the output:

enter image description here

Upvotes: 3

D Stanley
D Stanley

Reputation: 152556

Just declare your input variable outside of te Contains check:

static void Main(string[] args)
{
    string[] name= {"Bob","Bob2","Bob3","Bob4"};

    string userName = Console.ReadLine();
    bool exists = name.Contains(userName);

    if (exists == true)
        Console.WriteLine("Hi " + userName);

    Console.ReadLine();
}

Upvotes: 0

Related Questions