0

So I know how to take the integers given by a text file and turn them into an array, but I want the user to be able to input the file name. Here's what I have:

Scanner scanner = new Scanner(new File("grades.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}

Except the text file could be any text file the user inputs, not just grades.txt.

Sorry not great at java :/

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • You could make a `new Scanner(System.in)` and then get the user's input from that and use that in place of `"grades.txt"`. – 2rs2ts Oct 30 '14 at 22:48
  • @2rs2ts you should provide an answer for that, not a comment. – Luiggi Mendoza Oct 30 '14 at 22:49
  • have a look here, that's the simplest way: http://stackoverflow.com/questions/5287538/how-to-get-basic-user-input-for-java – Hagai Oct 30 '14 at 22:49
  • @LuiggiMendoza To be truthful... I didn't want to test a code example to make sure my answer was correct. I figured I'd just give a tip in the right direction. – 2rs2ts Oct 30 '14 at 23:16

2 Answers2

0
System.out.println("Please enter the file name:");
Scanner sc = new Scanner(System.in);
String file = sc.nextLine();

Scanner scanner = new Scanner(new File(file));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}

Not tested, but is this what you were looking for? You can use System.in to get input from the console.

austin wernli
  • 1,801
  • 12
  • 15
  • It would help more to OP and future readers to provide an explanation of this code. – Luiggi Mendoza Oct 30 '14 at 22:51
  • "You can use System.in to get input from the console."... Other then that they are assigning values, so i assumed they know what is going on from there. Plus, i think it would be a good learning experience to look at some documentation to see what else you can do with this. – austin wernli Oct 30 '14 at 22:52
0

So you want the user to be able to input the name of the file that is loaded, that's done easily enough:

First, get the file from the user and store it in a string

Scanner input = new Scanner(System.in);
string fileName = input.nextLine();

Then, you can either use it straight away, or do some checking to make sure it ends in .txt

while (!fileName.matches(".*\\.txt"))
{
    System.out.print("Please enter a .txt file: ");
    fileName = input.nextLine();
}

Once you have the file name, just use that in place of the hard coded "grades.txt" in your code:

Scanner scanner = new Scanner(new File(fileName));
Shadow
  • 3,926
  • 5
  • 20
  • 41