I have this homework assignment where i have to input a text file into my java program. the file is a "bed sensor", and tells you if the person is in a deep sleep, a restless sleep, or interrupted sleep(awake), with 0s, 1s, and 2s respectively. each line has a 0, 1, or 2 and there are 86,400 lines (one line for each second of the day).
I have figured out most of the assignment but one part i cannot figure out how to code.
My problem is i have to figure out when the person falls asleep and then output "Sleep time: (answer) hours after midnight".
i've been using counters and if statements and i would like to continue along this path if possible. i've attached my code.. and i feel like this should be pretty simple to figure out based on what i've already done... i just cannot wrap my head around it. i would appreciate any help or advice. thanks
public static void main(String[] args) {
try {
File sleepDataFile = new File("/Users/homeWork3/sleep_data.csv");
Scanner sleepData = new Scanner(sleepDataFile); // scans the data from the file into this java program
double totalSecondsCounter = 0, wakeCounter = 0, timeAwakeCounter = 0, timeAsleepCounter = 0, deepSleepCounter = 0, restlessSleepCounter = 0, interruptedSleepCounter = 0;
double wakeUpTime = 0, sleepTime = 0;
double sleepQuality = 0;
boolean inSleep = false;
while (sleepData.hasNextLine()) // this loop writes data to java as long as there is a next line
{
String data = sleepData.nextLine(); // converts the file data to strings
double val = Double.parseDouble(data); // changes string type to double type
totalSecondsCounter++;
if (inSleep == true) {
timeAsleepCounter++;
}
if (inSleep == false) {
timeAwakeCounter++;
}
if (val == 0) //deep sleep
{
deepSleepCounter++;
inSleep = true;
wakeCounter = 0;
}
if (val == 1) //restless sleep
{
restlessSleepCounter++;
inSleep = true;
wakeCounter = 0;
}
if (val == 2) // interrupted sleep / awake
{
wakeCounter++;
inSleep = false;
}
if (val == 2 && wakeCounter < 1800) {
interruptedSleepCounter++;
inSleep = true;
}
if (val == 2 && wakeCounter > 1800) {
inSleep = false;
}
if (wakeCounter == 1800) // 1800 seconds = 30 minutes. counter is set for 30 min of interrupted sleep.
{
wakeUpTime = totalSecondsCounter;
}
if (val != 2) {
}
}
sleepData.close();
System.out.println("Sleep Report for 24 hour period.");
System.out.println("----------------------------------------------------------");
System.out.println("Wake Time: \t\t\t\t" + wakeUpTime / 60 / 60 + "\t hours after midnight");
System.out.println("Sleep Time: \t\t\t\t" + sleepTime / 60 / 60 + "\t\t\t hours after midnight");
System.out.println("Duration of Deep Sleep: \t\t" + deepSleepCounter / 60 / 60 + "\t hours");
System.out.println("Duration of Restless Sleep: \t\t" + restlessSleepCounter / 60 / 60 + "\t hours");
System.out.println("Duration of Interrupted Sleep: \t\t" + interruptedSleepCounter / 60 / 60 + "\t hours");
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
I'll just give you a (comprehensive) hint, since this is a homework question.
My problem is i have to figure out when the person falls asleep and then output "Sleep time: (answer) hours after midnight".
First of all, you're going to want to initialize two variables before your while loop:
Some boolean flag variable hasFallenAsleepYet
Some double variable fallenAsleepTime
Like so:
boolean hasFallenAsleepYet = false;
double fallenAsleepTime;
Now, inside of your while loop, as you're iterating through sleepData, you're going to want to count the time taken until the person falls asleep, then stop counting.
if(!hasFallenAsleepYet) {
if(val == someInteger || val == someOtherInteger){ // some condition to tell if the person is asleep
hasFallenAsleepYet = true;
fallenAsleepTime = totalSecondsCounter;
}
}
I'll leave you to figure out what the numbers someInteger and someOtherInteger are, but you should be able to figure it out quickly. They key takeaway here is that you need to initialize some flag variable, so that you stop keeping track of fallenAsleepTime after a certain condition is met.
Related
I'd like to add a progress indicator to a command-line Java program.
For example, if I'm using wget, it shows:
71% [===========================> ] 358,756,352 51.2M/s eta 3s
Is it possible to have a progress indicator that updates without adding a new line to the bottom?
Thanks.
I use following code:
public static void main(String[] args) {
long total = 235;
long startTime = System.currentTimeMillis();
for (int i = 1; i <= total; i = i + 3) {
try {
Thread.sleep(50);
printProgress(startTime, total, i);
} catch (InterruptedException e) {
}
}
}
private static void printProgress(long startTime, long total, long current) {
long eta = current == 0 ? 0 :
(total - current) * (System.currentTimeMillis() - startTime) / current;
String etaHms = current == 0 ? "N/A" :
String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(eta),
TimeUnit.MILLISECONDS.toMinutes(eta) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(eta) % TimeUnit.MINUTES.toSeconds(1));
StringBuilder string = new StringBuilder(140);
int percent = (int) (current * 100 / total);
string
.append('\r')
.append(String.join("", Collections.nCopies(percent == 0 ? 2 : 2 - (int) (Math.log10(percent)), " ")))
.append(String.format(" %d%% [", percent))
.append(String.join("", Collections.nCopies(percent, "=")))
.append('>')
.append(String.join("", Collections.nCopies(100 - percent, " ")))
.append(']')
.append(String.join("", Collections.nCopies((int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
.append(String.format(" %d/%d, ETA: %s", current, total, etaHms));
System.out.print(string);
}
The result:
First when you write, don't use writeln(). Use write(). Second, you can use a "\r" to Carriage Return without using \n which is a New line. The carriage return should put you back at the beginning of the line.
This is my code to update the Status:
String[] status = new String[] {"Version: 1.5.0", "https://discord.gg/arWEM2h", "Love Backxtar", "You want me!", "Type: ~help", "User Counter: %members"};
int next = 60;
public void onSecond() {
if(next%5 == 0) {
if(!hasStarted) {
hasStarted = true;
StatChannelCommand.onStartUp();
}
Random rand = new Random();
int i = rand.nextInt(status.length);
shardMan.getShards().forEach(jda -> {
String text = status[i].replaceAll("%members", "" + jda.getUsers().size());
jda.getPresence().setActivity(Activity.playing(text));
});
StatChannelCommand.checkStats();
if(next == 0) {
next = 60;
}
}
else {
next--;
}
}
But the String is running every second. I thought it was every 5 seconds. I did 60 sec % 5. What is wrong with this code?
When you enter the method onSecond() for the first time, the condition next%5 == 0 will be true. The variable next will not be updated, because this happens only in the else part. So, on next run of the method next will still be 60.
I'd like to add a progress indicator to a command-line Java program.
For example, if I'm using wget, it shows:
71% [===========================> ] 358,756,352 51.2M/s eta 3s
Is it possible to have a progress indicator that updates without adding a new line to the bottom?
Thanks.
I use following code:
public static void main(String[] args) {
long total = 235;
long startTime = System.currentTimeMillis();
for (int i = 1; i <= total; i = i + 3) {
try {
Thread.sleep(50);
printProgress(startTime, total, i);
} catch (InterruptedException e) {
}
}
}
private static void printProgress(long startTime, long total, long current) {
long eta = current == 0 ? 0 :
(total - current) * (System.currentTimeMillis() - startTime) / current;
String etaHms = current == 0 ? "N/A" :
String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(eta),
TimeUnit.MILLISECONDS.toMinutes(eta) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(eta) % TimeUnit.MINUTES.toSeconds(1));
StringBuilder string = new StringBuilder(140);
int percent = (int) (current * 100 / total);
string
.append('\r')
.append(String.join("", Collections.nCopies(percent == 0 ? 2 : 2 - (int) (Math.log10(percent)), " ")))
.append(String.format(" %d%% [", percent))
.append(String.join("", Collections.nCopies(percent, "=")))
.append('>')
.append(String.join("", Collections.nCopies(100 - percent, " ")))
.append(']')
.append(String.join("", Collections.nCopies((int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
.append(String.format(" %d/%d, ETA: %s", current, total, etaHms));
System.out.print(string);
}
The result:
First when you write, don't use writeln(). Use write(). Second, you can use a "\r" to Carriage Return without using \n which is a New line. The carriage return should put you back at the beginning of the line.
When the requestTime == 0 I get 2 results. I've printed "luck" into the for loop and it loops for 5 seconds but the thing is when it reaches 0 it prints two results. I get one result from the System.out which is in the if(requestTime == 0 ) then my for loop runs 1 more and I get another System.out (an updated one) from if(requestTime == 0 ) How can I fix this? I need to get the FINAL value. A friend told me I could use arrays but I have no idea how. I need to calculate inside the for loop and print the SUM of the values.
//TIMER METHOD
static int requestTime = 5;
public static void randomN () {
myTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if(requestTime > 0)
{
requestTime--;
}
else myTimer.cancel();
int nTimesRandom = (int) (Math.random()*6+1);
for (int i=0; i<nTimesRandom; i++) {
int rx = (int) (Math.random()*10+1);
int ry = (int) (Math.random()*10+1);
a = a+nTimesRandom;
if (Math.sqrt(Math.pow((a1x1-rx),2)+Math.pow((a1y1-ry),2))<3) {
reached1++;
if ( cap1 < 3 ) { cap1++; }
else if ( cap1 == 3 ) { nreached1++; }
}
else { oor++; }
if (Math.sqrt(Math.pow((a2x2-rx),2)+Math.pow((a2y2-ry),2))<3) {
reached2++;
if ( cap2 < 3 ) { cap2++; }
else if ( cap2 == 3 ) { nreached2++; }
}
else { oor++; }
if (Math.sqrt(Math.pow((a3x3-rx),2)+Math.pow((a3y3-ry),2))<3) {
reached3++;
if ( cap3 < 3 ) { cap3++; }
else if ( cap3 == 3 ) { nreached3++; }
}
else { oor++; }
System.out.println("luck");
}
oor = a -( reached1+reached2+reached3) ;
int totalreached = reached1+reached2+reached3 ;
if ( requestTime == 0 ) {
System.out.println( a + " communication requests were generated, " + totalreached + " of them were served, " + oor + " of them were unserved."); }
// System.out.println("Requests " + "X : " + rx + " Y: " + ry);
}
}, 0, 1000);
}
My console output is like this :
...
luck
...
142 communication requests were generated, 20 of them were served, 122 of them were unserved.
luck
luck
luck
luck
158 communication requests were generated, 23 of them were served, 135 of them were unserved.
If the request time is > 0, then you decrement requestTime, and then execute the rest of the method. So when requestTime is 1, it becomes 0, and then the rest of the code is executed.
If the request time is == 0, then you don't decrement requestTime, and then execute the rest of the method. So it stays at 0, and then the rest of the code is executed.
I guess that you either want to decrement always, or to avoid the execution of the rest of the code if requestTime is == 0.
I'd like to add a progress indicator to a command-line Java program.
For example, if I'm using wget, it shows:
71% [===========================> ] 358,756,352 51.2M/s eta 3s
Is it possible to have a progress indicator that updates without adding a new line to the bottom?
Thanks.
I use following code:
public static void main(String[] args) {
long total = 235;
long startTime = System.currentTimeMillis();
for (int i = 1; i <= total; i = i + 3) {
try {
Thread.sleep(50);
printProgress(startTime, total, i);
} catch (InterruptedException e) {
}
}
}
private static void printProgress(long startTime, long total, long current) {
long eta = current == 0 ? 0 :
(total - current) * (System.currentTimeMillis() - startTime) / current;
String etaHms = current == 0 ? "N/A" :
String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(eta),
TimeUnit.MILLISECONDS.toMinutes(eta) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(eta) % TimeUnit.MINUTES.toSeconds(1));
StringBuilder string = new StringBuilder(140);
int percent = (int) (current * 100 / total);
string
.append('\r')
.append(String.join("", Collections.nCopies(percent == 0 ? 2 : 2 - (int) (Math.log10(percent)), " ")))
.append(String.format(" %d%% [", percent))
.append(String.join("", Collections.nCopies(percent, "=")))
.append('>')
.append(String.join("", Collections.nCopies(100 - percent, " ")))
.append(']')
.append(String.join("", Collections.nCopies((int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
.append(String.format(" %d/%d, ETA: %s", current, total, etaHms));
System.out.print(string);
}
The result:
First when you write, don't use writeln(). Use write(). Second, you can use a "\r" to Carriage Return without using \n which is a New line. The carriage return should put you back at the beginning of the line.