2017-08-11 42 views
0

所以我很清楚地知道,我可以用下面的代码如何在时间上一行用的方法打印一个字符

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

我真的不明白你想说实话。你想要一个嵌套循环? – SomeJavaGuy

+0

对于延迟,你可以使用Java 8的调度程序执行器服务功能,你可以在这里找到链接:https://stackoverflow.com/questions/45439694/how-to-interrupt-a-scheduledexecutorservice/45439902#45439902 –

+0

我不知道看不出原始代码中有多余的东西。这是我无法理解的第二个片段。 – shmosel

回答

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(); 
     } 
    }); 
} 
+0

你不需要收集到列表中 - 你可以简单地从流中打印。 –

+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); 
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类是用来做什么任务我们想要延迟处理。

+1

没有错误的问题(哲学)的答案, –

相关问题