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));
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);
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
Description: Write a program that asks the user for a starting value and an ending value. The program should then print all values inclusively between those values. In addition, print out the sum and average of the numbers between those two values.
I need help trying to layout the program and getting it to run correctly. The program runs, the desired result just isn't the same. Can someone help me understand what i should do for it to work correctly. Thank you.
But, here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Prog152d
{
public static void main(String[] args) throws IOException
{
BufferedReader userin = new BufferedReader(new InputStreamReader(System.in));
String inputData;
int starting, ending, sum;
double avg;
sum = 0;
System.out.print("Enter Starting Value: ");
inputData = userin.readLine();
starting = Integer.parseInt( inputData );
System.out.print("Enter Ending Value: ");
inputData = userin.readLine();
ending = Integer.parseInt( inputData );
while ( starting <= ending)
{
System.out.println(starting);
sum = sum + starting;
avg = sum / 4;
System.out.println("Sum of the numbers " + starting + " and " + ending + " is " + sum);
System.out.println("The average of the numbers " + starting + " and " + ending + " is " + avg);
starting++;
}
}
}
Sample Output:
Enter Starting Value: 5
Enter Ending Value : 8
5
6
7
8
Sum of the numbers 5..8 is 26
The average of the numbers 5..8 is 6.5
The first problem I see is with the following line:
avg = sum / 4;
Don't use a constant value (in this case 4) unless it is the ONLY possibility. Instead use a variable and set its value equal to the difference between your starting and ending values:
int dif = ending - starting + 1; // add one because we want to include end ending value
avg = sum / dif;
Also, the average only needs to be calculated once at the end and therefore doesn't belong inside your loop. After making these adjustments you'll end up with something like this...
int start = starting; // we don't want to alter the value of 'starting' in our loop
while ( start <= ending)
{
System.out.println(start);
sum = sum + start;
start++;
}
int dif = ending - starting + 1;
avg = (double)sum / dif;
System.out.println("Sum of the numbers between " + starting + " and " + ending + " is " + sum);
System.out.println("The average of the numbers between " + starting + " and " + ending + " is " + avg);
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 a bit confused about how += assignment operator works. I know that x += 1 is x = x+1. However, in this code there is a string variable called 'String output' and initialized with an empty string. My confusion is that that there are 5 different outputs for the variable 'output' but I don't see where it's being stored. Help clarify my misunderstanding. I can't seem to figure it out.
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //number of questions
int correctCount = 0; // Count the number of correct answer
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; // Output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. if number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer "What is number1 - number2?"
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++; // Increase the correct answer count
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "
wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime = startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
Answer given by Badshah is appreciable for your program and if you want to know more about operator' usability, jst check out this question i came across
+ operator for String in Java
The answers posted have very good reasoning of the operator
Its Add AND assignment operator.
It adds right operand to the left operand and assign the result to left operand.
In your case
output += someString // output becomes output content +somestring content.
`
Maybe the proper answer was written but if I understand your question correctly, you want some clarification instead of meaning of +=
Change the code;
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
as this:
output += "\nCount: " + count + " and the others: " +
number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
// Increase the question count
count++;
So you can see the line and the count together. Then increase as your wish.
In Java, Strings are immutable. So output += somethingNew makes something like this:
String temp = output;
output = temp + somethingNew;
At the end, it becomes something like concat/merge