如何连续输入一些字符串,然后在Java中打印它们和字符串的数量?

时间:2017-05-18 08:15:03

标签: java string input

我正在学习Java。我有一个Scanner,我知道如何输入一个String。如何连续输入一些String然后打印它们以及Java中String的数量?

我的代码:

Scanner in = new Scanner(System.in);
//Get input String
System.out.println("Enter a string: ");
str = in.nextLine();
System.out.println("Input String is: "+str);

我想要的结果:

Enter a string: Item1
Input String: Item1, Number of items: 1

2 个答案:

答案 0 :(得分:0)

您可以使用String循环输入任意数量的while。您还可以在Scanner in = new Scanner(System.in); int numberOfItem = 0; String str; while(true) { //Get input String System.out.print("Enter a string(enter QUIT to quit): "); str = in.nextLine(); if (str.equals("QUIT")) break; numberOfItem++; System.out.println(); System.out.print("Input String is: " + str); System.out.println(", Number of items: " + numberOfItem); } 循环中记录您输入的项目数。

yum info wget
 * base: mirrors.melbourne.co.uk
Installed Packages
Name        : wget
Arch        : x86_64
Version     : 1.12
Release     : 10.el6
Size        : 1.8 M
Repo        : installed
From repo   : base
Summary     : A utility for retrieving files using the HTTP or FTP protocols
URL         : http://www.gnu.org/software/wget/
License     : GPLv3+ and GFDL
Description : GNU Wget is a file retrieval utility which can use either the HTTP or
            : FTP protocols. Wget features include the ability to work in the
            : background while you are logged out, recursive retrieval of
            : directories, file name wildcard matching, remote file timestamp
            : storage and comparison, use of Rest with FTP servers and Range with
            : HTTP servers to retrieve files over slow or unstable connections,
            : support for Proxy servers, and configurability.

答案 1 :(得分:0)

输入EXIT完成并显示结果:

    Scanner in = new Scanner(System.in);
    String str = "", tmp;
    int count = 0;
    System.out.println("Enter a string: (Type EXIT to exit");
    while(true){
        System.out.println("Enter a string: ");
        tmp = in.nextLine();
        if(tmp.equals("EXIT"))
            break;
        count++;
        str += tmp + ", ";
    }
    System.out.println("Input String: " + str + "Number of items: " + count);