首页 > 解决方案 > 我该如何解决这些错误?程序

问题描述

我一直在做一个程序。

我不断收到这些错误:

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

我想修复程序。

标签: javaloopsif-statement

解决方案


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

您的代码中有 2 个错误:

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

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

我花了一些时间来为这个问题写一个评论的解决方案。
其中最令人困惑的部分可能是可变参数的使用(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);
    }
  }
}

推荐阅读