开发者

How to type in a string that will be assigned to a variable?

I need my program to ask the user to type in a String which will be assigned to a variable eg:string in the case below 开发者_运维技巧so the array list can be searched for a String containing the String entered by the user.

public void search(){
    String string = "";
    for (int i = 0; i < wordArray.size(); i++){
        if (wordArray.get(i).contains(string) == true){
            System.out.println(wordArray.get(i));
        }
        else{
            System.out.println("No words match your search.");
        }
    }
}


If this is no gui application you can use System.in.

Scanner s = new Scanner(System.in);
String string = s.readLine();


Use the Scanner api:

Scanner s = new Scanner(System.in);
String string = s.nextLine();

....

s.close();

... or Console from System.console() :

String string = System.console().readLine();

(You need to check that you get a console back from System.console() if you want to be sure!)


here's how you read from keyboard using JavaIo

  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);



    System.out.print("please type in a value ");

    String str = br.readLine();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜