简体   繁体   中英

Store user input String into array

User input into array.

Eg

    private void addVideo()
{
    Scanner in = new Scanner( System.in );
    String message = "Video";
    System.out.print("Enter Video Name: ");
    return in.nextLine();
}

In in class:

    public static String nextLine()
{   
    return in.nextLine(); 
}

I have compile error 'incompatible types: unexpected return value.' What is the problem? explanation will be appreciated.

Thanks!

How do I assign the entered video name into an array? eg first video name into id array(id=1) second is id = 2 and so on?

private String addVideo() {
        Scanner in = new Scanner(System.in);
        String message = "Video";
        System.out.print("Enter Video Name: ");
        return in.nextLine();
    }

in.nextLine() is returning a String value, so you have to use String not void

If you wanted to store the video names into an array you could just use the method outlined by Nikolai Hristov and then add each instance to an array like this

String[] videos = new String[10];
videos[0] = addVideo();
videos[1] = addVideo(); 

Each call to addVideo() will prompt the user for a video name and then return a String to that position of the array.

You have defined a method with the return type void yet you used a return statement in the method.

As for how to do it, try something like this:

List<String> list = new ArrayList<String>();

public String addVideo() {
    Scanner in = new Scanner(System.in);
    String message = "Video";
    System.out.println("Enter Video Name: ");
    String input = in.nextLine();
    list.add(input);
    return input;
}

Each time you call addVideo you will add one video to the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM