0

So need a method that reads a txt file holding 4 integers (1,2,3,4) and throws an exception. I am think I have the scanner correct... But I want to print the values that the scanner read in my main method. I am not sure how to do that with System.out.println(). The scanner is not in the main method. Here is my code:

public static void scan()
{     
    String fileInputName  = "data.txt";
    Scanner sc = null;  

    try {
        sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
        while (sc.hasNextLine()) 
        {                     
            sc.nextInt();
        }
    }
    catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
    finally
    {
        if (sc != null)
            sc.close();  
    }           
}
user5344755
  • 47
  • 2
  • 6

2 Answers2

0

You have to assign the scan to a variable, then print it:

Change the interface of the method

public List<Integer> void scan()

Then declare a list:

List<Integer> list = new ArrayList<Integer>();

while (sc.hasNextLine()) 
    {
        int myInt = sc.nextInt();
        list.add(myInt);
    }

Then return it:

return list;

Then in your main, iterate through your list and print it out:

list = scan();

for (Integer i : list){
    System.out.println(i);
}
ergonaut
  • 6,547
  • 1
  • 14
  • 42
0

You can either assign the int go a variable and then print the variable like so:

System.out.println(variableInt);

Or you can just print it when you access it like so:

System.out.println(sc.nextInt());

Also, know that println will move a new line after it prints the thing. If you want to avoid this, simply change it to:

System.out.print(whatever);
DITTO
  • 117
  • 1
  • 8