在开关情况下出现错误 - > RUNNING,ABORTED和READY无法解析为变量。我能做些什么让它发挥作用?尝试了enum,但它确实无法正常工作。
我无法编辑的主要课程:
public class Main {
public static void main(String[] args) throws InterruptedException {
StringTask task = new StringTask("A", 70000);
System.out.println("Task " + task.getState());
task.start();
if (args.length > 0 && args[0].equals("abort")) {
/*<- code that interrupts task after 1 sec and start a new thread
*/
}
while (!task.isDone()) {
Thread.sleep(500);
switch(task.getState()) {
//error case RUNNING: System.out.print("R."); break;
//error case ABORTED: System.out.println(" ... aborted."); break;
//error case READY: System.out.println(" ... ready."); break;
default: System.out.println("unknown state");
}
}
System.out.println("Task " + task.getState());
System.out.println(task.getResult().length());
}
}
StringTask类:
public class StringTask implements Runnable {
String string;
String result = "";
String status = "";
int x;
boolean end = false;
boolean done = false;
public StringTask(String string, int x) {
this.string = string;
this.x = x;
this.status = "CREATED";
}
public void start() {
Thread thread = new Thread(this);
thread.start();
}
public void run() {
this.status = "RUNNING";
synchronized (this.result) {
try {
for (int i = 0; i < x; i++) {
result += string;
}
this.status = "READY";
this.done = true;
} catch (Exception ex) {
this.status = "ABORTED";
this.done = false;
}
}
}
public void abort() {
this.end = true;
this.done = true;
this.status = "ABORTED";
Thread.interrupted();
}
public StringTask() {
this.status = "ABORTED";
}
public String getState() {
return this.status;
}
public boolean isDone() {
return this.done;
}
public String getResult() {
return this.result;
}
}
答案 0 :(得分:1)
我刚注意到你不允许编辑主类。要改善您的问题,您必须制作enum
来存储状态:
public enum Status {
RUNNING, ABORTED, READY
}
将StringTask#getState
更改为返回Status
后,您可以使用switch语句:
switch (task.getState()) {
case RUNNING:
System.out.print("R.");
break;
case ABORTED:
System.out.println(" ... aborted.");
break;
case READY:
System.out.println(" ... ready.");
break;
default:
System.out.println("unknown state");
}
答案 1 :(得分:0)
您是否尝试在00:00:00
案例中使用String
?
switch
而不是"RUNNING"
等?
答案 2 :(得分:-1)
您的作业似乎是让主要课程与Enum
一起使用,为此,您必须更改StringTask
课程。将状态的类型更改为State
State status;
public StringTask(String string, int x) {
this.string = string;
this.x = x;
this.status = State.CREATED;
}
...
public State getState() {
return this.status;
}
...
enum State {
RUNNING, ABORTED, READY
}
然后你的开关应该可以正常工作
switch(task.getState()) {
case RUNNING:
System.out.print("R.");
break;
case ABORTED:
System.out.println(" ... aborted.");
break;
case READY:
System.out.println(" ... ready.");
break;
default:
System.out.println("unknown state");
}