所以我很清楚我可以使用以下代码延迟行
long time=100L;
listLine[1] = "You are on a war-torn Plateau";
for ( int i= 0; i < listLine[1].length(); i++) {
// for loop delays individual String characters
System.out.print(listLine[1].charAt(i));
Thread.sleep(time); //time is in milliseconds
}
System.out.println(""); // this is the space in between lines
但是,在代码中重复使用它是多余的,并且很难读取我的代码。有没有办法实现一个函数/方法,以便代码看起来类似于以下。
public static void delay() {
// your solution to my problem goes here
System.out.print(listLine[0].delay();
提前谢谢你:)
答案 0 :(得分:1)
您似乎正在尝试根据第一个代码段创建延迟的输入效果。那里的代码应该没问题,你需要做的就是将代码迁移到一个方法中,这样你就可以反复创建延迟效果。
public void delay(String s, long delay) {
for ( int i= 0; i < s.length(); i++) {
// for loop delays individual String characters
System.out.print(s.charAt(i));
Thread.sleep(delay); //time is in milliseconds
}
System.out.println(""); // this is the space in between lines
}
接着是方法调用,例如
delay("You are on a war-torn Plateau", 100L);
答案 1 :(得分:0)
您可以先将字符串转换为字符数组,然后使用代码
进行打印public static void main(String[] args){
String sample = "Hello World";
printCharactersWithDelays(sample, TimeUnit.MILLISECONDS, 400);
}
public static void printCharactersWithDelays(String sample, TimeUnit unit, long delay){
List<Character> chars = sample.chars().mapToObj(e->(char)e).collect(Collectors.toList());
chars.forEach(character -> {
System.out.println(character);
try {
unit.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
答案 2 :(得分:0)
这是你的答案:
package stack;
import java.util.Timer;
import java.util.TimerTask;
public class Scheduling {
String string = "You are on a war-torn Plateau";
Timer timer;
int index = 0;
public Scheduling() {
timer = new Timer();
//this method schedule the task repeatedly with delay of 1sec until the timer is not cancel
timer.schedule(new Delay(), 0, 1000);
}
public class Delay extends TimerTask {
@Override
public void run() {
if (index == string.length()) {
timer.cancel();
} else {
System.out.println(string.charAt(index));
index++;
}
}
}
public static void main(String[] args) {
new Scheduling();
}
}
在上面的回答中,我使用java.util.Timer
类进行计时,TimerTask
类用于执行我们想要做的延迟任务。