尝试帮助学生修理计算机数学课程的作业。当他运行他的小程序时,文本重叠。我们如何改变这个?
该作业旨在教授基本的if-then循环。
以下是代码:
import java.awt.*;
import java.lang.*;
import java.applet.*;
public class HibbertJ_if extends Applet {//more points lost
public void init() { }
public void paint(Graphics g) {
int Rigby=(int)(Math.random()*123)+123;
int Mario=(int)(Math.random()*321)+2;
int SJF = (int)(Math.random()*2)+3;
int Drake = (int)(Math.random()*9)+7;
int Luigi = (int)(Math.random()*6)+8;
int Benson = (int)(Math.random()*3)+4;
boolean DoYouLikeToLose=getRandomBoolean();
boolean DoYouLikeMario=getRandomBoolean();
boolean DoYouSlackOff=getRandomBoolean();
boolean IAmLolzingAtYou=getRandomBoolean();
boolean IAmBeatingYou=getRandomBoolean();
boolean DoYouLikeRegularShow=getRandomBoolean();
String Go="Mr. Win";
String Bball="Wii U";
String Hib="PS4";
String Son="3DS";
String Marshall="Compaq";
String Jordan="Beats";
String student="sweeeeet";//need 3 string variables
//type code here
//start first word
g.drawString("x = "+Rigby,100,15);
g.drawString("y= "+SJF,200,15);
g.drawString("Headaches= "+DoYouLikeMario,300,15);
if(DoYouLikeMario)//equals NOT =, = assigns values, == says if same
{
if(SJF>=Rigby)//greater than or equal to
{
g.drawString("Mordo has a "+Rigby,10,15);
}
else
g.drawString("SMB has a ",10,15);;
}
else
g.drawString("SMG4 has a ",10,15);
if(DoYouLikeMario)//equals NOT =, = assigns values, == says if same
{
g.drawString(Go,10,30);
if(SJF>=Rigby)//greater than or equal to
g.drawString(Bball,10,30);
}
if(Rigby<=SJF)//less than or equal to
g.drawString(Hib,10,45);
else if(SJF>Rigby)//greater than
g.drawString(Son,10,60);
else
{
g.drawString(student,10,75);
if(Mario<SJF)//less than
{
g.drawString(Marshall,10,90);
if(Rigby!=Rigby)//Not equal to
g.drawString(student,10,105);
}
}
if(Mario==SJF&&SJF>Rigby)//(equal to) AND (greater than)
g.drawString(Jordan,10,120);
if(Luigi==Drake&&Benson>Rigby)//(equal to) AND (greater than)
g.drawString(Bball,10,120);
if(Rigby==SJF||SJF==Mario)//(equal to) OR (equal to)
g.drawString(student,10,135);
if(Mario==Drake||Rigby==SJF)//(equal to) OR (equal to)
g.drawString(Go,10,135);
else
g.drawString(Go,10,135);
if(DoYouLikeMario)
g.drawString(Bball,10,135);
if(DoYouSlackOff)
g.drawString(Hib,10,135);
if(IAmLolzingAtYou)
g.drawString(Son,10,135);
if(true)
g.drawString("This always happens",1,100);
//if(false); also works, ; means some line of code could be there
}
public boolean getRandomBoolean() {
return Math.random() < 0.5;
}
}
答案 0 :(得分:0)
if(Rigby==SJF||SJF==Mario)
g.drawString(student,10,135);
if(Mario==Drake||Rigby==SJF)
g.drawString(Go,10,135);
else
g.drawString(Go,10,135);
没有花括号的块非常容易出错。在这种特定情况下,编译器将其解释为:
if(Rigby==SJF||SJF==Mario) {
g.drawString(student,10,135);
}
if(Mario==Drake||Rigby==SJF) {
g.drawString(Go,10,135);
} else {
g.drawString(Go,10,135);
}
请注意它与缩进意味着什么有很大不同?最佳做法是在每个 if
和else
上添加花括号,即使它们是单行。这避免了许多未来的错误并且成本非常低。
除此之外,通过手动指定位置来绘制文本很难编写和维护。尝试使用layout manager,它们是专门创建的,以确保所有内容都在其位置且没有重叠