简体   繁体   中英

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

How to print multiple Strings from Scanner as there is no array to call out and I'm stuck on how to generate the output.

My do-while loop will stop when user enters # . It seems fine until the part to print out the result, if I put the strResult I can only see the last string of user input.

Below is my current code :

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);

        }
    }
}

Use 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
    }  

You can use an 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));

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM