2016-11-28 8 views
-4

なぜこの文字列配列にa-1文字列を入力するのですか?なぜ私はいつもこの文字列にa-1文字列を入力するのですか?

public class Source { 
    public static void main(String[] args) {   
     Scanner in = new Scanner(System.in); 

     // Declare the variable 
     int a; 

     // Read the variable from STDIN 
     a = in.nextInt(); 
     String strs[]=new String[a]; 
     for(int i=0;i<a;i++) 
     strs[i]=in.nextInt();  
    } 
} 
+1

ようこそ:ペン

結果:アップル

文字列番号2を入力してください! [ツアー]を見て周りを見て、[ヘルプ]、特に[*どのように良い質問をしますか?](/助け/やり方) –

+0

なぜあなたはintを文字列配列に変換しますか? –

+0

入力例がありますか?あなたが配列とaの中にあるべきと思うものと、そして実際の結果は何ですか? – Mark

答えて

0

あなたはこのように、あなたのループ内で条件を変更することができます。

for (int i = 0; i < a - 1; i++) { 
    strs[i] = in.nextInt(); 
} 
0

あなたは正しくaに等しい回数だけ反復されています。いいえa-1。そこで問題は、無効であると表示されます。

public class Source { 
public static void main(String[] args) { 
    try(Scanner in = new Scanner(System.in)) { 
     // Declare the variable 
     int a; 
     System.out.print("How many Strings would you like to enter? "); 
     // Read the variable from STDIN 
     a = in.nextInt(); 
     String[] strs = new String[a]; // this will fail for certain values of `a` 
     for(int i=0; i<a; i++) { 
      System.out.format("Enter String number %d: ", i+1); 
      strs[i]= in.next(); 
     } 
     System.out.println("Result: " + Arrays.toString(strs)); 
    } 
} 
} 

は、実行:

どのように多くの文字列あなたが入力したいですか? 2

入力した文字列番号1:スタックオーバーフローに[アップル、ペン]

関連する問題