0

I'm implementing a class called NumberPrinter that prints out a number (as read from command line arguments) repeatedly using the Timer class. It will print this number every interval seconds, starting from startTime.

A feature that needs to be added is that when a user input of 'q' is detected, the timer and the whole program should be terminated. I'm stuck here because I have no idea how to detect the user input.

Below is my current code.

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class NumberPrinter extends TimerTask {

  private double numberToPrint;

  NumberPrinter(double numberToPrint) {
    this.numberToPrint = numberToPrint;
  }

  public void run() {
    System.out.println(numberToPrint);
  }

  public static void main(String[] args) {
    // Arguments
    double numberToPrint = Double.parseDouble(args[0]);
    long startTime = Long.parseLong(args[1]);
    long interval = Long.parseLong(args[2]);

    // Timer
    Timer timer = new Timer();
    NumberPrinter number = new NumberPrinter(numberToPrint);
    timer.schedule(number, startTime, interval);

    // A scanner to keep track of the input from user
    Scanner sc = new Scanner(System.in);
    // Not sure about the following lines :(
    if (sc.nextLine() == "q") {
      System.out.println("asd");
      timer.cancel();
      sc.close();
    }
  }
}

Can anyone help me with this problem? :)

hsiaomijiou
  • 544
  • 4
  • 18

0 Answers0