【问题标题】:Java Error: Invalid top level statementJava 错误:无效的顶级语句
【发布时间】:2012-01-14 13:47:09
【问题描述】:

我在运行以下代码时遇到问题。不确定我是否做对了,但我试图让 main 方法读取我作为参数传递给该方法的两个文件。所以在交互窗格中,我输入: run Main(customer.dat, smartphone.dat)

如果我尝试这样做,我会收到错误消息:invalid top level statement

我附上了下面的主要方法。我哪里出错了?即使代码编译了,我也有一种感觉,我的 readFile 方法和/或调用 main 函数时遗漏了一些东西。

提前致谢——我确实查看了类似案例,但没有任何结果。如果以前发布过此类问题,我深表歉意。

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

public class Main
{
  private static ArrayList<Customer> customers = new ArrayList<Customer>(); // array-based list to store customers while reading file
  private static ArrayList<Smartphone> smartphones = new ArrayList<Smartphone>(); // array-based list to store smartphones while reading file
  private static MyPriorityQueueSmart[] sections = new MyPriorityQueueSmart[30]; // array of Queues to store sections of store with phones. 30 because max(model#%day = 30)
  private static MyPriorityQueueCust line = new MyPriorityQueueCust(); // Queue to simulate line outside the store

  private static void readFileCustomer(String file) // method to read customer.dat
  {
    try
    {
          FileReader input = new FileReader(file);
      BufferedReader bufRead = new BufferedReader(input);
      String line = "";
      line = bufRead.readLine(); // parses first line
      while(line != null)
      {
        String[] tokens = line.split("\\|"); // splits line by vertical bar
        String name = tokens[0]; 
        int patience = Integer.parseInt(tokens[1]);
        int speed = Integer.parseInt(tokens[2]);
        int strength = Integer.parseInt(tokens[3]);
        int budget = Integer.parseInt(tokens[4]);
        int PreferredModel = Integer.parseInt(tokens[5]);
        Customer cust = new Customer(name, patience, speed, strength, budget, PreferredModel); // constructs customer
        customers.add(cust);  // stores customer in list
        line = bufRead.readLine(); // parses next line
      }
    } 
    catch(IOException e) // error-checking
    {
      System.out.println("There was a problem reading the file");
      System.exit(0);
    }
  }

  private static void readFileSmartphone(String file) // method to read smartphone.dat
  {
    try
    {
      FileReader input = new FileReader(file);
      BufferedReader bufRead = new BufferedReader(input);
      String line = "";
      line = bufRead.readLine(); // parses first line
      while(line != null)
      {
        String[] tokens = line.split("\\|"); // splits line by vertical bar
        int model = Integer.parseInt(tokens[0]);
        int price = Integer.parseInt(tokens[1]);
        Smartphone smart = new Smartphone(model, price); // constructs smartphone
        smartphones.add(smart); // stores smartphone in list
        line = bufRead.readLine(); // parses nextl ine
      }
    } 
    catch(IOException e) // error-checking
    {
      System.out.println("There was a problem reading the file");
      System.exit(0);
    }
  }

  public static void main(String[] args) // string[] args should be the customer file name followed by the smartphone file name
  {
    if(args.length!=2) // error-checking
    {
      System.out.println("Must provide an argument: 2 files names");
      System.exit(0);
    }

    readFileCustomer(args[0]); // reads customer.dat
    readFileSmartphone(args[1]); // reads smartphone.dat

    Scanner scan = new Scanner(System.in); // 

    while(true)
    { 
      System.out.println("1 -- Load Additional Customers");
      System.out.println("2 -- Insert New Phone");
      System.out.println("3 -- Display Customers");
      System.out.println("4 -- Start Simulation");
      System.out.println("5 -- Exit");

      int choice = scan.nextInt();

      if(choice == 1)
      {
        System.out.println("Enter the file name of the customer data: ");
        String name = scan.next();
        readFileCustomer(name);
      }

      else if(choice == 2)
      {
        System.out.println("Enter model# (100, 200, 300, 400): ");
        int model = scan.nextInt();
        System.out.println("Enter price of phone: ");
        int price = scan.nextInt();
        Smartphone smart = new Smartphone(model, price);
        smartphones.add(smart);
      }

      else if(choice == 3)
      {
        for(Customer cust: customers)
        {
          System.out.println(cust.getName() + ", ");
        }
      }

      else if(choice == 4)
      {
        // Start Simulation
        System.out.println("Please enter the current day (#) of the month: "); // necessary for hashing
        int dayOfMonth = scan.nextInt(); // reads user-input for current day of the month
        if(dayOfMonth < 1 || dayOfMonth > 31) // error-checking
        {
          System.out.println("Invalid date. Please re-enter the current day (#) of the month: ");
          dayOfMonth = scan.nextInt();
        }

        // Reorganize customers into PQ -- simulating the "line" outside the doors according to skills
        for(Customer cust: customers) // iterates through array-based list of customers generated during file-reading
        {
          line.offer(cust); // builds the line of customers at the front of the store in order of ability
        }

        // Reorganize smartphones into PQ by type -- simulating the "most expensive" phones in order
        for(Smartphone smart: smartphones)
        {
          int model = smart.getModel(); // store model of current phone in list
          int hash = model % (dayOfMonth + 20); // generate hash tag
          boolean confirmAdd = false; // required for recursion -- will turn to true if phone is added
          while(confirmAdd = false)
          {
            if(sections[hash].isEmpty() == true || sections[hash].peek().getModel() == model) // check if hash index is empty or holds same model 
            {
              sections[hash].offer(smart); // add the phone to the PQ @ the index
              confirmAdd = true; // toggle to confirm the addition of the phone
            }
            else
              hash = (hash + 1) % 30; // linear probing
          }
        }

        // Customers leave line, go to section & buy most expensive phone if possible
        while(line.isEmpty() == false) // makes sure there are people in the line
        {
          Customer firstInLine = (Customer)line.peek(); // locates first customer in line
          int PreferredModel = firstInLine.getPreferredModel(); // stores preference of said customer
          int hash = PreferredModel%(dayOfMonth+20); // generates hash tag to direct customer to correct section
          if(sections[hash].isEmpty() == false) // makes sure the section has not sold out
          {
            if(firstInLine.getBudget() >= sections[hash].peek().getPrice()) // checks if phone is within budget of customer
            {
              Smartphone boughtPhone = (Smartphone)sections[hash].remove(); // customer buys phone and phone is removed from display
              System.out.println(firstInLine.getName() + "has bought phone model# " + boughtPhone.getModel() + "at the price of " + boughtPhone.getPrice()); // prints results
            }
            else // phone is out of budget of customer
              System.out.println(firstInLine.getName() + "cannot afford phone model# " + sections[hash].peek().getModel() + "at the price of " + sections    [hash].peek().getPrice() + "and leaves the store"); // prints results
          }
          else
          {
            System.out.println(firstInLine.getName() + "is out of luck. The phone he or she wants is sold out");
          }
          line.remove(); // as the first person in line has entered the store, he leaves the line and the line moves up
        }
      } // recursive loop until the line is empty

      else if(choice == 5)
      {
        System.exit(0);
      }

      else
      {
        System.out.println("Enter a number from 1 - 5");
      }
    }
  }
}  

【问题讨论】:

  • 错误是来自程序还是你的IDE?如果代码编译得很好,那么您不太可能会从程序中收到invalid top level statement 错误,因为这会被解析器捕获。
  • 什么是“run Main(customer.dat, smartphone.dat)”——这不是 Java 语法,在几个方面。
  • 我很确定它来自 IDE。我正在使用 Java 博士。也许我将主要方法称为错误?代码编译没有任何错误或警告。
  • 肖恩,这就是我试图调用主要方法的方式。你能解释一下正确的方法吗?这两个文件都与程序位于同一目录中。我想以某种方式调用将文件名作为参数传递的 main 方法。

标签: java bluej


【解决方案1】:

在快速搜索之后,我假设您使用的是 DrJava 及其交互窗格。

运行命令中不需要这些括号。请改用run Main customer.dat smartphone.dat

这将运行 Main 类的 main 方法,参数为 customer.datsmartphone.dat

Source

【讨论】:

    【解决方案2】:

    你不能调用 main 方法。之所以称为主方法,是因为它调用了其余的方法。但是当你不执行基于 DOS 的程序时,主方法不是强制性的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2011-01-21
      • 2018-04-03
      • 1970-01-01
      • 2020-12-13
      相关资源
      最近更新 更多