我正在尝试将我的int“n”设置为由用户输入定义。但它永远不会被设定,我不确定是什么问题。我不是很擅长java和这是IS作业。我认为我的问题非常基本,但我被困住了。 所以,重申一下我的问题。为什么我不能将我的int设置为用户输入? “n”问题不是实际的作业,但为了让我的作业正常工作,必须设置“n”。
package printer.java;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;
import java.util.Scanner;
public class PrinterJava {
// Declaring ints needed
int count = 0;
int jobCount = 0;
int done = 0;
int time = 0;
int jobTimerDelay = 1000;
int jobTimerPeriod = 1000;
int timeTimerDelay = 1000;
int timeTimerPeriod = n * 60 * 1000;
// declaring timers needed
Timer jobTimerTimer = new Timer();
Timer timeTimerTimer = new Timer();
// This is a timer that is supposed to create new "pages" every 5 seconds.
//the pages have to be a random "size between 1 and 5 pages long"
public void jobTimer() {
jobTimerTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
count++;
Random dom = new Random();
int p = dom.nextInt(5) + 1;
if (count % 5 == 0) {
pages page = new pages(); // Creates a new page every 5 seconds
page.pages = p;
jobCount++;
jobQueue.offer(page); // pushes the newly created pages into the queue
System.out.println("A new Job has been created! Job queue size: " + jobQueue.size());
System.out.println("Total Jobs created: " + jobCount);
} else if (!jobQueue.isEmpty() && count > 2 && count % 2 == 0) {
done++;
jobQueue.remove();
System.out.println("Job printed successfully! total jobs printed: " + done);
}
}
}, jobTimerDelay, jobTimerPeriod);
}
// this is the queue that holds the pages
Queue<Object> jobQueue = new LinkedList<Object>();
public class pages { // pages
int pages;
// constructor
public pages() {
}
public pages(int NumPages) {
this.pages = NumPages;
}
}
public void timerTwo() {
timeTimerTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
PrinterJava runOne = new PrinterJava(); // creats an instance of my page creator
runOne.jobTimer();
System.out.println("Please Enter Run time in minutes as an integer: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
}
}, timeTimerDelay, timeTimerPeriod);
}
public static void main(String[] args) {
PrinterJava runTwo = new PrinterJava(); // creats an instance of my page creator
runTwo.timerTwo();
}
}
答案 0 :(得分:0)
当你说int n
你宣布一个新变量时,所以在下一行之后你就不再有它了。另外,我没有看到n
被声明为实例变量或其他任何地方。
如果您在行int n = scan.nextInt();
之后设置断点并查看是否在那里设置了断点(或者您可以使用System.out.println()
将其打印出来,该怎么办?
答案 1 :(得分:0)
此行不会编译,因为n
尚未定义:
int timeTimerPeriod = n * 60 * 1000;
但是,如果它不会按预期工作:
timeTimerTimer.scheduleAtFixedRate(new TimerTask() {...}, timeTimerDelay, timeTimerPeriod);
因为在n
方法中定义了TimerTask.run()
。要解决这个问题,请考虑进行此更改:
int timeTimerPeriod = 60 * 1000; // instance variable
int n = 0;
...
public void timerTwo() {
System.out.println("Please Enter Run time in minutes as an integer: ");
Scanner scan = new Scanner(System.in);
n = scan.nextInt(); // <-- read n here for first time
timeTimerTimer.scheduleAtFixedRate(new TimerTask() {...}, timeTimerDelay, timeTimerPeriod * n);
}