I am working on a school project and I'm having a dickens of a time trying to get the JButton to do..well.. anything! this is my code, I don't know how important the other .java files are.
I started with a simple code that worked but after adding and editing it can't seem to update the text exactly how I want it.
<removed>
var1, var2, etc. that are being passed in are stored as such..
they are all in another .java file
the Function.fun
<removed>
Okay...
Don't rely on static, it's not going to help you and will create a whole lot of new issues which will be difficult to solve
The main problem is, your code is generating a NumberFormatException - java.lang.NumberFormatException: For input string: "javax.swing.JSpinner[,8,6,109x26,invalid,layout=com.apple.laf.AquaSpinnerUI$SpinnerLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=]"
So, based on the exception, it's obvious that Double.parseDouble isn't getting the value it excpects
So, having a deeper look at your code...
if (jspValue1.getValue() instanceof Double) {
s = jspValue1.toString();
d = Double.parseDouble(s);
return d;
} else {
return 0.00;
}
You're passing the result of jspValue.toString to Double.parseDouble, but he fact is, it's just not required.
You've already determined that the value from the JSpinner is a double, so you on;y need to cast it...
double value = 0.00d;
if (jspValue1.getValue() instanceof Double) {
value = (Double)jspValue1.getValue();
}
return value;
Related
I am working on a program which uses jLabels and I need to check if label is empty or not. If it's empty it should just pop up a note that it's empty and nothing else, but it actually throws a lot of errors. I'm using label.getText().isEmpty().
Here's the code:
if(Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||najboljsi1.getText().isEmpty()||
Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najboljsi2.getText().isEmpty()||
Integer.parseInt(najboljsi3.getText())<1||Integer.parseInt(najboljsi3.getText())>17||najboljsi3.getText().isEmpty()||
Integer.parseInt(najslabsi1.getText())<1||Integer.parseInt(najslabsi1.getText())>17||najslabsi1.getText().isEmpty()||
Integer.parseInt(najslabsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||najslabsi2.getText().isEmpty()||
Integer.parseInt(najslabsi3.getText())<1||Integer.parseInt(najslabsi3.getText())>17||najslabsi3.getText().isEmpty())
{
jLabel101.setForeground(Color.red);
jLabel101.setText("Eno ali več vnesenih števil ni v pravilnem obsegu (1-16)!");
}
else
{
jLabel101.setText("");
int a=Integer.parseInt(najboljsi1.getText());
tabela[a-1]+=3;
int b=Integer.parseInt(najboljsi2.getText());
tabela[b-1]+=2;
int c=Integer.parseInt(najboljsi3.getText());
tabela[c-1]+=1;
int d=Integer.parseInt(najslabsi1.getText());
tabela[d-1]-=3;
int e=Integer.parseInt(najslabsi2.getText());
tabela[e-1]-=2;
int f=Integer.parseInt(najslabsi3.getText());
tabela[f-1]-=1;
najboljsi1.setText("");
najboljsi2.setText("");
najboljsi3.setText("");
najslabsi1.setText("");
najslabsi2.setText("");
najslabsi3.setText("");
count++;
jLabel1.setText("Učenec "+count);
}
Everything else in if statement works ok, if value is lower than 1 or higher than 16, it throws a pop up.
Yes, you must test najboljsi1.getText().isEmpty() BEFORE any parsing of najboljsi1.getText().
Your if would become:
if(najboljsi1.getText().isEmpty()||Integer.parseInt(najboljsi1.getText())<1||Integer.parseInt(najboljsi1.getText())>17||
najboljsi2.getText().isEmpty()||Integer.parseInt(najboljsi2.getText())<1||Integer.parseInt(najboljsi2.getText())>17||
etc...
If you do Integer.parseInt(najboljsi2.getText()) on a label with the textn "" (empty String), it won't be an integer. An exception will be thrown.
I think your problem is in the use of the "Integer.parseInt" without any check! If, for example, the variable contains an empty string, it will throw an Exception and your if clause will never work!
I would manage the situation with a double check.
Check if it is already a number (this guide could help
check-if-variable-is-a-number-in-javascript)
Then, if it is a string, check if it is empty and if it actually contains a string (the following post could also help check-whether-an-input-string-contains-a-number-in-javascript)
Ps. Sorry, I modified the answer with some extra links
I've just been coding for the past few months, and am just getting started on Java.
I'm getting these weird error messages when I'm testing some of my code.
In one of my exercises, I have this class WeatherRecord. I define it like this:
class WeatherRecord {
Date d;
double precipitation;
TemperatureRange today;
TemperatureRange normal;
TemperatureRange record;
WeatherRecord(Date d, double precipitation, TemperatureRange today,
TemperatureRange normal, TemperatureRange record) {
d = this.d;
precipitation = this.precipitaiton;
today = this.today;
normal = this.normal;
record = this.record;
}
Seems dandy. I also have some comments and methods, but I left those out.
Then, later on in my examples, I make an example, like this:
WeatherRecord record2 = new WeatherRecord(this.date2, 0.24,
this.temp2, this.tempNormal, this.coldTemp);
Where date2, temp2, and all that stuff are previously defined.
I then use a tester library just to check to make sure that precipitation is set to 0.24 (since one of my methods wasn't working earlier, so I was checking):
boolean test(Tester t) {
return t.checkExpect(this.record2.precipitaiton, 0.24);
}
And my console tells me that the actual value was 0.0, rather than .24. I'm consistently getting this sort of error on a lot of different exercises.
Does anything immediately stand out to y'all that I am doing wrong? Is there any more information I should provide?
Thank you!
d = this.d; this chunk of code should be the other way around. this.d = d;
as well as the others.
this.var means the object's var while the variable you receive into the method or constructor doesn't start with this
I am having a code sequence like this which is part of an Accuracy checking of a Data mining algorithm.
ie A trained data gets compared against some predicted values from my algorithm, and accuracy checking is done comparing both class labels.
say my values are [No,No],[No,Yes],[1.0,1],[1,1],[1,0] which are class labels
I am trying to compare the accuracy of my predicted data
public void reduce(Text key, Iterable<Text> values, Context context)
Set<String> set = new HashSet<String>();
for (Text val : values) {
set.add(val.toString());
}
int count = set.size();
if(count == 1){
System.out.println("Correct class label");
corClass++;
}
else{
System.out.println("InCorrect class label");
}
[No,No]: Correct class label
[No,Yes]: InCorrect class label
[1.0,1]: InCorrect class label
[1,1]: Correct class label
[1,0]:InCorrect class label
For me [1.0,1] this is falling into incorrect classlabel.
Set<String> set is treating [1.0,1] as different eventough they are equal but double and integer.
How to fix a workaround.
Please suggest
Thanks in advance.
You seem to have rules that your code doesn't respect. You say 1.0 is a "double". Is there a rule that determines under which conditions the code is a double? For example, is "1e10" a double -- 1 x 10^10? Or is it a string like "yes" presumably is?
1.0 and 1 are different strings. If you have some comparison rule that makes these two things identical, you'll have to implement it somewhere -- it won't happen by magic. It's not clear from your question precisely what the rule is, but whatever it is, implement it.
You're not storing a set of strictly strings, you're storing a set of both strings and integers. You don't know which one you're going to put in next, but you don't necessarily care about that; you're just leveraging the set properties for your use case.
What you can do instead of just create a set that stores most any object in it.
Set<?> set = new HashSet<>();
for (Text val : values) {
try {
set.add(Double.valueOf(val.toString()).intValue());
} catch (NumberFormatException nfe) {
set.add(val.toString());
}
}
It's not an attractive thing to do when we're talking about using exceptions as control flow, but this will get you past your immediate pain.
Currently, you are using a set of strings to store your data. Since it is a set of Strings, the set will allow any elements that are unequal strings. Wouldn't it be confusing if you were writing a different application, where you really needed string equality, if "1".equals("1.000")==true?
In this case, I think it would be better not to use a set at all...
This function should work properly for any number or string based equality:
public boolean stringOrDoubleEqual(String a,String b){
try{
//Change the 0.001 to the acceptable error for your application.
return Math.abs(Double.parseDouble(a)-Double.parseDouble(b))<0.001;
}catch(NumberFormatException e){
return a.equals(b);
}
}
I'm sure the rest should come naturally, if this fits your use case :)
I'm trying to create a equation that will translate a hexadecimal to a binary number.
I know what the code is in the standard editor, I just don't know how to translate it so for a GUI
This is my attempt to create it in a GUI environment.
// -------------------------------------------------------------
// Equation for Binary Conversion
//--------------------------------------------------------------
public void binaryConversion (double binary){
String binary = Integer.toBinaryString(decimal);
totalLabel.setText(decimal.format(binary));
This is the code that translates a hexadecimal to a binary number
String binary = Integer.toBinaryString(decimal);
If I didn't have to make a GUI, I would simply System.out.print these methods. I'm confused. So far I created a GUI, it's just non functioning. I need to make it function. I have a fairly good idea on how to implement actionlisteners, and buttons listeners. So I think I'll be okay with that. It's just translating these equations for a GUI that's confusing me. Any help would be appreciated.
I also need to convert a hexadecimal to a decimal.
EDIT
My attempt to use NumberFormatException. Still getting errors though.
(this is probably completely off.
public void binaryConversion (double binary){
NumberFormat b = NumberFormat.getInstance(b, 16);
Integer.toBinaryString();
For a start, does this code compile?
public void binaryConversion (double binary){
String binary = Integer.toBinaryString(decimal);
It is having both a parameter and a local variable called binary.
Update
You can use
try {
Integer b = Integer.valueOf(hexString,16);
Integer.toBinaryString(b);
} catch (NumberFormatException ee) {
ee.printStackTrace();
}
I'm new here, and I'd like some help on a small Java project I'm doing. This is the code snippet I need help with:
private void CalculateButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
float Principal, Rate, Time, Result, Temp;
Principal = Float.valueOf(PrincipalTextField.getText());
Rate = Float.valueOf(RateTextField.getText());
Time = Float.valueOf(TimeTextField.getText());
Temp = (float) Math.pow((1 + Rate / 100), Time);
Result = Principal * Temp;
ResultTextField.setText(String.valueOf(Result));
}
I'd like to check if PrincipalTextField, OR RateTextField, OR TimeTextField aren't filled by the user, and if so, display a dialog box that asks him/her to recheck them. The text fields are JFormattedTextField variables. I realise that I can do this with a if/else or a while loop, but I'm not sure how to set about doing so. Please help!
You can do something like this:
The getText() returns you a String value. So you can always invoke length() and check whether the length comes to 0 or not. (*I would suggest calling trim() on the String before calling length() to remove any whitespaces)
Next if any of the length comes to be zero, what you want to do is display a Dialog Box. This you can do by calling JOptionPane.showMessageDialog(). You can read more about "How to Make Dialogs" over here.
So, you would do something like this:
String principalText = PrincipalTextField.getText();
String rateText = RateTextField.getText();
String timeText = TimeTextField.getText();
if(principalText.trim().length == 0 || rateText.trim().length == 0 || timeText.trim().length == 0){
JOptionPane.showMessageDialog(null, "YOUR_ERROR_MSG", "ERROR_TITLE", JOptionPane.ERROR_MESSAGE);
}
This might be off-topic, but I would suggest looking at Java Naming Convention. The convention for variables is to compose variable names using mixed case letters starting with a lower case letter
you miss reason for why there is JFormattedTextField
have to set Number Formatter for JFormattedTextField, then
you not need to parsing Float value (better could be to use double)
empty coudl be 0 (zero) value by default
take value in the form ((Number)PrincipalTextField.getValue()).floatValue();
look at code example for tutorial,
Also consider subclassing InputVerifier, as discussed in Validating Input. There's a related example here.