gpt4 book ai didi

java - ArrayList 如何从构造函数中捕获一项的异常

转载 作者:行者123 更新时间:2023-12-01 10:51:19 24 4
gpt4 key购买 nike

如何从数组列表中捕获一项并抛出异常?我尝试编译这个程序,但出现错误。这是 film.add 行上的消息内容:rok 无法解析为变量。

这是我的代码。请快速答复并感谢

我有两个类。电影类和另一个类

 public class Film {

String tytul;
int rok;
double ocena;
String imierezysera;
String nazwiskorezysera;

public String toString()
{
return tytul+" "+rok+" "+ocena+" "+imierezysera+" "+nazwiskorezysera;
}


public String gettytul() {
return tytul;
}
public void settytul(String tytul) {
this.tytul = tytul;
}
public int getrok() {
return rok;
}
public void setrok(int rok) {
this.rok = rok;
}
public double getocena() {

return ocena;

}
public void setocena(double ocena) {
this.ocena = ocena;
}
public String getimierezysera() {
return imierezysera;
}
public void setimierezysera(String imierezysera) {
this.imierezysera = imierezysera;
}
public String getnazwiskorezysera() {
return nazwiskorezysera;
}
public void setnazwiskorezysera(String nzawiskorezysera) {
this.nazwiskorezysera = nzawiskorezysera;
}

public Film(String tytul, int rok, double ocena, String imierezysera, String nazwiskorezysera) {

this.tytul= tytul;

this.rok= rok;
this.ocena= ocena;
this.imierezysera= imierezysera;
this.nazwiskorezysera= nazwiskorezysera;
}



public String wyswietl() {
// TODO Auto-generated method stub
return tytul+" "+rok+" "+ocena+" "+imierezysera+" "+nazwiskorezysera;
}



}

}

另一个类

ArrayList<Film> film = new ArrayList<>();
System.out.println("title");
String tytul;
tytul = sc.next();
try{
System.out.println("year");
int rok;
rok = sc.nextInt();
}catch(Exception e)
{System.out.println("Wrong value");}



System.out.println("rating");
double ocena;
ocena =sc.nextDouble();

System.out.println("name");
String imierezysera;
imierezysera = sc.next();

System.out.println("surename);
String nazwiskorezysera;
nazwiskorezysera = sc.next();
film.add(new Film(tytul,rok,ocena,imierezysera,nazwiskorezysera));

这是我的代码

最佳答案

rok 已定义,并且仅存在于 try/catch block 的范围内。

注意:如果 nextInt() 失败,它不会消耗该单词,并且您的评分可能是无效的年份

你可以这样写

String yearStr = sc.next(); // always read the word, even if invalid
int rok = Integer.MIN_VALUE; // value to use if year is invalid.
try {
rok = Integer.parseInt(yearStr);
} catch (InvalidArgumentException e) {
System.out.println("Ignoring invalid year " + yearStr);
}

捕获异常然后忽略它而不检查发生了什么错误通常是一个坏主意。除非您知道所有可能的异常,否则您可能会遇到意想不到的异常。

关于java - ArrayList 如何从构造函数中捕获一项的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879802/

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