Code crashing after using formatting - java

I'm new to the Java language (Just started about 2 weeks ago)
Basically, the user enters their year/month/day they were born on in order and I use this information to perform a math calculation that will show their age.
I need numbers from 0-9 to be taken in as 01, 02, 03... So, I searched around and found that I can use Decimal.Format and then print out the format later on.
My code crashes whenever it reaches the println(twodigits.format) part no mater where I put it. There are no errors displayed that I need to address.
Why is it doing this and is there a better way to do this? I need it to be 2 digits at all times or the calculation won't work.
Here's a part of my code, I can provide more if needed.
DecimalFormat twodigits = new DecimalFormat("00");
System.out.println("Calculating...");
Integer CurrentDate2 = Integer.valueOf(CurrentDate);
Integer BirthDate2 = Integer.valueOf(BirthDate);
int a = CurrentDate2.intValue();
int b = BirthDate2.intValue();
int age = (a - b) / 1000;
Thread.sleep(300);
System.out.println(".");
Thread.sleep(300);
System.out.println(".");
Thread.sleep(300);
System.out.println(".");
System.out.println(twodigits.format(CurrentDate));
System.out.println(twodigits.format(BirthDate));
Any help is appreciated!

What types are "CurrentDate" and "BirthDate" because it's not clear from your code? You first use them to set "CurrentDate2" and "BirthDate2". And then you use them in the println().
If I were to guess, I'd say they are of type 'String', and 'twodigits.format()' can't handle Strings, which is why it's crashing.

This takes two dates and split time on "/". It then prints them out in the format that you want.
DecimalFormat twodigits = new DecimalFormat("00");
System.out.println("Calculating...");
String CurrentDate = "01/02/2007";
String BirthDate = "02/03/2007";
String[] currentDateParts = CurrentDate.split("/");
String[] birthDateParts = BirthDate.split("/");
int cdp0 = Integer.parseInt(currentDateParts[0]);
int cdp1 = Integer.parseInt(currentDateParts[1]);
int cdp2 = Integer.parseInt(currentDateParts[2]);
int bdp0 = Integer.parseInt(birthDateParts[0]);
int bdp1 = Integer.parseInt(birthDateParts[1]);
int bdp2 = Integer.parseInt(birthDateParts[2]);
//do your calculations
System.out.println(twodigits.format(cdp0));
System.out.println(twodigits.format(cdp1));
System.out.println(twodigits.format(cdp2));
System.out.println(twodigits.format(bdp0));
System.out.println(twodigits.format(bdp1));
System.out.println(twodigits.format(bdp2));

Related

Comparing values obtained from combo box to another string fails even though both appear to be the same

I am trying to obtain a date from 3 separate combo boxes that I then convert to ints and make a Date object. However, when I compare this date string to an already existing string, it doesnt match even though in the debugger it appears to be the same. I have setup a simple if statement to check what the problem is however I am not sure why it does not match.
int apptDay, apptMonth, apptYear;
apptDay = Integer.parseInt(consultationDay.getSelectedItem().toString());
apptMonth = Integer.parseInt(consultationMonth.getSelectedItem().toString());
apptYear = Integer.parseInt(consultationYear.getSelectedItem().toString());
consultationDate = new Date(apptDay, apptMonth, apptYear);
if (appointmentList.get(0).getDate() == consultationDate) {
sopl("Working");
}
I am quite sure that there is some issue with my code related to combo boxes as that is the only place where I face problems. The if statement is never satisfied so "Working" is never printed.
Any help would be appreciated.
You should use .equlas() instead of the == operator.
int apptDay = 5, apptMonth = 12, apptYear = 2000;
Date testDate = new Date(apptDay, apptMonth, apptYear);
Date consultationDate = new Date(apptDay, apptMonth, apptYear);
if (testDate == consultationDate) {
System.out.println("Success for ==");
} else if (testDate.equals(consultationDate)) {
System.out.println("Success for equals");
}

Add float to Java Calendar

I'm currently developing some functionality that needs to either subtract or add time to a Calendar class instance. The time I need to add/sub is in a properties file and could be any of these formats:
30,sec
90,sec
1.5,min
2,day
2.333,day
Let's assume addition for simplicity. I would read those values in a String array:
String[] propertyValues = "30,sec".split(",");
I would read the second value in that comma-separated pair, and map that to the relevant int in the Calendar class (so for example, "sec" becomes Calendar.SECOND, "min" becomes Calendar.MINUTE):
int calendarMajorModifier = mapToCalendarClassIntValues(propertyValues[1]);
To then do the actual operation I would do it as simple as:
cal.add(calendarMajorModifier, Integer.parseInt(propertyValues[0]));
This works and it's not overly complicated. The issue is now floating values (so 2.333,day for eaxmple) - how would you deal with it?
String[] propertyValues = "2.333,day".split(",");
As you can imagine the code becomes quite hairy (I haven't actually written it yet, so please ignore syntax mistakes)
float timeComponent = Float.parseFloat(propertyValues[0]);
if (calendarMajorModifier == Calendar.DATE) {
int dayValue = Integer.parseFloat(timeComponent);
cal.add(calendarMajorModifier, dayValue);
timeComponent = (timeComponent - dayValue) * 24; //Need to convert a fraction of a day to hours
if (timeComponent != 0) {
calendarMajorModifier = Calendar.HOUR;
}
}
if (calendarMajorModifier == Calendar.HOUR) {
int hourValue = Integer.parseFloat(timeComponent);
cal.add(calendarMajorModifier, hourValue);
timeComponent = (timeComponent - hourValue) * 60; //Need to convert a fraction of an hour to minutes
if (timeComponent != 0) {
calendarMajorModifier = Calendar.MINUTE;
}
}
... etc
Granted, I can see how there may be a refactoring opportunity, but still seems like a very brute-forceish solution.
I am using the Calendar class to do the operations on but could technically be any class. As long as I can convert between them (i.e. by getting the long value and using that), as the function needs to return a Calendar class. Ideally the class also has to be Java native to avoid third party licensing issues :).
Side note: I suggested changing the format to something like yy:MM:ww:dd:hh:mm:ss to avoid floating values but that didn't pan out. I also suggested something like 2,day,5,hour, but again, ideally needs to be format above.
I'd transform the value into the smallest unit and add that:
float timeComponent = Float.parseFloat(propertyValues[0]);
int unitFactor = mapUnitToFactor(propertyValues[1]);
cal.add(Calendar.SECOND, (int)(timeComponent * unitFactor));
and mapUnitToFactor would be something like:
int mapUnitToFactor(String unit)
{
if ("sec".equals(unit))
return 1;
if ("min".equals(unit))
return 60;
if ("hour".equals(unit))
return 3600;
if ("day".equals(unit))
return 24*3600;
throw new InvalidParameterException("Unknown unit: " + unit);
}
So for example 2.333 days would be turned into 201571 seconds.

How to convert double values to string in a text field

I want to do the average of 9 textfields and also the sum of them and place them in 2 other textfields by using a button, currently this code doesnt displays anything in the other textfiels. If i put anything, for example "A" instead of "%.Of" it would display the "A" in the textfield but not the average or the sum. Please i need help with a code that would work, dont mind if i need to change a lot.
This is what im working with:
private void jButton_RankingActionPerformed(java.awt.event.ActionEvent evt) {
double R[] = new double [14];
R[0] = Double.parseDouble(jTextField_Math.getText());
R[1]= Double.parseDouble(jTextField_English.getText());
R[2] = Double.parseDouble(jTextField_Spanish.getText());
R[3] = Double.parseDouble(jTextField_Biology.getText());
R[4] = Double.parseDouble(jTextField_Physics.getText());
R[5] = Double.parseDouble(jTextField_Chemestry.getText());
R[6] = Double.parseDouble(jTextField_PE.getText());
R[7] = Double.parseDouble(jTextField_Humanities.getText());
R[8] = Double.parseDouble(jTextField_Technology.getText());
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
String Average = String.format("%.Of",R[9]);
jTextField_Average.setText(Average);
String TotalScore = String.format("%.Of",R[10]);
jTextField_TotalScore.setText(TotalScore);
if(R[10]>=50)
{
jTextField_Ranking.setText("Superior");
}
else if (R[10]>=41){
jTextField_Ranking.setText("Alto");
}
else if (R[10]>=34){
jTextField_Ranking.setText("Basico");
}
else if (R[10]<=33){
jTextField_Ranking.setText("Bajo");
Since you mentioned that an A would print, it follows that jButton_RankingActionPerformed is being called. The issue you have is the format string you are using to print the total and average. You have mistakenly chosen the capital letter O rather than the number zero.
Replace this (which contains a capital letter O):
String.format("%.Of",R[9]);
With
1) No decimal will be printed: i.e. 50.2 would be 50
String.format("%.0f",R[9]);
2) Or perhaps you want to see one decimal place like 50.2
String.format("%.1f",R[9]);
Also a very small optimization is:
R[9] = (R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8])/ 9;
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
Could be replaced with:
R[10] = R[0]+R[1]+R[2]+R[3]+R[4]+R[5]+R[6]+R[7]+R[8];
R[9] = R[10] / 9;
or use a loop to calculate R[10]. (to add R[0] to R[8])

Write a monitoring tool with selenium+java

Good day!
I have an idea about using selenium as short-time monitoring tool. For example, need to check for an two-three hours about some table values changing.
I've got in mind a cycle "while", where i set up timer how long need to monitor values, and then print them for easy compare.
2016.04.26 | 160789 186491 0.76% 05:28:56
2016.04.26 | 160789 186491 0.76% 05:30:56
But I think there is better, smart solution. But i can't figure out how.
open(projectUrl);
int timer = 120;
int i = 1;
int iterations = 50;
String var1 = $("cssSelector1").getText();
while (i<iterations) {
open(projectUrl);
var1 = $("cssSelector1").getText();
if (!$("cssSelector1").getText().equals(var1)) {
System.out.print(
var1+" | "+
$("cssSelector2").getText()+" "+
$("cssSelector3").getText()+" "+
$("cssSelector4").getText()+" ");
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
System.out.println(ft.format(dNow));
}
sleep(timer*1000);
i++;
}
Now it's done, and works like I want. When var1 changes, update var1, then write value. And cycling again. Upper code works fine.
var1..4 need to be set within the while loop or they'll just keep printing the same data through each iteration
Now it's done, and works like I want. When var1 changes, update var1, then write value. And cycling again. Upper code works fine.

Removing the .0 from a double

I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0
example: display 5.5 as 5.5 and 5.0 as 5
This is what I have so far: (answer is a double)
double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);
this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
The DecimalFormat suggestions are the easiest way to handle this. If they aren't sufficient, here's another idea.
If you're starting to hit the maximum values that can be represented by primitives in Java, then you may need to move to BigInteger and BigDecimal.
Try playing around with the BigDecimal.toBigInteger() method coupled with the toString() methods on BigDecimal and BigInteger.
It's not good solution
if you use new DecimalFormat("0.#") you are missing data, for example
PI = 3.14, but after parse you ae geting 3.1
Another solution to use eval%1 ? (int)d : d
this time couse max integer limit , again missing data
my solution is working, but it's not good idea
res = removeLastChars(eval,".0");
private String removeLastChars(double eval, String text){
String res = String.valueOf(eval);
int length = text.length();
if (res.length() > length){
res = res.substring((res.length() - length), res.length()).equals(text)
? res.substring(0, (res.length() - length)) : res;
}
return res;
}
Look at
http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
you would want just DecimalFormat("0.0")

Categories