【问题标题】:Array filling that users inputs with Method用户使用 Method 输入的数组填充
【发布时间】:2013-05-03 00:21:22
【问题描述】:

我的项目需要您的帮助。我正在编写一个程序,向学生显示用户之前填写的信息。这是关于我学到了多少方法。我已经写了一个没有方法的程序。但是当我用我遇到的通过引用传递的方法编写相同的东西时......我正在填充 0. 索引但是当我填充 1. 索引时,0. 索引变为空。我尝试了所有方法,但我无法解决这个问题,我认为这与我的回报有关...这里的代码基本上可以帮助我,因为您可以看到我的 Java 语言水平是初学者:);

//=========================================================== Methods 
  public static void record(String x, int y)
   String[] stringArray = new String[100];
   stringArray[y] = x;
   return stringArray;
   }
public static double[] record(double x, int y){
double[] doubleArray = new double[100];
doubleArray[y] = x;
return doubleArray;
} 

还有我的选择;

 case 1:  {
    System.out.println("** Recording a new student");
    System.out.println("*** Please use lower case");
    in.nextLine(); // for solve skipping 

    System.out.print("Enter Student Name and Surname: ");
    String namex = in.nextLine();
    name=record(namex,accountNumber);


    System.out.print("Enter Student Gender(m/f): ");
    String genderx = in.nextLine();
    gender=record(genderx,accountNumber);

    System.out.print("Enter Student Number: ");
    String studentNox = in.nextLine();
    studentNo=record(studentNox,accountNumber);


    System.out.print("Enter Student GPA: "); // i dont use method here for testing
    gpa[accountNumber] = in.nextDouble();


    accountNumber++;


    System.out.println("New Student Recorded. There are ["+accountNumber+"] students in system.");
    System.out.println("");
  }break;

【问题讨论】:

  • 返回字符串数组的 void 方法在几个方面看起来很奇怪。

标签: java arrays methods pass-by-reference


【解决方案1】:

问题是你每次在数组里面放东西时都在初始化:

String[] stringArray = new String[100];

double[] doubleArray = new double[100];

您必须确保这些数组的初始化在您的应用程序中只发生一次,可能是在声明这些静态数组时。知道了这一点,您的 record 方法应该如下所示(基于您的代码):

public static void record(String x, int y)
    stringArray[y] = x;
}

public static void record(double x, int y) {
    doubleArray[y] = x;
}

另外,作为基础知识,Java从不通过引用传递,它只通过值传递。更多信息在这里:Is Java "pass-by-reference" or "pass-by-value"?

【讨论】:

  • 你是对的,它是传值。我的错...所以,我用这些更改了我的代码,并且我的 main 中有 stringArray 命名数组,但是我的编译给出了 stringArray 的错误“...无法解析为变量”我需要更多定义这些数组吗?
  • @GökhanNas 根据您问题中的实际代码,我无法为您的新问题提供解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多