String.Format chokes on decimal values? - decimal

I expect both tests below (written for NUnit) to pass, but the Decimal version fails with, "System.FormatException: Format specifier was invalid", as does a Double version. I cannot figure out why. Can someone please shed light?
Thanks;
Duncan
[Test]
public void Integer_Format_Hex()
{
//Assume
Int32 myValue = 11101110;
//Arrange
//Act
//Assert
Assert.That( String.Format( "0x{0:X8}" , myValue ) , Is.EqualTo( "0x00A963B6" ) );
}
[Test]
public void Decimal_Format_Hex()
{
//Assume
Decimal myValue = 11101110m;
//Arrange
//Act
//Assert
Assert.That( String.Format( "0x{0:X8}" , myValue ) , Is.EqualTo( "0x00A963B6" ) );
}
[Test]
public void Decimal_Format_Hex2()
{
//Assume
Decimal myValue = 11101110m;
//Arrange
//Act
//Assert
Assert.That( myValue.ToString( "X" ) , Is.EqualTo( "00A963B6" ) );
}

Exerpt from http://msdn.microsoft.com/en-us/library/fzeeb5cd(v=VS.90).aspx
"The format parameter can be any valid standard numeric format specifier except for D, R, and X...."
Awesome.

Related

Weired problem after reading input from keyboard

edit: The ArrayList wasn't needed to reproduce the "error". Sorry for this delay, but know it should be much clearer.
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
package com.example.mypackage;
import java.util.ArrayList;
import java.util.Scanner;
class Contact {
public String name;
public String number;
public Contact(String name, String number) {
this.name = name;
this.number = number;
}
public void print(){
System.out.println(name+number);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (obj == null) {
return false;
} else if (obj instanceof Contact) {
Contact contact = (Contact) obj;
if ((contact.name == this.name && contact.number == this.number)) {
return true;
}
}
return false;
}
}
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Contact c1 = new Contact("ben", "1");
c1.print();
Contact c2 = new Contact("ben", "1");
c2.print();
System.out.println("name : ");
String name=scanner.nextLine();
System.out.println("number");
String number=scanner.nextLine();
Contact c3=new Contact(name, number);
c3.print();
System.out.println("c1.equals(c2) = "+c1.equals(c2));
System.out.println("c3 instanceof Contact = "+(c3 instanceof Contact));
System.out.println("c2.name.equals(c3.name) = "+c2.name.equals(c3.name));
System.out.println("c2.number.equals(c3.number) = "+c2.number.equals(c3.number));
System.out.println("c2.number.equals(c3.number) = "+c3.equals(c2));
}
}
Output is:
ben1
ben1
name :
ben
number
1
ben1
c1.equals(c2) = true
c3 instanceof Contact = true
c2.name.equals(c3.name) = true
c2.number.equals(c3.number) = true
c2.number.equals(c3.number) = false
Process finished with exit code 0
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Why is:
c2.number.equals(c3.number) = false
I really expected a true here. There must be something wrong with my equals method?
Why on earth do I need to write more text...
Ah finally I got it. The error is in the equals method.
I must use "equals()" instead of "==" there. For some reason this comparison does work with c1 and c2 but not with c3.
-1 is returned if it wasn't found in the list.
Did you forget to myList.add() it?
The only add I see is when you added c1.
You need to myList.add(c3) after you get the input, or it won't be in the list to find an index of.

Apply decimal format to a CellType.Formula

I've recently update my POI lib to 3.17 and since then when I have a CellType.FORMULA I can't do the following:
public static void writeDecimal(Cell cell) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
String pattern = "#0.00";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
BigDecimal bigDecimal;
try {
bigDecimal = (BigDecimal) decimalFormat.parse(cell.getStringCellValue());
Double value = bigDecimal.doubleValue();
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(value);
} catch (ParseException e) {
Logger.getGlobal().log(Level.FINE, e.getMessage(), e);
}
}
I get this error Cannot get a STRING value from a NUMERIC formula cell, because of this bigDecimal = (BigDecimal) decimalFormat.parse(cell.getStringCellValue());
With 3.7 library I was able to execute this.
Thanks in advance
The issue is that the cell in the file itself is formatted to be a numeric cell. Assuming this cell will either always be a String or a Number, you should be able to modify your code just a little bit to get it to work.
You'll just need to check if it is a String cell first, and if it is, do things the way you're currently doing them. If it is a Numeric cell, you'll need to make your new BigDecimal from that number. I haven't worked much with BigDecimal, but I think the following code should work:
try {
if(cell.getCellTypeEnum() == CellType.STRING) {
bigDecimal = (BigDecimal) decimalFormat.parse(cell.getStringCellValue());
} else {
//Assuming here that cell.getCellTypeEnum() == CellType.NUMERIC
bigDecimal = new BigDecimal(cell.getNumericCellValue());
}
Double value = bigDecimal.doubleValue();
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(value);
} catch (ParseException e) {
Logger.getGlobal().log(Level.FINE, e.getMessage(), e);
}
As an aside, is the BigDecimal necessary here? You seem to create it and then just get the Double value from it. You might be able to optimize this code by removing the BigDecimal stuff.

boolean to string in TableView JavaFx

im trying to display a boolean value as a string in a tableview so instead of true i want to display male.
i'm a bit lost with it to be honest. i cant find anything on the internet to help.
the error ecilpse is giving me is The method " setCellValueFactory(Callback,ObservableValue>) in the type TableColumn is not applicable for the arguments (( cellData) -> {})"
heres my code. its probably wrong
TableColumn<Animal, String > genColumn = new TableColumn<>("Male");
genColumn.setMinWidth(50);
genColumn.setCellValueFactory(cellData -> {
boolean gender = cellData.getValue().getGender();
String genderAsString;
if(gender == true)
{
genderAsString = "Male";
}
else
{
genderAsString = "Female";
}
new ReadOnlyStringWrapper(genderAsString);
});
i would be grateful for any help thanks
Keep the type as boolean and use a cell factory to change the way you display it:
TableColumn<Animal, Boolean> genColumn = new TableColumn<>("Gender");
genColumn.setCellValueFactory(cellData -> cellData.getValue().genderProperty());
// or cellData -> new SimpleBooleanProperty(cellData.getValue().getGender())
// if your model class doesn't use JavaFX properties
genColumn.setCellFactory(col -> new TableCell<Animal, Boolean>() {
#Override
protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty) ;
setText(empty ? null : item ? "Male" : "Female" );
}
});
i managed to get it working i was just missing the return statement.
heres the code
TableColumn<Animal, String > genColumn = new TableColumn<>("Gender");
genColumn.setMinWidth(50);
genColumn.setCellValueFactory(cellData -> {
boolean gender = cellData.getValue().getGender();
String genderAsString;
if(gender == true)
{
genderAsString = "Male";
}
else
{
genderAsString = "Female";
}
return new ReadOnlyStringWrapper(genderAsString);
});

If Else: String Equality (Java)

Lab Description : Compare two strings to see if each of the two strings contains the same letters in the
same order.
This is what I have so far far:
import static java.lang.System.*;
public class StringEquality
{
private String wordOne, wordTwo;
public StringEquality()
{
}
public StringEquality(String one, String two)
{
setWords (wordOne, wordTwo);
}
public void setWords(String one, String two)
{
wordOne = one;
wordTwo = two;
}
public boolean checkEquality()
{
if (wordOne == wordTwo)
return true;
else
return false;
}
public String toString()
{
String output = "";
if (checkEquality())
output += wordOne + " does not have the same letters as " + wordTwo;
else
output += wordOne + " does have the same letters as " + wordTwo;
return output;
}
}
My runner looks like this:
import static java.lang.System.*;
public class StringEqualityRunner
{
public static void main(String args[])
{
StringEquality test = new StringEquality();
test.setWords(hello, goodbye);
out.println(test);
}
}
Everything is compiling except for the runner. It keeps saying that hello and goodbye aren't variables. How can I fix this so that the program does not read hello and goodbye as variables, but as Strings?
You need to quote strings otherwise they are treated as variables.
"hello"
"goodbye"
so this would work better.
test.setWords("hello", "goodbye");
Problem with your code is with checkEquality(), you are comparing the string's position in memory when you use == use .equals() to check the string
public boolean checkEquality()
{
if (wordOne == wordTwo) //use wordOne.equals(wordTwo) here
return true;
else
return false;
}
Enclose them in double-quotes.

searching in List<>

i want to find value in List<> but i am not getting the integer value. Here is my code from that i want to find the value in the List
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
try
{
//decimal find = decimal.Parse(txtnapsaserach.Text);
if (decimal.Parse(txtnapsaserach.Text) > 0)
{
List<NapsaTable> _napsatabs = this.napsaTableBindingSource.List as List<NapsaTable>;
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text)).ToList();
}
}
catch (Exception Ex)
{
}
}
any solution for me . Because this works for me when i try to find string value.
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
float value;
if (!float.TryParse(txtnapsaserach.Text, out value))
return; // return if text cannot be parsed as float number
if (value > 0)
{
var napsatabs = napsaTableBindingSource.List as List<NapsaTable>;
napsaTableBindingSource.DataSource =
napsatabs.Where(p =>p.NapsaRate == value).ToList();
}
}
try this
i want to find value in List<> but i am not getting the integer value.
Your p.NapsaRate is either integer type or floating point number, (probably decimal) Convert your txtnapsaserach.Text to decimal value and then compare it in where clause.
decimal rate = 0;
if(!decimal.TryParse(txtnapsaserach.Text), out rate)
{
//Invalid number in textbox
}
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate == rate)).ToList();
if p.NapsaRate is of type double or float you can parse them accordingly using Double.TryParse or Double.Parse etc
The reason you are not getting any error is that you are using object.Equals method for comparing decimal value with string. You should always use == for equality comparison of value types.

Resources