簡體   English   中英

Java-在無限循環中在do中返回多個字符串用戶輸入

[英]Java - Return multiple string user input in do while infinite loop

如何從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);

        }
    }
}

使用StringBuilder: 在Java中,如何更有效地附加字符串?

    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
    }  

您可以使用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));

   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM