【问题标题】:How can I fix these errors? java program我该如何解决这些错误?程序
【发布时间】:2020-11-03 09:49:29
【问题描述】:

我一直在做一个程序。

我不断收到这些错误:

StationInformation.java:65: error: non-static variable this cannot be referenced from a static context
      Station mile_end = new Station();
                         ^
StationInformation.java:66: error: non-static variable this cannot be referenced from a static context
      Station oxford_circus  = new Station();
                               ^
StationInformation.java:67: error: non-static variable this cannot be referenced from a static context
      Station kings_cross = new Station();
                            ^
StationInformation.java:68: error: non-static variable this cannot be referenced from a static context
      Station stepney_green = new Station();
                              ^
4 errors

我想修复程序。

【问题讨论】:

  • 您想解决什么问题?它目前是否做错了什么?
  • 您似乎尝试通过 create_messages 中的 out-parameters 初始化字符串 - 这在 Java 中是不可能的。引用是按值传递的,并且不能在方法内以从方法外部可见的方式进行修改。

标签: java loops if-statement


【解决方案1】:

我已将 Station 类设为静态并从 create_messages() 返回一个列表。

//this program tells the user whether a station is a step free access station or not and how far is it from the platform

import java.util.Scanner; // imports the scanner function to input data from the user
import java.util.ArrayList;
import java.util.List;

class StationInformation {
    public static void main(String[] args) // main method where methods are sequenced
    {
        int numberOfStations = inputint("how many stations do you want to know about?");
        String station;

        for (int i = 1; i <= numberOfStations; i++) {
            station = inputstring("what station do you want to know about?");
            search_station(station);

        }

        System.exit(0);
    }

// A method to input integers
    public static int inputint(String message) {
        Scanner scanner = new Scanner(System.in);
        int answer;

        System.out.println(message);
        answer = Integer.parseInt(scanner.nextLine());

        return answer;
    } // END inputInt

    public static String inputstring(String message) {
        Scanner scanner = new Scanner(System.in);
        String answer;

        System.out.println(message);
        answer = scanner.nextLine();

        return answer;
    }

    public static String create_message(Station station) {
        String message;
        if (station.step_free_access == true) {
            message = (station.name + "does have step free access. " + "it is " + station.distance_from_platform
                    + "m away from the entrance");
        } else {
            message = (station.name + "does not have step free access. " + "it is " + station.distance_from_platform
                    + "m away from the entrance");
        }
        return message;
    }

    public static List<String> create_messages() {
        Station mile_end = new StationInformation.Station();
        Station oxford_circus = new Station();
        Station kings_cross = new Station();
        Station stepney_green = new Station();

        mile_end.distance_from_platform = 50;
        mile_end.name = "Mile End ";
        mile_end.step_free_access = false;
        String message1 = create_message(mile_end);

        oxford_circus.distance_from_platform = 200;
        oxford_circus.name = " Oxford Circus ";
        oxford_circus.step_free_access = true;
        String message2 = create_message(oxford_circus);

        kings_cross.distance_from_platform = 700;
        kings_cross.name = " kings cross ";
        kings_cross.step_free_access = true;
        String message3 = create_message(kings_cross);

        stepney_green.distance_from_platform = 300;
        stepney_green.name = " Stepney Green ";
        stepney_green.step_free_access = false;
        String message4 = create_message(stepney_green);

        List<String> list = new ArrayList<>();
        list.add(message1);
        list.add(message2);
        list.add(message3);
        list.add(message4);
        return list;
    }

    public static void search_station(String station) {

        List<String> list = create_messages();
        String mileEndMessage = list.get(0);
        String oxfordCircusMessage = list.get(1);
        String kingsCrossMessage = list.get(2);
        String stepneyGreenMessage = list.get(3);

        if (station.equals("Mile End")) {
            System.out.println(mileEndMessage);
        } else if (station.equals("kings cross")) {
            System.out.println(kingsCrossMessage);
        } else if (station.equals("oxford circus")) {
            System.out.println(oxfordCircusMessage);
        } else if (station.equals("stepney green")) {
            System.out.println(stepneyGreenMessage);
        } else {
            System.out.println(station + " is not a London underground station ");
        }

    }

    static class Station // a record to store information about stations
    {
        int distance_from_platform;
        String name;
        boolean step_free_access;
    }

}

【讨论】:

  • 修改程序后出现这个错误:Error: Could not find or load main class StationInformation Caused by: java.lang.ClassNotFoundException: StationInformation
  • 现在它可以工作了。我已将 StationInformation 重命名为 Main。
【解决方案2】:

编辑:这个答案可能看起来已经过时了,因为 OP 决定编辑这个问题,在这个过程中删除了他的代码。

您的代码中有 2 个错误:

  1. 您的内部类Station 不是静态的,这意味着您不能在静态上下文中实例化它。这会产生您看到的错误消息。
  2. 您认为 Java 是按引用传递的,并试图覆盖变量指向的值(在 Java 中您不能这样做)。

您可以通过将 Station-class 设为静态 (static class Station) 并通过使工作站使用类变量并使用它们的字段创建字符串来纠正错误。
您还可以为 Station-class 实现一个 getInfo()-method,它自己准备其信息。有了这个,你可以打电话给System.out.println(STATION_YOU_WANT.getInfo())

我花了一些时间为这个问题写了一个带注释的解决方案。
其中最令人困惑的部分可能是varargs 的使用(下面代码中的String...)。它们基本上允许您将任意数量的参数传递给方法,该方法本质上会被 Java 转换为数组。

import java.util.HashMap;
import java.util.Locale;
import java.util.Scanner;

public class StationInformation {
  private static class Station {
    private String name;
    private int distanceToPlatform;
    private boolean stepFree;
    private String[] alternateNames;
    
    Station(String name, int distanceToPlatform, boolean stepFree, String...alternateNames) {
      this.name = name;
      this.distanceToPlatform = distanceToPlatform;
      this.stepFree = stepFree;
      this.alternateNames = alternateNames; // 'String...' makes that parameter optional, resulting in 'null' if no value is passed
    }
    
    String getInfo() {
      return name + " does" + (stepFree ? " " : " not ")
        + "have step free access.\nIt is " + distanceToPlatform + "m from entrance to platform.";
    }
  }
  
  private static HashMap<String, Station> stations = new HashMap<String, Station>();
  
  public static void main(String[] args) {
    createStations();
    
    // The Program
    Scanner scanner = new Scanner(System.in);
    
    // Keep requesting input until receiving a valid number
    int num;
    for (;;) { // 'for (;;) ...' is effectively the same as 'while (true) ...'
      System.out.print("How many stations do you need to know about? ");
      String input = scanner.nextLine();
      
      try {
        num = Integer.parseInt(input);
        break;
      } catch (Exception exc) {
        // Do nothing
      }
      
      System.out.println("Please enter a correct number.");
    }
    
    for (int i = 0; i < num; ++i) {
      System.out.print("\nWhat station do you need to know about? ");
      String input = scanner.nextLine();
      
      // If available, show Station-information
      if (stations.containsKey(input.toLowerCase(Locale.ROOT))) {
        System.out.println(stations.get(input.toLowerCase(Locale.ROOT)).getInfo());
      } else {
        System.out.println("\"" + input + "\" is not a London Underground Station.");
      }
    }
    
    scanner.close(); // Close Scanner; Here actually not needed because program will be closed right after, freeing its resources anyway
  }
  
  private static void createStations() {
    // Add new Stations here to automatically add them to the HashMap
    Station[] stations = new Station[] {
      new Station("Stepney Green", 100, false),
      new Station("King's Cross", 700, true, "Kings Cross"),
      new Station("Oxford Circus", 200, true)
    };
    
    for (Station station : stations) {
      StationInformation.stations.put(station.name.toLowerCase(Locale.ROOT), station);
      
      // Alternative names will be mapped to the same Station
      if (station.alternateNames == null) continue;
      for (String altName : station.alternateNames)
        StationInformation.stations.put(altName.toLowerCase(Locale.ROOT), station);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 2016-07-21
    • 2016-09-09
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多