Java if/for loop assistance - java

Below is my code...I am trying to make a countdown timer. Right now it works correctly in terms of counting down in the correct sequential order. I am trying to figure out how to place an if statement within the code so that is prints 1 minute and ''seconds, instead of 1 minutes and '' seconds
import java.util.Scanner;
public class countdown {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int minutes;
System.out.println("Please enter the timer countdown in minutes:");
minutes = scan.nextInt();
while (minutes < 1) {
System.out.print("Invalid entry: Enter 1 or more minutes: ");
minutes = scan.nextInt();
}
for (int i = minutes - 1; i >= 0; i--)
{
for (int s = 59; s >= 1; s--)
System.out.println(i + " minutes, " + s + " seconds");
System.out.println("The timer is done!");
}
}
}

Like this,
String minutes = i + (i > 1 ? " minutes" : " minute"); // put this line in outer loop
String seconds = s + (s > 1 ? " seconds" : " second"); // and this line in inner loop
System.out.println(minutes +", "+ seconds);

just add an if/else statement in there:
for (int i = minutes - 1; i >= 0; i--){
String minute;
if(minutes == 1)
minute = " minute ";
else
minute = " minutes ";
for (int s = 59; s >= 1; s--){
String seconds;
if(s == 1)
seconds = " second";
else
seconds = " second";
System.out.println(i + minute + s + seconds);
}
}
The other answer is probably better, but it uses a different syntax that makes all this code into a short line. They do basically the same thing.

These two if/else statements should work.
for (int s = 59; s >= 1; s--)
{
if (i == 1)
System.out.print(i + " minute, ");
else
System.out.print(i + " minutes, ");
if (s == 1)
System.out.println(s + " second");
else
System.out.println(s + " seconds");
}

Related

java- how to add time properly?

My code isn't working properly for example when a user put that right now is 5 h 43 m and 7 s and the user wanna add 3 h 50 m and 57 s the code compute and shows what will be the time adding but it shows 8 h 93 m and 64 s but I want that after 60 m it shows 9 h 34 m and 4 s so can u help me out.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner (System.in);
int startup_hour;
int startup_minute;
int startup_second;
int add_hours;
int add_minutes;
int add_seconds;
System.out.print("what time is it right now(hour)? \n");
startup_hour = user_input.nextInt();
System.out.print("what time is it right now(minutes? \n");
startup_minute = user_input.nextInt();
System.out.print("what time is it right now(seconds)? \n");
startup_second = user_input.nextInt();
System.out.println("The starting time is " + startup_hour
+ " hours " + startup_minute + " minutes " + "and "
+ startup_second + " seconds \n");
System.out.print("How many hours you wanna add? \n");
add_hours = user_input.nextInt();
System.out.print("How many minutes you wanna add? \n");
add_minutes = user_input.nextInt();
System.out.print("How many seconds you wanna add? \n");
add_seconds = user_input.nextInt();
System.out.println("The user wanna add " + add_hours
+ " hours " + add_minutes + " minutes "
+ "and " + add_seconds + " seconds \n");
int totalHours = (startup_hour + add_hours);
int totalMinutes = (startup_minute + add_minutes);
int totalSeconds = (startup_second + add_seconds);
if (totalSeconds == 60){
totalMinutes++;
totalSeconds = 0;
}
if (totalMinutes == 60){
totalHours++;
totalMinutes = 0;
}
System.out.println("After adding, the time would then be "
+ totalHours + " hours " + totalMinutes + " Minutes "
+ totalSeconds + " Seconds ");
*emphasized text*
}
}
thanku
The reason your program is not working because you are processing time, without using the standard unit, which is seconds.
For example:
Suppose the start up time is 1 hours 3 minutes and 57 seconds.
And the user want to add, 1 hour 57 minutes and 3 seconds.
The correct answer will be, 3 hours 1 Minutes 0 Seconds but your program will return 2 hours 61 Minutes 0 Seconds.
Now, why did this happen?
The reason are:
As already stated, you did not process time using the standard unit (seconds).
The condition in your if loop is not correct. You are only checking if the minutes/seconds are equal to 60. What if the minutes or seconds are 61 or more?
Solution:
The simplest solution is, first convert time into seconds, add how much time you want to add, then convert it back to hours:minutes:seconds. You won't even have to use if loop if you process time using seconds.
Here is the modified code, which works properly :
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System.in);
int startup_hour;
int startup_minute;
int startup_second;
int add_hours;
int add_minutes;
int add_seconds;
System.out.print("What time is it right now(hour) : ");
startup_hour = user_input.nextInt();
System.out.print("What time is it right now(minutes) : ");
startup_minute = user_input.nextInt();
System.out.print("What time is it right now(seconds) : ");
startup_second = user_input.nextInt();
System.out.println("The starting time is " + startup_hour + " hours " + startup_minute + " minutes "
+ "and " + startup_second + " seconds.");
System.out.println();
System.out.print("How many hours you wanna add : ");
add_hours = user_input.nextInt();
System.out.print("How many minutes you wanna add : ");
add_minutes = user_input.nextInt();
System.out.print("How many seconds you wanna add : ");
add_seconds = user_input.nextInt();
System.out.println("The user wanna add " + add_hours + " hours " + add_minutes + " minutes "
+ "and " + add_seconds + " seconds.");
System.out.println();
int totalSecondsAtStart = (startup_hour * 60 * 60) + (startup_minute * 60) + startup_second;
int totalSecondsToAdd = (add_hours * 60 * 60) + (add_minutes * 60) + (add_seconds);
int totalSeconds = totalSecondsAtStart + totalSecondsToAdd;
//Convert total seconds to hour, minutes and seconds;
int totalMinutes = (totalSeconds / 60);
int totalHours = (totalMinutes / 60);
int finalHours = totalHours;
int finalMinutes = totalMinutes - (totalHours * 60);
int finalSeconds = totalSeconds - (totalMinutes * 60);
System.out.println("After adding, the time would then be " + finalHours + " hours"
+ " " + finalMinutes + " Minutes " + finalSeconds + " Seconds.");
}
}
Notice how I converted time back into hours:minutes:seconds.

How to get time difference between two ZonedDateTimes and pretty print it like "4 hours, 1 minute, 40 seconds ago"?

This is how I call getTimeBetween function:
getTimeBetween(ZonedDateTime.now().minusHours(4).minusMinutes(1).minusSeconds(40), ZonedDateTime.now());
And I expect this output:
4 hours, 1 minute, 40 seconds ago
This is my getTimeBetween function:
private String getTimeBetween(ZonedDateTime zonedDateTime1, ZonedDateTime zonedDateTime2) {
Duration timeDifference = Duration.between(zonedDateTime1, zonedDateTime2);
if (timeDifference.getSeconds() == 0) return "now";
String timeDifferenceAsPrettyString = "";
Boolean putComma = false;
if (timeDifference.toDays() > 0) {
if (timeDifference.toDays() == 1) timeDifferenceAsPrettyString += timeDifference.toDays() + " day";
else timeDifferenceAsPrettyString += timeDifference.toDays() + " days";
putComma = true;
}
if (timeDifference.toHours() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.toHours() == 1) timeDifferenceAsPrettyString += timeDifference.toHours() + " hour";
else timeDifferenceAsPrettyString += timeDifference.toHours() % 24 + " hours";
putComma = true;
}
if (timeDifference.toMinutes() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.toMinutes() == 1) timeDifferenceAsPrettyString += timeDifference.toMinutes() + " minute";
else timeDifferenceAsPrettyString += timeDifference.toMinutes() % 60 + " minutes";
putComma = true;
}
if (timeDifference.getSeconds() > 0) {
if (putComma) timeDifferenceAsPrettyString += ", ";
if (timeDifference.getSeconds() == 1) timeDifferenceAsPrettyString += timeDifference.getSeconds() + " second";
else timeDifferenceAsPrettyString += timeDifference.getSeconds() % 60 + " seconds";
}
timeDifferenceAsPrettyString += " ago";
return timeDifferenceAsPrettyString;
}
This function works as expected but is it really necessary to do it like this? Perhaps there is a better way to achieve this?
I'm using Java 8.
How about this?
static String getTimeBetween(ZonedDateTime from, ZonedDateTime to) {
StringBuilder builder = new StringBuilder();
long epochA = from.toEpochSecond(), epochB = to.toEpochSecond();
long secs = Math.abs(epochB - epochA);
if (secs == 0) return "now";
Map<String, Integer> units = new LinkedHashMap<>();
units.put("day", 86400);
units.put("hour", 3600);
units.put("minute", 60);
units.put("second", 1);
boolean separator = false;
for (Map.Entry<String, Integer> unit : units.entrySet()) {
if (secs >= unit.getValue()) {
long count = secs / unit.getValue();
if (separator) builder.append(", ");
builder.append(count).append(' ').append(unit.getKey());
if (count != 1) builder.append('s');
secs %= unit.getValue();
separator = true;
}
}
return builder.append(epochA > epochB ? " ago" : " in the future").toString();
}
You could probably store the LinkedHashMap instead of instantiating it every method call, but this should work.

How do I get the military time difference to read correctly?

I am trying to write a program in which the console tells a person the difference between two times WITHOUT IF STATEMENTS, in "military time" or 24 hr time. So far, I have:
import java.util.Scanner;
public class MilTimeDiff {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
int t1 = Integer.parseInt(tm1);
int t2 = Integer.parseInt(tm2);
int difference = t2 - t1;
while (t1 < t2) {
String tmDif = Integer.toString(difference);
System.out.println("The difference between times is " + tmDif.substring(0, 1) + " hours " +
tmDif.substring(1) + " minutes.");
break;
}
}
}
But I have two issues: one: if I make time one 0800, and time two 1700, it gives me the correct 9 hours. But if the difference is 10 hours or more, it gives 1 hour and a lot of minutes. I thought using the String.format method would help, but it doesn't do anything.
two: I'm not sure how to approach a situation where time 1 is later than time 2.
Thanks!
You can try below code which will give Time difference in military format :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
String hrs1 = time1.substring(0, 2);
String min1 = time1.substring(2, 4);
String hrs2 = time2.substring(0, 2);
String min2 = time2.substring(2, 4);
// int difference = t2 - t1;
if (Integer.parseInt(time1) < Integer.parseInt(time2)) {
int minDiff = Integer.parseInt(min2) - Integer.parseInt(min1);
int hrsDiff = Integer.parseInt(hrs2) - Integer.parseInt(hrs1);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
} else {
int minDiff = Integer.parseInt(min1) - Integer.parseInt(min2);
int hrsDiff = Integer.parseInt(hrs1) - Integer.parseInt(hrs2);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
}
}

Skip some Value while looping

I'm trying to make a code which counting pages as the user set, the problem is the ListView is skipping some of the row !!
I tried the code alone as a java code and it's work well !!
Here's the code:
public void CollectThePages(int Num1,int Num2){
int startpage = Num1;
int endpage = Num2;
int Number = startpage;
int Day = 1;
int DailyPages = 9;
while(Number >= startpage){
HashMap<String,String> data = new HashMap<>();
if(Number == startpage){
System.out.println("Day Number " + Day);
data.put("day", "Day " + Day);
Day ++;
System.out.print("From " + Number);
data.put("from","From " + Number);
Number += DailyPages;
int NumberofPages = DailyPages + 1;
System.out.print(" To "+Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + NumberofPages);
data.put("NOP",NumberofPages + " Pages");
}
if(Number >= startpage){
Number +=1;
System.out.println("Day Number " + Day);
data.put("day", "Day " + Day);
Day ++;
System.out.print("From "+Number);
data.put("from", "From " + Number);
Number += DailyPages;
int NumberofPages = DailyPages + 1;
System.out.print(" To "+Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + NumberofPages);
data.put("NOP", NumberofPages + " Pages");
}
if(Number > endpage | (Number + DailyPages) > endpage){
Number +=1;
System.out.println("Day Number " + Day);
data.put("day","Day " + Day);
Day ++;
System.out.print("From " + Number);
data.put("from","From " + Number);
int value = endpage - Number;
Number += value;
System.out.print(" To " + Number);
data.put("to", "To " + Number);
System.out.println(" | The Pages are " + (value + 1));
data.put("NOP",value + " Pages");
}
if(Number == endpage | (Number + 1) == endpage){
Number = 0;
}
valueList.add(data);
}
ValueList = (ListView) findViewById(R.id.valueList);
//Out of The Loop
valueListAdapter = new ValueListAdapter(getApplicationContext(),valueList);
ValueList.setAdapter(valueListAdapter);
}
And Here's the result (First page is 1, Last is 55) - Skipped the 1st day and 5th day
#Shree Krishna correctly pointed out your mistake and should fix your code accordingly. You can use following as well :-
public void CollectThePages(int Num1,int Num2){
int startpage = Num1;
int endpage = Num2;
int Number = startpage;
int Day = 1;
int DailyPages = 9;
while(Number <= endpage){
HashMap<String,String> data = new HashMap<>();
System.out.print("Day Number " + Day);
data.put("day", "Day " + Day);
++Day;
System.out.print("From " + Number);
data.put("from", "From " + Number);
int prevNumber = Number;
Number += DailyPages;
Number = Number > endpage ? endpage : Number;
int NumberofPages = Number - prevNumber + 1;
System.out.print(" To " + Number);
data.put("to", "To " + Number);
System.out.print(" | The Pages are " + NumberofPages);
data.put("NOP", NumberofPages + " Pages");
++Number;
valueList.add(data);
}
ValueList = (ListView) findViewById(R.id.valueList);
//Out of The Loop
valueListAdapter = new ValueListAdapter(getApplicationContext(),valueList);
ValueList.setAdapter(valueListAdapter);
}
As your logic in codes, Simply lets take an example if
Num1 = 1
Your condition will be
if(Number == startpage) ---> if(1 == 1) //Condition satisfied
Then what happened is Day is increased by 1 and added to variable data.
Another condition in the same loop
if(Number >= startpage) ---> if(10 >= 1) //Again Condition satisfied
Then again Day is increased by 1
Conclusion
Your every data is being shown with +1 added.
To prevent this
Check your every if condition and make them all unique, Don't make it repetitive in the same condition, OR change the value of startpage too in each condition if it doesn't violate your logic in future.

Two die simulator do-while-if-else-if error

This is the assignment that was give to me. But I can't seem to understand what is wrong with my program and how to go about fixing it. It just keeps rolling dice non-stop and freezes my JCreator. I even tried changing the NUMBER value to 10 and it still does the same thing.
I have declared all the variables. You need to add code to simulate rolling the
dice and keeping track of the doubles. Convert the algorithm below to Java and
place it in the main method after the variable declarations, but before the output
statements. You will be using several control structures: a while loop and an if-else-
if statement nested inside another if statement. Use the indenting of the
algorithm to help you decide what is included in the loop, what is included in the
if statement, and what is included in the nested if-else-if statement.
To “roll” the dice, use the nextInt method of the random number generator to
generate an integer from 1 to 6.
You are not using a doop loop correctly. You have a do-loop and while loop, not a single do-loop. In the do-loop count never increases so the loop will never end. A do loop performs the first iteration before evaluating whether to continue.
import java.util.Random;
public class DiceSimulation
{
public static void main(String[] args)
{
final int NUMBER = 10000;
Random generator = new Random();
int die1Value;
int die2Value;
int count = 0;
int snakeEyes = 0;
int twos = 0;
int threes = 0;
int fours = 0;
int fives = 0;
int sixes = 0;
do{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
if (die1Value == die2Value)
{
if(die1Value == 1)
{
snakeEyes++;
}
else if (die1Value == 2)
{
twos++;
}
else if (die1Value == 3)
{
threes++;
}
else if (die1Value == 4)
{
fours++;
}
else if (die1Value == 5)
{
fives++;
}
else if (die1Value == 6)
{
sixes++;
}
}
count++;
}while (count < NUMBER);
System.out.println ("You rolled snake eyes " + snakeEyes +
" out of " + count + " rolls.");
System.out.println ("You rolled double twos " + twos +
" out of " + count + " rolls.");
System.out.println ("You rolled double threes " + threes +
" out of " + count + " rolls.");
System.out.println ("You rolled double fours " + fours +
" out of " + count + " rolls.");
System.out.println ("You rolled double fives " + fives +
" out of " + count + " rolls.");
System.out.println ("You rolled double sixes " + sixes +
" out of " + count + " rolls.");
}
}
I think you understood the do-while concept wrong.
The "do {...}" part (where you roll the dice) gets executed as long as the expression inside the while brackets is true.
Move the whole "if (die1Value == die2Value)" part (up to the "counter++;" line) into the do braces, and it should run.
do
{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
}
while (count <= NUMBER);
That first keyword do is taking the while to loop the whole block forever since the count variable is only incremented on the next block.
My advice is to remove the do:
//do
//{
die1Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die1Value);
die2Value = generator.nextInt(6) + 1;
System.out.println("You rolled: " + die2Value);
//}
while (count <= NUMBER)
{
...
}
Since you already have a block after the while.

Categories