我正在使用BlueJ进行此项任务,我在解决问题的这一部分时遇到问题,即将决策结构设置为确保未设置的无效数据,我已经尝试过了。其中我放置了if else声明 setName部分不起作用。如果我在setName的GraphicIllustrators主void部分中放置了1,则代码将显示错误。那么我需要在下面的代码中放置if else语句.BTW我使用继承来做这个。所以请指教。谢谢!
主类的编码:
public class Publishing_Inc
{
private int ID=0;
private String name="-Name Needed-";
private int level=0;
private String jobtitle="-Title Needed-";
private String edit="-Edit Skill-";
public void calculateID(){
int uniqueID;
uniqueID =((int)( Math.random()*10000)+1);
ID = uniqueID;
}
public int getID(){
return ID;
}
public void setName(String d) {
name = d;
}
public String getName() {
return name;
}
public void setTitle(String b){
jobtitle=b;
}
public String getTitle() {
return jobtitle;
}
public void calculatelevel(){
int uniquelevel;
uniquelevel =((int)( Math.random()*3)+1);
level = uniquelevel;
}
public int getlevel() {
return level;
}
public void setEdit(String z){
edit=z;
}
public String getEdit() {
return edit;
}
}
子类:
public class GraphicIllustrators extends Publishing_Inc
{
public void displayGraphInformation() {
System.out.println("ID: " + getID());
System.out.println("Name:" + getName());
System.out.println("Job Title: " + getTitle());
System.out.println("Level: " + getlevel());
System.out.println();
}
public static void main (String args[]) {
GraphicIllustrators graphic = new GraphicIllustrators ( );
graphic.calculateID ( );
graphic.setName (" Tim Cook" );
graphic.calculatelevel ();
graphic.setTitle ("Graphic Illustrators" );
graphic.displayGraphInformation( );
}
}
答案 0 :(得分:0)
public static void main (String args[]) {
GraphicIllustrators graphic = new GraphicIllustrators ( );
graphic.calculateID ( );
if (input instanceof String) {
graphic.setName ( input ); //where input comes from an input box or query or other source.
}
else
{
//alert the user.
}
graphic.calculatelevel ();
graphic.setTitle ("Graphic Illustrators" );
graphic.displayGraphInformation( );
}
当您将参数传递给不是setName
的函数String
时,Java将抛出异常。您需要将发送的对象强制转换为字符串。如果要阻止这种情况,则应在输入函数setName
之前检查输入。这将检查输入是否是对象String
的实例,如果没有提醒用户。