2

I'm trying to read a txt file and print the line opposite. for example: txt:

3 //size of matrix  
3 4 5  
5 6 7  
6 7 8  

output should be:

6 7 8  
5 6 7  
3 4 5  

I wrote a program. the program prints:

5 6 7  
3 4 5  

which is without the first line: 6 7 8.

What is my mistake?

public static void main (String[] args)  {
   int matrixSize = StdIn.readInt(); 
   String [] array = new String [matrixSize]; 
   for (int i=0; i <= matrixSize-1; i++)
   { 
      array[i] = StdIn.readLine();
      StdOut.println(array[i]);
   } 
   for (int j=matrixSize-1; j >= 1; j--)
   {
      StdOut.println(array[j]);
   }
}
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Loren
  • 95
  • 10

1 Answers1

0

This loop will iterate from the last element to the second one.

for (int j=matrixSize-1; j >= 1; j--)

Change to also include the first element

for (int j=matrixSize-1; j >= 0; j--)

Also it seems that StdIn.readInt() doesn't consume the new line character. So when you do a StdIn.readLine() after that you get an empty line. That empty line is what remains from the first line after you have scanned the number. A simple workaround for that would be to obtain matrixSize like this :

String text = StdIn.readLine();
int matrixSize = Integer.parseInt(text);
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82