简体   繁体   中英

How can I make a filescanner being passed between methods work?

For some reason, the compiler does not see the fileScan Scanner. I am passing it so I can open and read the file and then read its lines. I am unsure of what the problem is - How can I fix this? Thanks in advance!

public static void main (String[] args)
   {
      int weaponNumber = 0;
      Scanner scan = new Scanner(System.in);
      Scanner fileScan = new Scanner(FILENAME);

      while (fileScan.hasNextInt())
      {
         String line = fileScan.nextLine();
         Scanner lineScan = new Scanner(line);
         weaponNumber = lineScan.nextInt();
      }
      intro();
      String[] weapons = menu(fileScan, weaponNumber);
      String[][] outcomes = possibleOutcomes(fileScan, weaponNumber);
      String[][] verbs = verbs(fileScan, weaponNumber);
      battle(scan, fileScan, weapons,outcomes,verbs, weaponNumber);
   }

   public static String[][] possibleOutcomes(Scanner fileScan,int weaponNumber)
   {
      int numberOfOutcomes = (int)Math.pow(weaponNumber,2);
      String[][] outcomes = new String[numberOfOutcomes][numberOfOutcomes];
      String line = fileScan.nextLine();
      Scanner lineScan = new Scanner(line);
      fileScan.nextLine();
      for (int i=0;i<weaponNumber;i++)
      {
         for(int x=0;x<weaponNumber;x++)
         {
            for(int y=0;y<weaponNumber;y++)
            {
               String a = (lineScan.next());
               String a1 = a.replace(a, String.valueOf(x));
               int a2 = Integer.valueOf(a1);
               String b = (lineScan.next());
               String b1 = b.replace(b,String.valueOf(y));
               int b2 = Integer.valueOf(b1);
               outcomes[a2][b2] = lineScan.next();
               fileScan.nextLine();
            }
         }
      }
      String array1 = Arrays.toString(outcomes);
      System.out.println(array1);
      return outcomes;
   }
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at RPSLSp2.possibleOutcomes(RPSLSp2.java:77)
    at RPSLSp2.main(RPSLSp2.java:30)

This,

Scanner fileScan = new Scanner(FILENAME);

uses the Scanner(String) constructor, and that (per the javadoc)

Constructs a new Scanner that produces values scanned from the specified string.

Not a file. You want Scanner(File) like

Scanner fileScan = new Scanner(new File(FILENAME));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM