I'm starting to learn Java..I am very excited.
First code is not return result as my want..
import java.util.Scanner;
public class Yusuf
{
public static void main(String args[])
{
Scanner text = new Scanner(System.in);
int a,b;
System.out.print("Enter first number:");
a = text.nextInt();
System.out.print("Enter second number:");
b = text.nextInt();
System.out.print("a + b = " + a+b);
}
}
This code's result is "a + b = 1525" (if a=15 and b=25 (i am giving random number for example))
Why above code isn't work such as this code:
import java.util.Scanner;
public class Yusuf
{
public static void main(String args[])
{
Scanner text = new Scanner(System.in);
int a,b,c;
System.out.print("Enter first number:");
a = text.nextInt();
System.out.print("Enter second number:");
b = text.nextInt();
c = a+b;
System.out.print("a + b = " + c);
}
}
This code returning 40 for same numbers..
What is the difference? Absolutely i need to use different variable?
When used with strings, the + operator does string concatenation. If you add numbers to the end of a string with + the numbers will be converted to strings first.
Your statement:
System.out.print("a + b = " + a+b);
takes the string "a + b" and concatenates the value from a as a string and then concatenates the value from b as a string.
It should work the way you want if you do this:
System.out.print("a + b = " + (a+b) );
The extra parens for (a+b) will cause that addition to be evaluated (as an int addition) before the string concatenation occurs.
+ does not always mean addition. When used with a string, it does concatenation.
When you do
System.out.print("a + b = " + a+b);
you are concatenating a and b onto the string.
In other words, you are doing
(("a + b = " + a) + b);
which evaluates to
"a + b = 15" + b
which evaluates to
"a + b = 1525"
When you do
c=a+b
and then
System.out.print("a + b = " + c);
you do the addition first, and then you concatenate the resulting value (40) onto the String.
In your first code when you say "a + b = " + a + b, you are doing a string concatenation. Whatever you add to a string will be come a string.
In your example,
first "a + b = " + a will become "a + b = 15" and then b will be contactenated.
So, it will become a + b = 1525
Where as in your second example, you are separately doing the addition and then concatenating to the string. So you are getting the desired result.
you can do "a + b = " + (a + b) aswell.
Just do System.out.print("a + b = " + (a+b)); so that the compiler can understand that it has to first add a and b and than concatenate.
The problem is in this line:
System.out.print("a + b = " + a+b);
The '+' operator in 'a + b' is being interpreted as a string concatenation not an integer addition.
Change it to this:
System.out.print("a + b = " + (a+b));
The reason you have to do this is a combination of the overload resolution rules for the '+' operator, and basic Java operator precedence rules.
If either operand of '+' is a String, then the operator is a string concatenation, and the non-String operand (if any) is converted to a String.
If you have x op y op z where 'op' is the same operator, then it is equivalent to (x op y) op z.
If you put that together, "a + b = " + a+b (where a and b are int) is equivalent to:
("a + b = " + a) + b
and hence
"a + b = ".concat(Integer.toString(a)).concat(Integer.toString(b))
The corrected version "a + b = " + (a + b) is equivalent to:
"a + b = ".concat(Integer.toString(a + b))
Related
This question already has answers here:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
(3 answers)
Closed 3 years ago.
I have encountered this error "Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String". I see that this is a fairly common question amongst Java newbies, and while I've attempted to apply the advice to my code, but I haven't had any success. I am hoping to get some feedback and suggestions on how to hopefully get this running properly. I am able to get it functioning properly using println, but having the output formatted is required for an assignment. Any advice would be appreciated.
Thanks.
import javax.swing.JOptionPane;
public class UserIO {
public static void main(String[] args) {
// initialize coefficients.
double a;
double b;
double c;
// int counter = 0;
String userInput; // take a String for input.
// display message. returns null.
JOptionPane.showMessageDialog(null,
"Welcome. Input positive a real number for a, b, and c. Numbers must range between 1.0 -10.0");
userInput = JOptionPane.showInputDialog("Input a real number for a.");
a = Double.parseDouble(userInput);// convert String userInput to real
// numbers.
System.out.println("Number for a = " + userInput); // print a
userInput = JOptionPane.showInputDialog("Input a real number for b. ");
b = Double.parseDouble(userInput);
System.out.println("Number for b = " + b); // print b
userInput = JOptionPane.showInputDialog("Input a real number for c.");
c = Double.parseDouble(userInput);
System.out.println("Number for c = " + c); // print c
// calculate quadratic equation 5 times, store in xValues then, print to
// screen.
double product;
double[] xValues = new double[5]; // array index of 5.
for (int i = 4; i >= 0; i--) {
xValues[i] = i + 1; // fills array with numbers 1-5.
// raise x to the i'th degree.
product = a * Math.pow(xValues[i], 2) + b * xValues[i] + c;
// System.out.println("[" + i + "]"+ " " + xValues[i] + " " +// product);
System.out.printf("%d , i " + "%1.2f ", xValues[i] + " " + "%1.3f ", product);
} // end loop
}
}
I guess this line causes theproblem:
System.out.printf("%d , i " + "%1.2f ", xValues[i] + " " + "%1.3f ", product);
which can be simplified to:
System.out.printf("%d , i %1.2f ", xValues[i] + " %1.3f ", product);
Here you can clearly see that you try to replace %d with the string xValues[i] + " %1.3f ".
I thinky you intended somethig different.
Look into the API, it should be like shown below.
System.out.printf("%d , %1.2f , %1.3f ", i, xValues[i], product);
So maybe many of you knows the exercise we need to do about learning primitives, where we need to print h3110 w0r1d 2.0 true
so mine is this;
public class main {
public static void main(String[] args) {
// H3110 w0r1d 2.0 true
byte bir = 0;
short iki = 31;
int uc = 10;
long dort = 1;
float bes = 2.0f;
char yedi = 'H';
char sekiz = 'w';
char dokuz = 'd';
char ekstra = ' ';
char ramk = 'r';
boolean on = true;
String son = (yedi + iki + uc + ekstra + sekiz + bir + ramk + dort + dokuz + ekstra + bes + ekstra + on );
System.out.println(son);
}
}
and their solution is this;
public class Main {
public static void main(String[] args) {
byte zero = 0;
short a = 3;
int b = 1;
char d = ' ';
float e = 2.0f;
boolean f = true;
String output = "H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
System.out.println(output);
}
}
So mine is giving me boolean and float errors, but I cant see what is wrong with that primitives.
the error Im getting is this
Main.java:16: error: bad operand types for binary operator '+'
String son = (yedi + iki + uc + ekstra + sekiz + bir + ramk + dort + dokuz + ekstra + bes + ekstra + on );
^
first type: float
second type: boolean
1 error
The line:
String son = (yedi + iki + uc ...
assigns a concatenation of multiple parameters of different types, none of which is a string, into a string.
The "solution" is to start the assignment by concatenating a string to the other parameters:
String output = "H" + a + b + ...
^
which will cast the rest of them - to strings.
You can do the same with the first example by adding an empty string at the beginning:
String son = ("" + yedi + iki + uc ...
^
Side-Note: I totally agree with T.J. Crowder's comment above...
The example works because everything can be automatically converted to a String, and addition is left-associative.
The difference between a char and a String may not be obvious to you. 'C' is a char literal, while "C" is a String literal (which can contain multiple chars).
Let's go through a few steps of the string concatenation in the example, showing conceptually how the addition is performed:
"H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H3" + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H31" + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H311" + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H3110" + d + "w" + zero + "r" + b + "d" + d + e + d + f;
...and so on. Every addition will always be a String + some other value, which is fine.
The addition in your code, on the other hand, tries to add incompatible types like int and boolean, which doesn't fly. Also, it tries to store the result in a String variable, which is not possible, because the result is not a String.
I would like to concatenate a few variables into a string variable but I am unable to get it to work. When I compile it says "not a statement" and "; expected."
float a = 1;
float b = 2;
String resW;
My purpose is to concatenate "a" and "b" and assign it to resW.
resW = a " + " b;
My ultimate goal is to use resW as such...
System.out.println(resW);
bufferedWriter.write(resW);
It should save to a file in the format of "1 + 2". I don't understand how to do this properly or if this is even possible.
String resW = a + " + " + b;
try this..
resW = a + " + " + b;
Use a plus sign to concatenate Strings.
It should allow an autoconversion from float to String, but if it doesn't, you can change the floats to Floats, and do:
resW = a.toString() + " + " + b.toString();
Instead of using resW, you could try this:
public class QuickTester {
public static void main(String[] args) {
float a = 1;
float b = 2;
System.out.println(String.format("%.0f + %.0f", a, b));
System.out.println(String.format("%.2f + %.2f", a, b));
System.out.println(String.format("%.5f + %.5f", a, b));
}
}
Output:
1 + 2
1.00 + 2.00
1.00000 + 2.00000
Note:
If you insist, you could do something like String resW = String.format(...);
String#format can help you 'beautify' your resulting string, allowing you to specify the number of decimal places, alignment, etc
Just starting learning java today and can't seem to figure this out. I am following the tutorial on learnjavaonline.org which teaches you a few things and then asks you to write a code to do a specific thing, it then checks the output to see if its correct. The thing is, if its not correct, it doesn't say why, or give you an example of the correct code.
It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives
i came up with this
public class Main {
public static void main(String[] args) {
char h = 'H';
byte three = 3;
short one = 1;
boolean t = true;
double ten = 10;
float two = (float) 2.0;
long won = 1;
int zero = 0;
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
System.out.println(output);
}
}
but it outputs 86.0 w0r1d 2.0 true
how can i make it so it doesn't add all the integers, but displays them consecutively?
The problem with this line:
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
is that operations are performed left to right, so it first sums h + three (which evaluates to an int) and then one and then ten. Up to that point you have a numerical value (an int) that then will be "summed" to a String. Try something like this:
String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
In this second case your expression will start with a String object, evaluating the rest of the operations as Strings.
You of course could use "" at the beginning or any other value that evaluates to String, like String.valueOf(h). In this last case you wouldn't need to use String.valueOf() for the other operands, as the first one is already a String.
You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.
system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).
There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest; to force all following values into the string like it does in the printline statement.
Most of it is not very pretty coding but will completly suffice for the learning process.
An easy and ugly way to do this would be to use String.valueOf for each numerical value.
As in:
String output = h + String.valueOf(three); // + etc...
Edit
morgano's approach is perfectly valid as well - +1 for that.
On a more general topic, you might want to use String.concat for String concatenation, or even better, a StringBuilder object.
This SO page contains a lot of info you can use on the matter.
I would use String.valueOf to explicitly cast each numeric value to String before being added. Like so:
String output = h + String.valueOf( three ) + String.valueOf( one ) + String.valueOf( ten ) + " " + "w" + String.valueOf( zero ) + "r" + String.valueOf( won ) + "d " + String.valueOf( two ) + " " + t;
The trick is to get the compiler to interpret + as string concatenation (which then silently convert the numbers to strings) instead of adding two numbers. This mean that one of the two arguments to + must be a string, and not - as your first three arguments - numbers (and yes, a char is a number).
It is not typical in code in the wild to want numbers to be directly adjacent to each other, but have a space between them, like:
String output = h + " " + three + " " + one + " " + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
If you really want to have no spaces, then just let the first argument be the empty string:
String output = "" + h ....
You could also just change h from char to String.
The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.
Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of:
72 + 3 + 1 + 10.0 (which is equal to 86.0)
String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play.
In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:
char h = 'H'; // This is a numeral! Capital H has value 72 in Ascii table
byte three = 3;
short one = 1;
boolean t = true; // not a numeral
double ten = 10;
float two = (float) 2.0;
long lOne = 1;
int zero = 0;
System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"
+ zero + "r" + lOne + "d " + two + " " + t );
Note how I needed to cast ten to the int-type, to lose the decimal...
Above example is however not a good example of using string concatenations!
For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:
System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
(int) ten, zero, lOne, two, t));
Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat
// please note: the double and the float won't print decimals!
// note: import java.text.MessageFormat for this
System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
three, one, (int) ten, zero, lOne, two, t));
More examples from the Ascii table.
public class Main {
public static void main(String[] args) {
int b = 3110;
int d = 0;
String e = "orld";
double f = 2;
boolean g = true;
System.out.println("H" + b + " " + "w" + d + e + " " + f + " " + g);
}
}
I was trying to pass a string object to System.out.printf(...) in Java, but I kept getting this error "java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0" which actually doesn't make a lot of sense to me.
String format = "%" + (3 * n) + "s"; // n is an int defined somewhere above, could be 0
System.out.printf(format, "My string");
Does anyone know if this is allowed?
Edit for more details:
int n = 0;
String fm = "%" + (3 * level) + "s";
String realFm = "%0s";
System.out.println("fm = " + fm);
System.out.println("realfm = " + realFm);
System.out.println("equals? " + (fm.equals(realFm)));
System.out.printf(fm, " ");
Here's the output:
fm = %0s
realfm = %0s
equals? true
java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0
Thanks
Yes it's allowed, but it won't work if n is 0. Is there a chance of this happening (looks like it from the error message)?
what if you add a line to your code to debug it:
// line added below for debugging. To remove later:
System.out.println("n is: " + n);
String format = "%" + (3 * n) + "s"; // n is an int defined somewhere above
System.out.printf(format, "My string");
Does it ever print n is: 0?
e.g.,
public static void main(String[] args) {
// try the for loop with n = 0 vs. n = 1
for (int n = 1; n <= 10; n++) {
// line added below for debugging. To remove later:
System.out.println("\nn is: " + n);
String format = "%" + (3 * n) + "s";
System.out.printf(format, "My string");
}
}