要求用户输入单词,直到他们进入“退出”,当他们进入退出状态时显示他们输入的所有单词而没有“退出”。
我很困惑如何将所有单词组合在一起并在最后显示它,我知道我需要另一个循环
import java.util.*;
public class testprac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
break;
}
}
}
}
答案 0 :(得分:0)
您可以使用数组或List来存储输入,然后循环遍历列表或数组进行打印。您还可以使用toString()方法进行打印。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<String> inputs = new ArrayList<>();
while (true) {
System.out.println("Enter a word: ");
String word = input.nextLine();
if (word.equals("exit")) {
System.out.println("Exited");
System.out.println("You entered: "+inputs);
break;
} else {
inputs.add(word);
}
}
}
}
答案 1 :(得分:0)
这应该有效:
import java.util.*;
public class testprac {
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner inputScanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
while (inputScanner.hasNextLine()) {
String line = inputScanner.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
String s = lineScanner.nextLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exited");
System.out.println("You entered: ");
System.out.println(sb.toString());
lineScanner.close();
System.exit(0);
} else {
sb.append(s);
}
}
}
inputScanner.close();
}