Using a Ternary Operator to a "0" within the statement - java

I'm trying to format a time using a variable input. If a user enter an hour as 1 - 9 the out put would include a "0", and the same for minutes. So far if a user enters 1 hour 3 minutes the output reads 1:3 instead of 01:03.
How do I get the extra 0 in front of numbers less than 10.
Here's the code.....
import java.util.Scanner;
public class FormatTime {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int MinutesInput;
int HoursInput;
int Hours;
int Minutes;
{
System.out.println("Enter hours between 1 and 24");
Hours = input.nextInt();
System.out.println("Enter minutes between 1 and 59");
Minutes = input.nextInt();
{
**//THIS NEXT LINE IS THE PROBLEM**
HoursInput = Hours < 10 ? "0" + Hours : Hours;
System.out.print(HoursInput + ":");
}
{
**//THIS NEXT LINE IS THE PROBLEM**
MinutesInput = (Minutes < 10) ? "0" + Minutes : (Minutes);
System.out.print(MinutesInput);
}
System.out.println();
}
}
}

How do I get the extra 0 in front of numbers less than 10.
You don't, while the target variable is of type int. An int is just a number, not a string - whereas "0" + Hours is a string.
int values don't contain any sort of string representation - the number sixteen is just as much "0x10" or "0b10000" as it is "16"... or even "00016" if your decimal representation allows much digits. ("00016" may be mis-interpreted as fourteen, however, if it's parsed as an octal string...)
Use DecimalFormat to convert numbers into strings in your desired format, or String.format, or possibly just PrintStream.printf if you want to write it straight to the console.
I'd also strongly recommend that you use camelCase for your local variables, and only declare them when you first need them.

Perhaps you should be using
System.out.printf("%02d:%02d%n", Hours, Minutes);

You are confusing int and String types:
int HoursInput;
//...
HoursInput = Hours < 10 ? "0" + Hours : Hours;
There are two problems with your code: you are trying to store string "07" (or similar) in an int. Secondly even if it was possible, 07 is equivalent to 7 as far as integer types are concerned (well, leading 0 has a special octal meaning, but that's not the point).
Try this instead:
String hoursInput;
//...
hoursInput = Hours < 10 ? "0" + Hours : "" + Hours;

you must use String variables or use format method (similar to sprintf from c) from String class.
String time = String.format("%02d:%02d", hours, minutes );

Related

Java int formating?

I want the user to input hours and minutes for a Local.Time from 00 to 23 and from 00 to 59, I scanned this as an int. It works but for values from 00 to 09 the int ignores the 0 and places then as a 0,1,2...9 instead of 00,01,02,03...09; this breaks the Local.Time since, for example "10:3"; is not a valid format for time.
I have read I can format this as a String, but I don't think that helps me since I need an int value to build the LocalTime and subsequent opperations with it.
There is a way of formatting this while kepping the variable as an int??
Can I code this differently to bypass this??
Am I wrong about how these classes work??
I am pretty new to these concepts
Here is the code I am using
int hours;
int minutes;
System.out.println("Input a number for the hours (00-23): ");
hours = scan.nextInt();
System.out.println("Input a number for the minutes (00-59): ");
minutes = scan.nextInt();
LocalTime result = LocalTime.parse(hours + ":" + minutes);
I tried using the NumberFormat class but it returns an error when trying to declare its variables (something like it is an abstract variable and cannot be instanced)
I also tried using the String format but I don't really know what to do with that string after that, it asks me for a int and not a string to build this method
First: an int doesn't differentiate between 09 and 9. They are the same value: the number nine.
Next: if you already have numbers, then going back to a string to produce a date is an anti-pattern: you are losing type checking by this. So instead of using LocalTime.parse and constructing the input from int values, you should simply use LocalTime.of(hours, minutes):
LocalTime result = LocalTime.of(hours, minutes);
tl;dr Use LocalTime.of(hours, minutes), it's most straight-forward
Alternative: Parse with a suitable DateTimeFormatter:
public static void main(String[] args) {
// single-digit example values
int hours = 9;
int minutes = 1;
// define a formatter that parses single-digit hours and minutes
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m");
// use it as second argument in LocalTime.parse
LocalTime result = LocalTime.parse(hours + ":" + minutes, dtf);
// see the result
System.out.println(result);
}
Output:
09:01
Fix
use the proper DateTimeFormatter
LocalTime.parse(hours + ":" + minutes, DateTimeFormatter.ofPattern("H:m"));
Build the expected default format
LocalTime.parse(String.format("%02d:%02d", hours, minutes));
Improve
Use a more appropriate method
LocalTime.of(hours, minutes);

How to use second and third value of split if first value is not present?

I'm trying to create a java class to get the amount of seconds from an HH:mm:ss duration to use in some math and it works. The only problem is, if the user only has minutes and seconds, they wouldn't think to put in, for example, 0:3:42, but they would instead put 3:42.
Here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int seconds = 0;
System.out.println("Enter time in HH:mm:ss to convert into seconds:");
String standardTime = scan.nextLine();
scan.close();
String[] split = standardTime.split(":"); {
seconds += Integer.parseInt(split[0]) * 3600;
seconds += Integer.parseInt(split[1]) * 60;
seconds += Integer.parseInt(split[2]);
}
System.out.println(seconds);
}
}
I want to be able to use [1] and [2] instead of [0] and [1] if the format is in mm:ss instead of HH:mm:ss.
If the input is mm:ss and you call split with ":" as a delimiter, it would essentially create an array with two values - the 'mm' and the 'ss'.
Hence, to read from that array, you should use indices 0 and 1. There's no way to get index 2 from an array with two values (without getting ArrayIndexOutOfBoundsException).
Instead, you may check the size of that array once created. If it is 2, then you know you have only minutes and seconds and do the calculation you want to.
You could refer to the indexes from the end of the array instead of the beginning of an array, and assume the value is 0 if the array is too small:
seconds += split.length == 3 ? Integer.parseInt(split[0])*3600 : 0;
seconds += Integer.parseInt(split[split.length - 2])*60;
seconds += Integer.parseInt(split[split.length - 1]);

Is there a way to modify the format of a user input (ex:900 -> 9h00)?

I'm currently working with a school-made class that allow the reading of a user input.
Here is my currently code which ask the hour, then the minutes for a car reservation because I need to give the final hour in the format HHhMM:
public class Facturation {
public static void main (String [] args) {
while (true) {
System.out.println(MSG1);
System.out.println (MSG_SOLLICITATION1);
while (true ) {
HrDebut= Clavier.lireInt();
if (HrDebut >= 9 && HrDebut <= 18 ) {
break;
} else {
System.out.println (MSG_ERREUR);
System.out.println (MSG_SOLLICITATION1);
} }
System.out.println (MSG_SOLLICITATION2);
while (true) {
MinDebut=Clavier.lireInt();
if (MinDebut >= 00 && MinDebut <= 59 ){
System.out.println("CONFIRMATION:" + "\n"
+ "Debut de la location:" + HrDebut + "h" + MinDebut
+ "\n" + "\n" + MSG_RTR_MENU) ;
Clavier.lireFinLigne();
break;
So if the user give 9+34, the final output would be: 9h34.
Is there a way to only have the user input 1 number from 900 to 1800 (9am to 18PM) and then give a final output in the format HHhMM?
For example, user input 945 -> final output is 9h45.
Thanks.
java.time
Java has a built-in class representing a time of day, LocalTime, and facilities for parsing a string into a LocalTime and formatting it back into a string. So yes, reading the time as 934 or 1800 goes nicely, and there’s no reason to hand format the way you did in the question.
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("Hmm");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("H'h'mm");
LocalTime minTime = LocalTime.of(9, 0);
LocalTime maxTime = LocalTime.of(18, 0);
String userInput = "1800";
LocalTime time = LocalTime.parse(userInput, inputFormatter);
if (time.isBefore(minTime) || time.isAfter(maxTime)) {
System.out.println("TODO put your error message here");
} else {
String output = time.format(outputFormatter);
System.out.println("Debut de la location: " + output);
}
Output from the example code snippet is:
Debut de la location: 18h00
One detail may surprise here: The input format pattern string Hmm would ordinarily mean input in three digits, one digit hour of day and two digit minute of the hour. However, when Java sees that there are four digits, not three, since it knows that hour of day may sometimes require two digits, it is smart enough to figure that 1800 is two-digit hour, 18, and two-digit minute, 00.
In the output format pattern, H'h'mm, the single quotes around the h means that this letter is to be printed literally, it is not a format pattern letter like H and mm.
If you can, I recommend that you read the input as a String, not an int.
If the user has typed a time that doesn’t conform with the exptected, for instance a wrong format or a minute of hour greater than 59, LocalTime.parse will throw a DateTimeParseException, so you will want to catch this exception, issue an error message and ask the user to try again.
Link: Oracle tutorial: Date Time explaining how to use java.time.
1 - Use scanner class for user input.
Scanner scan= new Scanner(System.in);
2 - ask user to input time in your desired format like 945 or 1230.
3 - then use below method logic in your code to get hour and minute.
public static void t() {
int a = 1945;//suppose your time
int minute = a%100; // your minute data
System.out.println(minute);
int hour = a/100;// your hour data
System.out.println(hour);
}
In this code we have not taken care of wrong input. so if you are not sure that user will always provide correct data, Please implement logic for data corrections check.(like number can not be less than 3 digit or more than 4 digit. time range is 100 to 2400).
If its 1 o'clock - user need to enter 100.

Char of string outputting incorrectly

This is my program and what I am trying to achieve is taking the char value in string amount1 at position 1 i.e for example amount1=$3.00 amount2=2. However it doesn't print out what I expected, 2.
System.out.print("$"+cost[0]+".00 remains to be paid. Enter coin or note: ");
String amount1 = keyboard.nextLine();
char amount2 = amount1.charAt(1);
String amountcheck = "$"+cost[0]+".00";
int [] remainder = new int[1];
if (amount1.equals(amountcheck)) {
System.out.println("Perfect! No change given."); }
if (amount2 < cost[0]) {
remainder[0] = cost[0] - amount2; }
System.out.println("Remainder = "+remainder[0]);
System.out.println(+amount2);
For example,
$3.00 remains to be paid. Enter coin or note: $2.00
Remainder = 0
50
The problem is both in lines 2 and 3. Firstly 3, It don't understand why it outputs 50 as char at amount1 index 1. If i'm not wrong don't char positions work similarly off array index systems. Secondly line 3, the if statement in lines of 8 and 9 of my original code don't seem to catch that amount 2 < cost[0] and don't do the following operations.
So what I expected to happen when I am taking char at position 1 of "$2.00" is newamount would be equal to 2 instead of 50 which the program is outputting.
I've tried changing the char positions but all this seems to do is decrement the value.
You set your amount2 as a char and when you print it, it translates to the ASCII number of that charater which for the charater '2' is 50.
If you want to output 2 you should change your amount2 to type intand parse the char to integer like this Integer.parseInt(""+amount1.charAt(1)); in line 3.
You are using a char to store a numeric value, but that value is a character, not a number. Meaning you are storing '2' which is actually 50 in ASCII. You should remove the value of 48 to get the correct value ('0') or parse the String into a number directly with Integer.parseInt(String).
But as I said in comment, this is easy to correct so I will not provide much more code to this.
But let's be honnest, your logic is risky from the beginning.
You are asking the user to input an amount in a specific format : "$#.00". If the number is two digit $##.00 it fails, if he add a space or don't put the $ or any mistake that users are professional to find, it fails.
First, you should simplified this, do you need the $ ? Ask for dollar currency if you want to specifiy it.
Then, do you need decimals ? Let first assume you don't (see Note for decimal hint).
You just need to input an integer value through the Scanner, which provide method to get Integer -> Scanner.nextInt()
int ammountReceived = keyboard.nextInt();
Then you need to see if this is
Equals
Too much
Not enough
Like this :
int remainder = amountToPay - amountReceived;
if(remainder == 0){
//equals
} else if(remainder > 0){
//not enough
} else {
//too much
}
This would give a simpler solution of :
Scanner sc = new Scanner(System.in);
System.out.print("Amount to pay : $");
int amountToPay = sc.nextInt();
System.out.print("Amount received : $");
int amountReceived = sc.nextInt();
int remainder = amountToPay - amountReceived;
if (remainder == 0) {
System.out.println("That perfect, thanks.");
} else if (remainder > 0) {
System.out.println("Remaining : $" + remainder);
} else {
System.out.println("Need to give back : $" + -remainder);
}
sc.close();
Yours and mine are close, but you will see this is more readable and focused on the problem, I don't play with char to get from a specific String pattern, I am focused on the problem -> to get paid ;)
Now, you have to add a loop here to ask again until you received the correct amount. But please, don't read a numerical String character by character...
Note :
Scanner.nextInt throws exception if the format is incorrect (not an integer)
You can easily adapt this to get double, float or better BigDecimal

Calculate difference between two hour's strings

I have a string that contain certain hour ex. 14:34, and now I want to calculate the difference between the current hour ex. 21:36-14:34=7 hours 2 minutes (or something like that.) Can someone explain me how can I do that?
It's very easy: You need to separate the string in terms you can add or substract:
String timeString1="12:34";
String timeString2="06:31";
String[] fractions1=timeString1.split(":");
String[] fractions2=timeString2.split(":");
Integer hours1=Integer.parseInt(fractions1[0]);
Integer hours2=Integer.parseInt(fractions2[0]);
Integer minutes1=Integer.parseInt(fractions1[1]);
Integer minutes2=Integer.parseInt(fractions2[1]);
int hourDiff=hours1-hours2;
int minutesDiff=minutes1-minutes2;
if (minutesDiff < 0) {
minutesDiff = 60 + minutesDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff ;
}
System.out.println("There are " + hourDiff + " and " + minutesDiff + " of difference");
UPDATE:
I'm rereading my answer and I'm surprised is not downvoted. My fault. I wrote it without any IDE check. So, the answer should be minutes1 and 2 for the minutesDiff and obviously and a check to carry the hour difference if the rest of minutes is negative, making minutes (60+minutesDiff). If minutes is negative, rest another hour to the hourDiff. If hours become negative too, make it (24+hourDiff). Now is fixed.
For the sake of fastness, I'm using a custom function. For the sake of scalability, read Nikola Despotoski answer and complete it with this:
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.println(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
I would start by using the .split method to get the string into its two components (minutes and hours) then I would convert both times into minutes by mutliplying the hours by 60 and then adding the minutes
String s = "14:34";
String[] sArr = s.split(",");
int time = Integer.parseInt(sArr[0]);
time *= 60;
int time2 = Integer.parseInt(sArr[1]);
time = time + time2;
do this for both strings and then subtract one from the other. You can convert back to normal time by using something like this
int hours = 60/time;
int minutes = 60%time;
The answer labeled as correct will not work. It does not account for if the first time is for example 3:17 and the second is 2:25. You end up with 1 hour and -8 minutes!

Categories

Resources