Can Java print text (letter by letter) into the command prompt? - java

Timer timer = new Timer();
TimerTask task = new TimerTask(){
int letter = 0;
#Override
public void run() {
if(letter<StatementInput.length()){
System.out.print(StatementInput.charAt(letter));
letter++;
}else{timer.cancel();}
}
};
timer.scheduleAtFixedRate(task,0,100 );
}
I'm trying to print out text one character at a time, with a small interval between each letter. When I try Thread.sleep or the above code, it won't print smoothly, the text comes out in bunches. Is there any way for me to smoothen it out?
I am running the code in intellij and am new to Java.
EDIT: Here's the full source code:
import java.util.Timer;
import java.util.TimerTask;
public class test {
public static void statement(String StatementInput) throws InterruptedException {
Timer timer = new Timer();
TimerTask task = new TimerTask(){
int letter = 0;
#Override
public void run() {
if(letter<StatementInput.length()){
System.out.print(StatementInput.charAt(letter));
letter++;
}else{timer.cancel();}
System.out.flush();
}
};
timer.scheduleAtFixedRate(task,0,100 );
}
public static void main(String[] args) throws InterruptedException {
test.statement("Hello World!!!!");
}
}

Related

Execute a few lines of program after a certain amount of seconds

I want to execute a few lines of program after a certain amount of seconds. How does one do this?
I already tried something but it won't work. The lamps are supposed to go on and off after a certain amount of seconds.
Beginner program so sorry if this is a stupid question.
package io.github.zeroone3010.yahueapi;
import org.omg.PortableServer.POAManagerPackage.State;
import java.util.*;
public class looptest
{
public static void main(String args[])
{
final String bridgeIp = "ip";
final String apiKey = "key";
final Hue hue = new Hue(bridgeIp, apiKey);
final Room room = hue.getRoomByName("Woonkamer").get();
int counter = 0;
boolean loop;
Timer timer = new Timer();
new java.util.Timer().schedule(
new java.util.TimerTask()
{
int secondsPassed = 0 ;
public void run()
{
secondsPassed++;
System.out.println(secondsPassed);
room.getLightByName("Tv 1").get().turnOn();
if (secondsPassed > 3) // after 3 seconds tv 2 on
room.getLightByName("Tv 2").get().turnOn();
if (secondsPassed > 11) // after 11 seconds tv 1 and 2 off
room.getLightByName("Tv 1").get().turnOff();
room.getLightByName("Tv 2").get().turnOff();
}
},
5000
};
{
I understand that your intention is to:
turn "Tv 1" light on immediately
turn "Tv 2" light on after 3 seconds
turn "Tv 1" and "Tv 2" lights off after 11 seconds
You should turn the "Tv 1" on light in the main method (outside of Timer.schedule block). Moreover you should schedule both future activities as independent tasks with proper delays as follows:
room.getLightByName("Tv 1").get().turnOn();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
room.getLightByName("Tv 2").get().turnOn();
}
}, 3000L);
timer.schedule(new TimerTask() {
#Override
public void run() {
room.getLightByName("Tv 1").get().turnOff();
room.getLightByName("Tv 2").get().turnOff();
}
}, 11000L);
I hope it helps.
I can see a syntax error in your code. You have missed to close the timer.schedule( ) properly, used a curly braces } instead of parenthesis ). Please update it
new java.util.Timer().schedule(
new java.util.TimerTask()
{
public void run()
{
//........
}
},
5000
);
Snipplet: Java TimerTask sample
import java.util.Timer;
import java.util.TimerTask;
class Main {
public static void main(String[] args) {
System.out.println("Timer Sample!");
long delayInMilliSeconds = 5000;
Timer timer = new Timer();
timer.schedule(new java.util.TimerTask(){
int secondsPassed = 0 ;
public void run()
{
System.out.println("Executed after the delay");
timer.cancel();
}
},delayInMilliSeconds);
System.out.println("Task run after "+ delayInMilliSeconds +" ms");
}
}

How to display seconds of the timer in the output screen?

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class Java {
Toolkit toolkit;
Timer timer;
int t=10000,total;
public Java(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
total =seconds * t;
System.out.println(total);
timer.schedule(new RemindTask(), total);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
System.exit(0);
}
}
public static void main(String args[]) {
new Java(5);
System.out.println("Timer started");
}
}
How can I display the seconds similar to countdown timer in output screen, I want to use it in a quiz program
0:53 => 0:52 like this ...
What you can do is schedule a task at a fixed rate (Timer.scheduleAtFixedRate) using a period of 1 second. As far as possible, we should refrain from calling the System.exit(0) and wait for the threads to complete their tasks. We can make the main thread (the thread that started the timer) sleep for the duration of the timer tasks and then when it finally wakes up, it cancels the timer:
private final Timer timer;
public CountDownTimer(int seconds) {
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(seconds), 0, 1000);
}
class RemindTask extends TimerTask {
private volatile int remainingTimeInSeconds;
public RemindTask(int remainingTimeInSeconds) {
this.remainingTimeInSeconds = remainingTimeInSeconds;
}
public void run() {
if (remainingTimeInSeconds != 0) {
System.out.println(remainingTimeInSeconds + " ...");
remainingTimeInSeconds -= 1;
}
}
}
public static void main(String args[]) throws InterruptedException {
CountDownTimer t = new CountDownTimer(5);
System.out.println("Timer started");
Thread.sleep(5000);
t.end();
}
private void end() {
this.timer.cancel();
}

Time interval in Java

how to call a method after a time interval?
e.g if want to print a statement on screen after 2 second, what is its procedure?
System.out.println("Printing statement after every 2 seconds");
The answer is using the javax.swing.Timer and java.util.Timer together:
private static javax.swing.Timer t;
public static void main(String[] args) {
t = null;
t = new Timer(2000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Printing statement after every 2 seconds");
//t.stop(); // if you want only one print uncomment this line
}
});
java.util.Timer tt = new java.util.Timer(false);
tt.schedule(new TimerTask() {
#Override
public void run() {
t.start();
}
}, 0);
}
Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.
Also do not mix threads in your code while you can do it without threads!
Hope this would be helpful!
Create a Class:
class SayHello extends TimerTask {
public void run() {
System.out.println("Printing statement after every 2 seconds");
}
}
Call the same from your main method:
public class sample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new SayHello(), 2000, 2000);
}
}
It can be achieved using Timer class
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
System.out.println("print after every 5 seconds");
}
},0,5000);
**You Must try this code. It works for me. **
Use Visual Studio and create Main.java file then paste this code and right click mouse>run java
`public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 12; i++) {
System.out.println(i);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
`

Actionlistener of a Timer object displays nothing

i am usin the timer class and in the docs it is written that i should import javax.swing.Timer to use it. does it mean that i can not use it in my normal java file? because i tried the below code, and it displays nothing:
static ActionListener timeStampListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("action listener");
for (int i = 1; i <= logfile.getTotalLines(); i++) {
System.out.println("Engine Time(ms): " +
logfile.getFileHash().get(i).getTimeStampInSec());
}
}
};
Timer t = new Timer(2, timeStampListener);
t.setRepeats(true);
t.start();
the problem is your main thread exist before starting timer thread .since your application is non-gui use util.Timer instead Swing.Timer ..if you want to work this code using swing timer then add a swing component .add new jframe() and see it's working ..you don't need swing.timer use util timer .
static ActionListener timeStampListener1 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("hi");
}
};
public static void main(String[] args) {
new JFrame(); //add this line
Timer t = new Timer(2, timeStampListener1);
t.setRepeats(true);
t.start();
}
or give some times by adding thread.sleep to timer to on and see it's working
Timer t = new Timer(2, timeStampListener1);
t.setRepeats(true);
t.start();
Thread.sleep(1000);
this is how can u use util timer for this
imports
import java.util.Timer;
import java.util.TimerTask;
code
public static void main(String[] args) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("action listener");
for (int i = 1; i <= logfile.getTotalLines(); i++) {
System.out.println("Engine Time(ms): "
+ logfile.getFileHash().get(i).getTimeStampInSec());
}
}
}, 500, 2);
}
No, it means that you should import which Timer class you will use. When you import javax.swing.Timer you specifies Timer class in javax.swing package. You can use it in your java file.
Anyway, have you tried not using static keyword with your timeStampListener?

Why does my java timer stop after seemingly random number of iterations?

I am trying to create a simple java program that will run indefinitely and output a number every second. I believe my code here should do this; however, it stops after the variable i gets to either 2, 3 or 4. Randomly. Most of the time it hits 3. I do not think that the program stopping is based on i at all, but something i'm overlooking perhaps.
All this program needs to do is spit out the second count using a timer. I feel like my code might be a little over complicated so please let me know if i'm making it too hard.
package testing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class driver {
static int delay = 1000; //milliseconds
private Timer timer;
int i = 0;
public driver(){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println(i);
i++;
}
};
timer = new Timer(delay, taskPerformer);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new driver();
}
});
}
}
Everything is just right in your program, but one.
Your program starts (from main() obviously), which starts the timer, timer method initiates the process of displaying time/number every second, and after that, the main thread dies! resulting in completion of program execution.
So to avoid this you simply can keep main thread busy.
Here's the simplest way :
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
driver d = new driver();
}
});
for(;;); // <-- **Check this out :D**
}

Categories