2016-09-01 3 views
-3

これまでは、forループを使用して文章の数を入力して文字列配列の各位置に入力できるように設定しました。文章を文字列配列で入力しようとしましたが、逆順で表示しようとしています

public class Test5 { 
    public static String inputline; 

    public static void main(String[] args) { 
     System.out.print("Enter the number of lines:"); 
     Scanner kb=new Scanner(System.in); 
     int number=kb.nextInt(); 
     String []line=new String[number]; 
     for(int i=0;i<line.length+1;i++){ 
      line[i]=kb.next(); 
     } 
    } 
} 

答えて

0

最初に、あなたのコードは、あなたが望むよりも1倍多く読み込まれ、配列外の例外が発生します。次に、nextLine()を実行して、ユーザーが入力した改行文字を考慮する必要があります。これを試してみてください:

System.out.print("Enter the number of lines:"); 
Scanner kb=new Scanner(System.in); 
int number=Integer.parseInt(kb.nextLine()); 
String []line=new String[number]; 
//loop through only the size of the array 
for(int i=0; i < line.length; i++){ 
    line[i]=kb.nextLine(); 
} 
//now to output the array in reverse order you need to start from the 
//other end of the array 
for(int i = line.length - 1; i >= 0; i--){ 
    System.out.println(line[i]); 
} 
//always close the Scanner when done 
kb.close(); 

スキャナに関するいくつかの有用なリソース - https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

+0

私は入力配列文字列で入力文を傾けます。私が行うときには、この は行数を入力ん:3 を、これは1 ライン は、あなたが一般的にユーザーの入力をつかむときに私はnextLineを(使用なぜthatsの時点でラインをつかむしよう この –

+0

あるラインである)の代わりに、次の() –

+0

私は 'nextLine()'を使用しているときに問題があり、配列の位置0をスキップしているということです。 –

関連する問題