How to print both bool and double in same line? [duplicate] - java

This question already has answers here:
How to format strings in Java
(10 answers)
Closed 3 years ago.
I am working on this very simple java problem which requires to print both the objects money and isTrue without skipping a line.
I have tried casting both objects to string but doesn't work. I know I could have two print statements but they would print on 2 differents lines. I need both to print as 9999.99false
class Main {
public static void main(String[] args) {
double money = 9999.99;
boolean isTrue = false;
System.out.println(money + isTrue);
}
}
The output expected is 9999.99false
Thanks!

What is happening right now is the compiler is seeing that you are trying to add a double and a boolean together using the + operator, which it does not know how to do. One option is to use the below code:
System.out.println("" + money + isTrue);
The first String literal tells the compiler to add a String and a double, which the compiler can do successfully by implicitly converting the double to a String. The same thing happens with the boolean.
Since String is a class, and double and boolean are primitive types, casting does not work between the two like it would in C# (see here for more information on that).
This produces your expected output when run:
9999.99false

Related

Why do I get a number when I add chars? [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 1 year ago.
I once decided to add two chars together, and it gave me a number. Here's the code:
class Main {
public static void main(String[] args) {
System.out.println('a'+'b');
}
}
Output: 195.
I've searched in a lot of places, but I still couldn't figure out why a char + char = int. Can someone explain this to me?
NOTE: THIS IS NOT A DUPLICATE!! The other question is asking the data type of an added char. This question asks why this happens. Those are DIFFERENT QUESTIONS WITH DIFFERENT ANSWERS!
You're adding their ASCII values:
'a'+'b' = 97+98 = 195
If you want to concatanate, try this :
System.out.println("a"+"b");
5.1. Kinds of Conversion
This code implicitly casts them to String:
System.out.println("" + 'a' + 'b'); //ab
And this code casts to double:
System.out.println(.8 + 'a' + 'b'); //195.8

ParseFloat String Java [duplicate]

This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Closed 4 years ago.
I have this String -> "100,24" and I want join in the var Java type float
But when I have the parse, I get error.
article.cost((Float.parseFloat(array.get(y))));
I need help, ty.
The number format must contain dot(.) instead of comma(,). That's why you get the exception. However, you can also use parseFloat with String's replace method to convert float by using comma.
class NumberTest {
public static void main(String[] args) {
String y = "100,24";
float num = Float.parseFloat(y.replace(',','.'));
System.out.println(num);
}
}
Your issue is the comma, "100,24", that string is not a valid float. So an error will be thrown if you try converting it to one. However if this is what you intended "100.24" that should fix your problem, because that is a valid float type.
So what you do is replace the ',' with a '.' and then try converting. i.e.
String floatStr = "100,24".replace(",", "."); // Change to a correct float value
float newFloat = Float.parse(floatStr); // parse and get your new float

Why am I getting an error when checking if a string can be an double [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 4 years ago.
Hey guys im pretty new to coding but one of my projects is to check to see if a string can be parse into a double. It keeps printing an error when trying running the program.
Here is the code:
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
// Constant entered in by user as a string
out.println("Welcome to constant approximator");
out.println("Please enter in a constant to be estimated");
String realConstant = in.nextLine();
//Double variable created in order to reassign later
double test = 0;
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
//Test reassign and converts
test = Double.parseDouble(realConstant);
out.print(test);
in.close();
out.close();
}
}
Here is the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "pi"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at ABCDGuesser1Test.main(ABCDGuesser1Test.java:36)
It happens because you type pi which is not recognized as π (pi) constant. What have you typed was a String and these characters are not convertible to a number.
If you want to enter any number including the special constant like pi, you have to check first if the input is a Number or String. In case it's String, you can try to match it with a defined constant like π or e and use their defined value in Java such as Math.PI.
You should use the result of canParseDouble() not just call it. Something like this, I think:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
As you say:
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
You know that this line calls a boolean method and will then return either true or false. However, you do not do any use of this returned value. If so, what's the point of even calling the function, right?
You are trying to check if the string realConstant is a double, the method checks it but you simply ignore it, here. I believe you have an error because whether it is truly a double or not, the rest of the code will run. In the case where the string is not actually a double, an error will appear since the rest of the code cannot compile.
You should then use an if statement such as:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
Also, I do not think you should expect an input of "pi" to return a double!

Getting Rid of Decimal place in Java? [duplicate]

This question already has answers here:
How to Replace dot (.) in a string in Java
(4 answers)
Closed 8 years ago.
I am reading in java inputs in format below
2499.873639
32.374242
0.610059
...
Now i want to get rid of the decimal place and have them in this format
2499873639
32374242
610059
...
I have this code which does it for smaller number for not for larger numbers. The Larger numbers become negative (i think this overflowing) and giving it junk values.
BigDecimal b = new BigDecimal(a).multiply(new BigDecimal("1000000.")
If i increase the 0's by another two
BigDecimal b = new BigDecimal(a).multiply(new BigDecimal("100000000.")
It works for larger numbers but not smaller numbers. In short of having a bunch of if's is there anyway to fix this issue?
Use this :
BigDecimal b = new BigDecimal(a.toString().replace('.', ''));
String formattedInput = (String.valueOf(input)).replace(".", "");
You can do this with String replacement functions.
public static BigDecimal noDecimal(BigDecimal b) {
return new BigDecimal(b.toPlainString().replace(".", ""));
}
If you already have a String rather than a BigDecimal, this can be simplified to this:
public static BigDecimal noDecimal(String s) {
return new BigDecimal(s.replace(".", ""));
}
Convert the double to String, if it is not.
Then use String.replace('.', '');
Then Convert back to int or long, if necessary.

Why does a char disappear when concatinated with an integer [duplicate]

This question already has answers here:
The concatenation of chars to form a string gives different results
(5 answers)
why does a char + another char = a weird number
(4 answers)
Closed 8 years ago.
We had an odd thing in our logging happen today. Printed is a list of integers and longs separated by commas, like the following code:
public class Main {
public static void main(String[] args) throws InterruptedException {
long l = 10;
System.out.println(l + ';' + "text");
}
}
The problem was that the ; disappeared from the output.
The problem here is caused by the overload of the + operator. It acts in one way when operating on a String and a long, and another when operating on a char and a long. When one of the operands is a string it will try to cast the other operand to a string if it's not already one and then concatenate the two.
But when the operators are numbers, like int and long, the + operator acts as the normal mathematical plus operator. And since char is a number and nothing else, ';' + l is treated as a numerical operation and thus the output of the code in the question is 69text and not 10;text.

Categories