【发布时间】:2023-03-23 23:50:02
【问题描述】:
我正在处理以下任务:尝试 moveOn 或 backUp 或在非法时评估 seesCD 会导致突然的 System.exit(0) 没有解释。在这种情况下,用户会喜欢跟踪输出。修改这三个方法,调用一个解释问题的私有方法(用showMessageDialog),然后终止。
我写了以下代码(请向下滚动代码):
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Vic extends Object
{
private static final String NONE = "0";
/////////////////////////////////
private String itsSequence = "";
private int itsPos = 1;
private final int itsID; // assigned by the constructor
private void trace (String action)
{
System.out.println ("Vic# " + itsID + ": " + action
+ itsPos + "; sequence= " + itsSequence);
} //======================
public void backUp()
{
if (itsPos == 1)
error("Could not backUp");
itsPos--;
trace ("backUp to slot ");
} //======================
public void moveOn()
{
if ( ! seesSlot())
error("Could not moveOn");
itsPos++;
trace ("moveOn to slot ");
} //======================
public boolean seesSlot()
{
return itsPos < itsSequence.length();
} //======================
public boolean seesCD()
{
if ( ! seesSlot())
error("Can't see CD, there is no slot");
String s = itsSequence.substring (itsPos, itsPos + 1);
return ! s.equals (NONE);
} //======================
private void error(String message)
{
JOptionPane.showMessageDialog(null, "ERROR: " + message);
System.exit(0);
}
}
编译时收到以下错误消息:
“变量 itsID 可能尚未初始化”。 并突出显示这一行。“public class Vic extends Object”
【问题讨论】:
-
首先,使用可以帮助您进行格式化的IDE,不要到处插入空行。这段代码一团糟,让人难以理解。
标签: java methods private bluej