Set<String> treating [1.0,1] as different values - java

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 :)

Related

JButton not sending action command

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;

Converting a string to an integer with a ternary operator

I have a string that I would like to convert into an integer before storing it as a property of an object. Although I can use regular if statements, I wanted to use a ternary operation to build my understanding of it. Here is the code I've tried
field_num = (((boolean bool_is_int = is_integer(string)) == true) ? (Integer int = Integer.parseInt(string)) : null);
What I'm trying to do (very basically) is set "field_num" (which is of type int) to the value of "string" if it is equal to an integer (by first converting it). is_integer is a function I have to check if a string is equal to an integer. It returns a boolean value.
Thanks for any help.
I would do something like this:
Integer theint = is_integer(thestr) ? Integer.parseInt(thstr) : null;
You cannot assign NULL to an intrinsic int but you can to an Integer object. Typically, of course, you'd simply rely on the parseInt() call throwing an exception rather than explicitly testing for integerness of the string beforehand.
field_num = is_integer(string) ? Integer.parseInt(string): -1;
In plain english this says if 'string' is an integer then parse string for the int and set it to field_num otherwise, set it to -1. -1 is arbitrary. you should instead use a number that is invalid for field_num.
You do not need is_integer(string) == true because that evaluates to the same thing as is_integer(string). You also don't need to set the boolean bool_is_int because unless you actually want that value later in the program.
You should just use an if/else statement. The Ternary operator is useful when you you want to set a variable to one of two values based on a condition. In your example, you don't want to set the value if the string is not an integer so ternary doesn't fit the situation well.
Keep it simple :)
int field_num = isInt(string) ? Integer.parseInt(string) : Integer.MAX_VALUE;
if (field_num == Integer.MAX_VALUE) {
// error; string is not a valid representation of int
}
To determine Whether a String represents an int value :
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
[Corrected]
Learn one thing at a time.
First, the ?: operator (more often referred to as the conditional operator, or the if/else operator; "ternary" just means it takes three arguments, and it's the only C operator that does so, hence the confusion)...
field_num = is_integer(string) ? Integer.parseInt(string) : null;
Ahhh. So field_num is an Integer. Would have help if you'd said that.
Second: Assignment-in-passing. If you don't know that you need to do this, and you can't make it perfectly obvious what you're doing and why, DON'T. It's hard to read, and it's rarely appropriate.
Also, "int" is not a legal variable name.
But if you insist:
Integer myint;
boolean bool_is_int;
field_num = (bool_is_int = is_integer(string)) ? (myint = Integer.parseInt(string)) : null;
What's myint's value in the false/else case? It's left as whatever it had been set to previously. This might be what you intended, but it's very hard for someone reading your code to understand.
In most cases, unless the ?: is a very simple one that can be read at a glance -- (foo!=null) ? foo.doSomething() : defaultValue -- you're better off using a real if/then/else statement. It's likely to be just as efficient after the compiler and JIT are done with it, and it'll be a lot easier to maintain.

Sudoku solver Recurrence stack with try and fail technique

I am building a Sudoku solver that use the Try and Fail technique to solve any problem. My algorithm is:
1)Update (method that remove any possible value that already given as a final value to element in the same Row, column or squar)
2)Get the minimum element that has minimum number of possible values
3)start solve assuming the first possible value is the final value
4)save the current sate into a stack
5)Try to solve
5-a)If solved, return
5-b)if not solved and with invalid Sudoku, then Pop previous state
6)Repeat step 3) for all possible vaues (9)
7)Repeat step 2) until the puzzel is solved
This is my code
Stack<Element[][]> myStack= new Stack<>();
private Element[][] mySudoku;
public void solve(){
update();//remove all final values from all possible values for each element
if(isSudokuSolved(mySudoku)){
return;
}
//find a cell that is not confirmed and has the minimal candidates
int celli=-1,cellj=-1, p=10;
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(mySudoku[i][j].getValue()==0){
if(mySudoku[i][j].getPossibleValues().size()<p){
celli=i;
cellj=j;
p=mySudoku[i][j].getPossibleValues().size();
}
}
}
}
try {
for (int c = 0; c < mySudoku[celli][cellj].getPossibleValues().size() - 1; c++) {
//save state
Element[][] copy=deepCopy(mySudoku);//copy the current state
myStack.push(copy);
//apply candidate to cell
mySudoku[celli][cellj].setValue(mySudoku[celli][cellj].getPossibleValues().get(c));
update();//check is solved
if(checkValidInputSudoku(mySudoku)){
solve();
}else{
try {
mySudoku = myStack.pop();
} catch (EmptyStackException est) {
//do nothing
}
}
}
} catch (Exception e) {
}
//if we have reached here then we are at the last possible value for the candidates so confirm candidate in cell
if(celli!=-1 && cellj!=-1 && p!=10) {//Some problems happen here "out of Boundry -1 Error"
mySudoku[celli][cellj].setValue(mySudoku[celli][cellj].getPossibleValues().get(mySudoku[celli][cellj].getPossibleValues().size()-1));
}
}//end of solve method
I have spent more than 6 hours trying to find out the problem. I have checked for the Update() method, deepCopy() method and checkValidInputSudoku() method. They all works fine. Thank you in Advance
I can see one problem in your code. You have a loop that is sawing off the branch it sits on:
for(int c = 0; c < mySudoku[celli][cellj].getPossibleValues().size() - 1; c++) {
...
mySudoku[celli][cellj].setValue(mySudoku[celli]cellj].getPossibleValues().get(c));
...
}
Apart from that, you are missing one of the values, it should be for(c=0; c!=size; ++c), i.e. not size - 1. Also, calling getPossibleValues() just once would make this code much more readable. Lastly, catching and ignoring a stack underflow is just stupid, because it hides errors in your algorithm, as far as I can tell. If you don't know how to handle an error, don't just silence it. Since java requires you to catch it, put it in the outermost place possible or at least abort or do something, but don't ignore it!
One more thing: You are recursing and passing the context data via mySodoku and myStack. This is completely missing the point of recursion (or at least the way it's typically used), because the function call stack is the only stack you need. Using these to pass parameters only makes things more complicated than necessary. Instead, the function should return a partial sodoku puzzle and return either the fully solved puzzle or null. Using is easier to distinguish than the exception you're using now, and it's a regular and expected thing, not really exceptional. Then, when trying different choices, you set the cell to the values in turn and recurse, until the call doesn't return null. If none of the choices returns a solution, you clear the cell and return null yourself.
solve(sodoku):
if sodoku is solved:
return true
if sodoku is invalid:
return false
c = some empty cell
for v in 1...9:
// set to a value and recurse
c = v
if solve(sodoku):
// found a solution
return true
// no solution found, clear cell and return failure
c = null
return false
BTW: This strategy is called "backtracking". Using a cell with the least amount of possible values is called "pruning", which allows you to cut off whole branches from the search tree. Actually determining the possible values also helps avoiding a few futile attempts.

Check for empty JFormattedTextField

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.

Checking which date comes first?

It seems logical that there should be some simple method to check which DatePicker object comes first but I can't find done.
// so if you had two objects
final DatePicker start_datepicker = (DatePicker)findViewById(R.id.DatePickerStart);
final DatePicker end_datepicker = (DatePicker)findViewById(R.id.DatePickerEnd);
// I was thinking something along the lines of:
if (end_datepicker > start_datepicker) {
// something
}
// or is there something like
if (end_datepicker.isLarger(start_datepicker)) {
// Something
}
Is this possible or does anyone know of something simple along these lines to compare to dates?
A DatePicker is a UI widget for displaying a date. You don't set it by assignment (as in your code) but by calling it's init method. Typically you would then track the date using an OnDateChangedListener. Nevertheless, you can compare the current dates displayed on two such widgets with something like this:
/** Returns a number <0, 0, or >0 when dp1 displays a date <, =, or > dp2. */
public int compare(DatePicker dp1, DatePicker dp2) {
int compare = dp1.getYear() - dp2.getYear();
if (compare == 0) {
compare = dp1.getMonth() - dp2.getMonth();
if (compare == 0) {
compare = dp1.getDay() - dp2.getDay();
}
}
return compare;
}
You should take the resulting values from the date pickers and convert them to Date objects which will then allow you to easily compare the values rather than going the route of writing your own Comparator that relies on the UI component.
I actually wrote a Java class specifically to handle this situation for Android. Feel free to use it and include it in your app! It's documented, as well.
Date has before() and after() methods.. just for that.

Categories

Resources