Created
October 31, 2018 01:55
-
-
Save sh-zam/0e7831aa6479cd8277727414969aac5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class ProgressCounter { | |
private int counter = 0; | |
private void progressPercentage(int remain) { | |
if (remain > counter) { | |
throw new IllegalArgumentException(); | |
} | |
int maxBarSize = 100; | |
int remainPercent = (100 * remain) / counter; | |
char defaultChar = '.'; | |
String icon = "#"; | |
String bar = new String(new char[maxBarSize]); | |
bar = bar.replace('\0', defaultChar) + "]"; | |
StringBuilder barDone = new StringBuilder("["); | |
for (int i = 0; i < remainPercent; i++) { | |
barDone.append(icon); | |
} | |
String barRemain = bar.substring(remainPercent, bar.length()); | |
System.out.print("\r" + barDone + barRemain + " " + remainPercent + "%"); | |
} | |
private void progressbar() { | |
try { | |
synchronized (this) { | |
for (int i = 1; i <= counter; ++i) { | |
wait(); | |
progressPercentage(i); | |
} | |
} | |
System.out.println(); | |
} | |
catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
private void main(int val) throws InterruptedException { | |
counter = val; | |
Thread t1 = new Thread(this::progressbar); | |
t1.start(); | |
for (int i = 1; i <= counter; ++i) { | |
Thread.sleep(1000); | |
synchronized (this) { | |
notify(); | |
} | |
} | |
} | |
public static void main(String[] args) throws InterruptedException { | |
Scanner reader = new Scanner(System.in); | |
new ProgressCounter().main(reader.nextInt()); | |
reader.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment