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
Related
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'm trying to calculate the average of the student scores and as it stands I'm struggling with the calculation part.
In my assignment I was asked to caulculate the avg age of three students and avg. heigth of three students.
Could someone please guide me in the last line of this code, I apologize for the newbie question, really stuck and cannot come up with any solution to why it's not calculating my numbers.
public static void main(String[] args) {
// this method will display the scores of students
//variable declaration
int JasperAge = 20;
int JasperHeigth = (int) 175.5;
int PaulaAge = 25;
int PaulaHeigth = (int) 190.5;
int NicoleAge = 18;
int NicoleHeigth = (int) 165;
//output
Scanner output = new Scanner (System.in);
System.out.println("Name\t "+ " Age\t " + " Height (cm)\t");
System.out.println("\n");
System.out.println("Jasper\t "+JasperAge+" \t "+JasperHeigth);
System.out.println("Paula\t "+PaulaAge+" \t "+PaulaHeigth);
System.out.println("Nicole\t "+NicoleAge+" \t "+NicoleHeigth);
System.out.println("Average\t ((20 + 25 + 18) /3) \t ((175.5 + 190.5 + 165) /3)");
}
}
There are a few things wrong:
int JasperHeigth = (int) 175.5;
int PaulaHeigth = (int) 190.5;
int NicoleHeigth = (int) 165;
Given that these appear to be heights with decimal values, it is likely that you would want to store these as doubles instead of ints. When you declare a value like 175.5 as an integer, it is actually truncated to instead be 175. To store the full value of these numbers, you should instead define them as:
double JasperHeigth = 175.5;
double PaulaHeigth = 190.5;
double NicoleHeigth = 165;
Side note: the reason you had to cast those numbers using (int) was because 175.5 is actually a double literal instead of an int, which was what you declared the variable as before.
Next, this scanner definition line is never used:
Scanner output = new Scanner (System.in);
You would use the Scanner class to get input from the user. For instance, if you wanted the user to enter in some names or numbers. In this case, it doesn't look like you need to request any input from the user so this line can probably be deleted.
And lastly, the problem with displaying your output is in this line:
System.out.println("Average\t ((20 + 25 + 18) /3) \t ((175.5 + 190.5 + 165) /3)");
The problem is that by enclosing the numbers within quotation marks, your expected arithmetic will not be evaluated and instead just displayed to the user as character data. If you wanted to evaluate those expressions you could instead pull the math operations out of the quotation marks and concatenate them to the String data using the + operator:
System.out.println("Average\t" + ((20 + 25 + 18) /3) + "\t" + ((175.5 + 190.5 + 165) /3));
However, there are still a few things wrong with this. First, ((20 + 25 + 18) /3) will evaluate as integer division. It will reduce to 63/3 which is 21. However, it would also display 21 if you had 64/3 or 65/3, because integer division truncates the part of the number past the decimal point. To prevent truncation of your desired result, you can cast either one of the numbers in the numerator or denominator to double, or divide by a double literal such as 3.0. So something like this:
System.out.println("Average\t" + ((20 + 25 + 19) /3.0) + "\t" + ((175.5 + 190.5 + 165) /3.0));
Then finally, none of these numbers are actually using the variables you defined earlier, they are completely separate. If you want to actually average the variables you will need to substitute them into the expression like this:
System.out.println("Average\t" + ((JasperAge + PaulaAge + NicoleAge) /3.0) + "\t" + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3.0));
Summary
Here is a program with all my suggested edits:
public static void main(String[] args) {
// this method will display the scores of students
//variable declaration
int JasperAge = 20;
double JasperHeigth = 175.5;
int PaulaAge = 25;
double PaulaHeigth = 190.5;
int NicoleAge = 18;
double NicoleHeigth = 165;
System.out.println("Name\t "+ " Age\t " + " Height (cm)\t");
System.out.println("\n");
System.out.println("Jasper\t "+JasperAge+" \t "+JasperHeigth);
System.out.println("Paula\t "+PaulaAge+" \t "+PaulaHeigth);
System.out.println("Nicole\t "+NicoleAge+" \t "+NicoleHeigth);
System.out.println("Average\t" + ((JasperAge + PaulaAge + NicoleAge) /3.0) + "\t" + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3.0));
}
Your last line should probably be something like:
System.out.println("Average age: " + ((JasperAge + PaulaAge + NicoleAge) /3) + ". Average height: " + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3) ".");
Mind my calculations, but you get the idea.
Java's an object-oriented language. You might just be starting, but it's never too soon to learn about encapsulation:
public class Student {
private final String name;
private final int age; // bad idea - why?
private final double heightInCm;
public Student(String n, int a, double h) {
this.name = n;
this.age = a;
this.heightInCm = h;
}
public String getName() { return this.name; }
public int getAge() { return this.age; }
public double getHeightInCm() { return this.heightInCm; }
public String toString() {
return String.format("name: '%s' age: %d height: %10.2f (cm)", this.name, this.age, this.heightInCm);
}
}
You just have to make your last print like this:
System.out.println("Average\t " + ((20 + 25 + 18) /3) + "\t " + ((175.5 + 190.5 + 165) /3));
or even better use your variables:
System.out.println("Average\t " + ((JasperAge + PaulaAge + NicoleAge) /3) + "\t " + ((JasperHeigth + PaulaHeigth + NicoleHeigth) /3));
The output of my program needs to be the value of an int printed inside square brackets but i can't work out how to type this so that it will compile!?
If I am understanding the question.
Say you have an int
int number = 0;
and you have a print statement.
System.out.println("This is the number : [" + number + "]");
That is how you do it.
just append the "[" + number + "]"
public static void main(String[] args) {
int a = 10;
System.out.println("[" + a + "]");
}
Output
[10]
As said:
System.out.println("[" + a + "]");
The + signs means "and". print string AND int AND string.
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'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))