Struggling with understanding FOR and WHILE loops - java

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);

Related

When my loop repeats, why isn't the random value assigned to a certain variable changing?

System.out.println("Composition Statistics for Families with Two Children: \n");
System.out.println("Total Number of Families: ");
FamilyNumber = Integer.parseInt(in.nextLine());
List<String> list = Arrays.asList(boy, girl);
while (RunCount < FamilyNumber) {
randNum = (int)(Math.random() * 1 + 0);
randNum2 = (int)(Math.random() * 1 + 0);
FirstGender = list.get(randNum);
SecondGender = list.get(randNum2);
GenderValues = FirstGender + SecondGender;
if (GenderValues == "BG" || GenderValues == "GB") {
BGCount++;
}
else if (GenderValues == "GG") {
GGCount ++;
}
else {
BBCount++;
}
RunCount++;
}
GGPercent = ((double)(GGCount/FamilyNumber)*(100));
BGPercent = ((double)(BGCount/FamilyNumber)*(100));
BBPercent = ((double)(BBCount/FamilyNumber)*(100));
System.out.println("Number of Families with: \n");
System.out.println("\tTwo Boys: " + BBCount + " Represents " + BBPercent + "%");
System.out.println("\tTwo Girls: " + GGCount + " Represents " + GGPercent + "%");
System.out.println("\tOne Boy and One Girl: " + BGCount + " Represents " + BGPercent + "%");
This is the segment of code the issue is in. I already initialized all the variables and imported everything necessary. The problem is, whenever I run the program, I get this output:
Composition Statistics for Families with Two Children:
Total Number of Families:
15
Number of Families with:
Two Boys: 15 Represents 100.0%
Two Girls: 0 Represents 0.0%
One Boy and One Girl: 0 Represents 0.0%
The output is always two boys make up all the families. I'm assuming that the issue is with randNum and randNum2 variables, but I'm really not sure. I have no idea what to do so any input on where I'm going wrong is greatly appreciated.
Math.random returns a number between 0 and 1.
So when cast to an int it will be always 0.
Select a scaling factor and multiply the result (lets say 5)
and then the result will an int in the range 0-4

Getting error Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String [duplicate]

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);

Java depreciation table loop using sum of years

Three parameters are passed into this function to output a depreciation table. The first loop calculates the sum of the years, while the second loop will calculate depreciation for each year during the useful life of the item entered by the user. I'm having trouble coding the second loop so that it outputs the correct values under the headers of the above System.out.println statement. As is the loop won't run since it's the same loop as the first one.
public class Table
{
public void makeDepreciationTable( int useful_Life, double acquisition_Value, double salvage_Value )
{
int sum = 0;
int year = 1;
double accumulatedDepreciation;
// make a loop to calculate the sum
while ( year <= useful_Life )
{
sum += year;
year++;
}
System.out.println("The sum is " +sum );
// write the header of the table
System.out.println(" Acquisition Value" + "" + " Salvage Value" + "" + " Useful Life" + "" + " Annual Depreciation" + "" + " Accumulated Depreciation" + "" + " Book Value" + "" +" Fraction");
// make a loop
while ( year <= useful_Life )
{
// calculate fraction
double fraction = (double)year/sum;
// calculate annualDepreciation
double annualDepreciation = (acquisition_Value - salvage_Value) * fraction ;
// calc accumulatedDepreciation
accumulatedDepreciation += annualDepreciation;
// calc bookValue
double bookValue = acquisition_Value - accumulatedDepreciation;
// write one line of table
System.out.println(acquisition_Value + "" + salvage_Value + "" + useful_Life + "" + annualDepreciation + "" + accumulatedDepreciation + "" + bookValue + "" + fraction);
year++;
}
}
}
Because year has become equal to the useful_Life during the end of the first while loop, you need to reset the year value to 1 again just before the 2nd while loop as shown below:
year = 1;//reset year before 2nd while
while ( year <= useful_Life ) {
//add your code
}
Add year =1 before second loop .
Because of first loop year value is incremented . But did not set it back to one before second loop

Calculate Average Java

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));

Java clarification on += assignment operator

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

Categories

Resources