You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Java编译出现cannot find symbol错误求助:Scanner方法未识别

Fixing Scanner cannot find symbol Errors in Your Java Code

Hey Andrew, those compilation errors are all down to using non-existent methods with the Scanner class—let's fix them step by step:

1. Why nextChar() and nextString() are causing issues

The Java Scanner class doesn't have a nextChar() or nextString() method. These are the straightforward replacements you need:

  • To get a single character: Use input.next().charAt(0) (reads the next whitespace-separated token as a string, then grabs its first character)
  • To get a string: Use input.next() (reads the next whitespace-separated token) or input.nextLine() (reads an entire line of input)

2. Corrected Code

Here's your code with the fixes applied, plus comments explaining each change:

import java.util.Scanner;
import java.io.*;

public class Tester{
    public static void main(String[] args){
        Scanner input=new Scanner(new File(args[0]));
        while(input.hasNextLine()){
            // Replace non-existent nextChar() with next().charAt(0)
            char posit = input.next().charAt(0);
            String compar = Character.toString(posit);
            
            if(compar.equals("#")){//If using manager symbol
                // Replace non-existent nextString() with next() for string input
                String firstN = input.next();
                String lastN = input.next();
                double var1 = input.nextDouble();
                Employee.Manager(firstN, lastN, var1);
            }//End if manager statement
            else if(compar.equals("*")){//If using hourly symbol
                // Replace non-existent nextString() with next() for string input
                String firstN = input.next();
                String lastN = input.next();
                double var1 = input.nextDouble();
                double var2 = input.nextDouble();
                Employee.HourlyWorker(firstN, lastN, var1, var2);
            }//End if hourly statement
        }//End while loop
    }//End main method
}//End class

3. Quick Additional Tip

If your input lines have the symbol and all values on the same line, you might want to read the entire line first to avoid issues with leftover newline characters. Here's a quick adjustment for that:

while(input.hasNextLine()){
    String line = input.nextLine();
    Scanner lineScanner = new Scanner(line);
    char posit = lineScanner.next().charAt(0);
    // Rest of your logic using lineScanner instead of the main input scanner
}

Also, double-check that your Employee class actually has static Manager and HourlyWorker methods—if these are constructors instead, you'll need to assign them to variables (e.g., Employee manager = new Employee.Manager(...)).

内容的提问来源于stack exchange,提问作者Andrew Kubat

火山引擎 最新活动