如何从Scanner
打印多个字符串,因为没有要调出的数组,而且我仍然坚持如何生成输出。
当用户输入do-while
时,我的#
循环将停止。在打印出结果的部分之前似乎很好,如果我放strResult
我只能看到最后一个用户输入字符串。
以下是我目前的代码:
import java.util.Scanner;
public class SecretMessage {
public static void main(String[] args) {
int count =0;
int i =0;
//char ch;<<<<<<<<<< I need this for converting the string to char
Scanner sc = new Scanner(System.in);
//String result[] = new String[count];<<<<<<<<purposedly for array
String input ="";
String strResult ="";
do {
System.out.print("Enter your text :");
input=sc.nextLine();
count++;
}
while (!input.equals("#"));
{
System.out.print("Result :\n");
strResult = "Case #"+(count-1)+" :"+input;
//result[count] = strResult;<<<<<<to represent all result
}
for (i=0;i<(count-1);i++) {
System.out.println(" "+strResult);
}
}
}
答案 0 :(得分:0)
使用StringBuilder:In Java, how to append a string more efficiently?
StringBuilder stringBuilder = new StringBuilder();
do {
System.out.print("Enter your text :");
input=sc.nextLine();
stringBuilder.append(input);
count++;
}
while (!input.equals("#"));
{
System.out.print("Result :\n");
strResult = "Case #"+(count-1)+" :"+stringBuilder.toString();
//result[count] = strResult;<<<<<<to represent all result
}
答案 1 :(得分:0)
您可以使用ArrayList
ArrayList list = new ArrayList();
do {
System.out.print("Enter your text :");
input=sc.nextLine();
list.add(input);
count++;
}
while (!input.equals("#"));
{
System.out.print("Result :\n");
strResult = "Case #"+(count-1)+" :"+input;
//result[count] = strResult;<<<<<<to represent all result
}
for (i=0;i<list.size()-1;i++) {
System.out.println("Case #" + (i+1) + " " + list.get(i));
}