2017-10-03 8 views
0

複数の文字列をScannerから印刷するには、配列を呼び出す必要がありません。出力を生成する方法が残っています。Java - 無限ループの間に複数の文字列ユーザー入力を返す

私の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

を使用することができます順序で読み込まれた各文字列を出力するにはどうすればよいですか?しかし、配列を使用して?または**それを使用していない**によって? – Frakcool

+0

"配列がないため" - 作成することを妨げるものがありますか? Btw:事前に行数を知ることができないので、ArrayList が良い選択かもしれません。 – tevemadar

+0

@Frakcoolに - はい、私は順序で入力された各文字列を印刷する必要があります。配列がどのように動作するのか分かりませんが、Forループでは配列の仕組みを知っています。 – Aliff

答えて

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

    } 
+0

はい。できます。ありがとう! – Aliff

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 
    } 
+0

StringBuilderを使用している場合、どのようにループを停止するのですか?あなたが私のwhile式がすでに入力された – Aliff

+0

で初期化されているのを見ればわかるように、最後の読み込み行として入力を更新し、stringbuilderに変数を追加することができます – Asthmatic

+0

ああそうです。ありがとう! – Aliff

関連する問題