gpt4 book ai didi

java - 解决空指针异常

转载 作者:行者123 更新时间:2023-11-30 04:18:54 26 4
gpt4 key购买 nike

我从上周开始学习Java(我有C#的基础知识),现在正在练习类(class)。我不明白为什么会出现此异常,我尝试多次更改代码但没有任何效果。这是代码:

package javaapplication1;

import java.util.Scanner;

public class JavaApplication1 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Competitor[] competitors;
System.out.println("Enter number of competitors");
competitors = Create(sc.nextInt());
for(int i = 0;i<competitors.length - 1;i++)
for(int j=i+1;j<competitors.length;j++)
if(competitors[i].GetHeight()==competitors[j].GetHeight())
System.out.println(competitors[i]+" and "
+competitors[j] + "bounced to height"
+competitors[i].GetHeight());
}
static Competitor[] Create(int n) {
Competitor[] competitors = new Competitor[n];
for(Competitor c : competitors) {
c = new Competitor();
System.out.println("Enter name, id and bounce height");
c.SetName(sc.next());
c.SetId(sc.next());
c.SetHeight(sc.nextFloat());
}
return competitors;
}
}
class Competitor {
private String name;
private String id;
private float height;
public Competitor() {
}
public Competitor(String name, String id, float height) {
this.name = name;
this.id = id;
this.height = height;
}
public String GetName() {
return this.name;
}
public String GetId() {
return this.id;
}
public Float GetHeight() {
return this.height;
}
public void SetName(String name) {
this.name = name;
}
public void SetId(String id) {
this.id = id;
}
public void SetHeight(Float height) {
this.height = height;
}
}

我在这一行中得到了异常:if(competitors[i].GetHeight()==competitors[j].GetHeight())

这里有什么问题吗?

非常感谢!

最佳答案

Create 方法以错误的方式初始化竞争对手的值。试试这个:

    for(int i = 0;i<competitors.length;i++){
competitors[i] = new Competitor();
System.out.println("Enter name, id and bounce height");
competitors[i].SetName(sc.next());
competitors[i].SetId(sc.next());
competitors[i].SetHeight(sc.nextFloat());
}

还有一个建议。在 C# 中,方法名称以一个大写字符开头,而在 Java 中,它们以小写字符开头。

关于java - 解决空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17629759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com