-1

I've been trying to figure out how to do this code, but can't figure out how to change my current code to work.

The problem reads:

Write a program to read an integer N (2 <= N <= 30) from an input filename “input5_01.txt” and then write a function to create an N x N matrix with random integers from the range [10, 99]. Output that matrix to the output filename “output5_01.txt”

Currently, here's my code:

public static final int UPPER = 99, LOWER = 10;

public static void main(String[] args) throws FileNotFoundException {
    int n = 5;
    int[][] arr = new int[n][n];
    Scanner inputFile = new Scanner(new File("input5_01.txt"));

      //read in an int (n) from input file
    while (inputFile.hasNext()) {
        if (inputFile.hasNextInt() >= 2 && inputFile.hasNextInt() <= 30) {
            n = inputFile.nextInt();
        } else {
            inputFile.next();
        }
    }

     //assigning random numbers to array
    Random rand = new Random();
    for (int r = 0; r < arr.length; r++) {
        for (int c = 0; c < arr[0].length; c++) {
            arr[r][c] = rand.nextInt(UPPER - LOWER + 1) + LOWER;
        }
        System.out.println();
    }
}

Really, the only problem I have is:

if(inputFile.hasNextInt() >= 2 && inputFile.hasNextInt() <= 30)

What can I do to make this work?

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
John
  • 9
  • 1
  • Are you getting an error? What is happening with your current code? – ToddB May 11 '15 at 14:23
  • As a best practice, specify a character set: `new Scanner(new File("input5_01.txt"), "UTF-8");` – Necreaux May 11 '15 at 14:35
  • [how-to-use-java-util-scanner-to-correctly-read-user-input-from-system-in](http://stackoverflow.com/questions/26446599/how-to-use-java-util-scanner-to-correctly-read-user-input-from-system-in) –  May 11 '15 at 15:46

2 Answers2

0

As per the JavaDoc, hasNextInt() returns a boolean, denoting if there is another integer value or not within the stream, it does not return the value of the next integer. Thus, this section:

while(inputFile.hasNext()){
  if(inputFile.hasNextInt() >= 2 && inputFile.hasNextInt() <= 30)
    n = inputFile.nextInt();   
  else
    inputFile.next();
}

Would need to read something like so:

int nextInt = -1;
boolean intFound = false;

while(inputFile.hasNext()){
  if(inputFile.hasNextInt()) {
      nextInt = inputFile.nextInt();
      if((nextInt >= 2) && (nextInt <= 30) {
          intFound = true;
          break;
      }
  }   
}

if(intFound) {
     ... //Populate your matrix according to the value of nextInt
}
npinti
  • 51,780
  • 5
  • 72
  • 96
0

If your input file will have only ints then I believe this should also work:

while(inputFile.hasNextInt()){
  int nextIntValue = inputFile.nextInt();
  if(nextIntValue >= 2 && nextIntValue <= 30) {
    n = nextIntValue ;   break;
  }
  else
    inputFile.next();
}

It will also avoid unnecessary calls.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95