2017-06-20 9 views
1

以下はコードです。配列を入力した後、コンソールはちょうど空白になり、さらに出力に配列されていません。スキャナー使用時に配列値が出力されない

import java.util.Scanner; 

public class advancedArrays { 

    public static void main(String[] args) { 

     System.out.println("Provide us the size of the array:"); 
     Scanner scanner = new Scanner(System.in); 
     int value = scanner.nextInt(); 

     int i = 0; 
     int[] array = new int[value]; 

     System.out.println("Enter the array:"); 
     Scanner input = new Scanner(System.in); 

     while(input.hasNextInt()) { 
      array[i] = input.nextInt(); 
      i++; 
     } 

     System.out.println("Array entered:"); 
     for(i=0;i<value;i++) 
     { 
      System.out.println(array[i]); 
     } 
     input.close(); 
     scanner.close(); 
    } 

} 

出力:

Provide us the size of the array: 
5 
Enter the array: 
1 2 3 4 5 
+1

私は、while(input.hasNextInt())によってアプリケーションが6番目のintを待っていると強く想定しています。とにかくユーザーが配列のサイズを入力できるようにするので、何度もループするのはなぜですか?ユーザーはint型ではない入力を処理する必要がありますが、現在は範囲外で処理することを検討します。 – Thomas

+1

複数のスキャナを作成しないでください。 –

答えて

0

あなたは「配列を読ん」の部分で立ち往生していますこのため、

while (input.hasNextInt()) { 
     array[i] = input.nextInt(); 

ヒント:配列のサイズを知っていれば、whアレイの内容を印刷するのと同じようにforループを実行していませんか?以下のような:

for (int j = 0; j < value; j++) { 
    array[i] = scanner.nextInt(); 
    i++; 
} 
0

問題は、あなたはそれがより多くの整数を待っておくwhileループと、入力された配列のサイズvalue上の条件付きループのために正常な状態に変換するのに優れていることです。

はまた、あなたの入力はあなたの配列の長さだった場合は、チェックされませんので、あなたは、配列のためのあなたの入力を読んで立ち往生された2つのscannerオブジェクト

public static void main(String[] args) { 

    System.out.println("Provide us the size of the array:"); 
    Scanner scanner = new Scanner(System.in); 
    int value = scanner.nextInt(); 

    int i = 0; 
    int[] array = new int[value]; 

    System.out.println("Enter the array:"); 

    for (int j = 0; j < value; j++) { 
     if (scanner.hasNextInt()) { 
      array[i] = scanner.nextInt(); 
      i++; 
     } 
    } 

    System.out.println("Array entered:"); 
    for (i = 0; i < value; i++) { 
     System.out.println(array[i]); 
    } 
    scanner.close(); 
} 
0
package Main; 

import java.util.Scanner; 

public class advancedArrays { 

public static void main(String[] args) { 

    System.out.println("Provide us the size of the array:"); 
    Scanner scanner = new Scanner(System.in); 
    int value = scanner.nextInt(); 

    int i = 0; 
    int[] array = new int[value]; 

    System.out.println("Enter the array:"); 
    Scanner input = new Scanner(System.in); 

    while(input.hasNextInt()) { 
     array[i] = input.nextInt(); 
     i++; 

     //Changed Code 
     if (i == value) { 
      break; 
     } 
    } 

    System.out.println("Array entered:"); 
    for(i=0;i<value;i++) 
    { 
     System.out.println(array[i]); 
    } 
    input.close(); 
    scanner.close(); 
    } 

} 

固定コードを使用する必要はありません。

固定コード。

if (i == value) { 
    break; 
} 
関連する問題