Please Help....
I have been trying to figure this out for hours...
I have this program and I have to print out everything in the loop in the JoptionPane. But when the loop is done, the values are reset so how do I get to save all the totals and the put into the JOptionPane.
Here is the question:
PARTA Write an application called ProjectA.java
In the main
a. It will prompt the reviewer to enter a main course
Example:
Enter the luncheon main course: Burger, Hotdog, Pizza or Grilled Cheese
b. It will declare appropriate variables to store his data
c. It will create a Scanner object
write a while loop controlled on the amount entered being greater or equal to 0 (or not a -1)
then write a while loop to prompt the reviewer to enter all lunch costs as surveyed separated by spaces, terminated with a -1
Example:
Enter all costs for the luncheon main dish Grilled Cheese separated by spaces, terminate with a -1:
1.95 2.55 0.99 -1
within the loop, add the amounts to the accumulating total, increment the numItems counter and read in the next amount using the scanner
when the loop ends , decrease counter so that the -1 does not count as a lunch, calculate the average cost and output in a System.out.println statement the name, number of lunches surveyed, total money collected and the average cost of that lunch. Do the same output in a JOptionPane – see sample execution below
PartB
Copy your ProjectA.java file into one named ProjectB.java
Modify the code so that it prompts the reviewer to enter the maximum number of lunches in his survey using a JOptionPane
It will now need variables for a counter for the actual number of lunches and a maximum number of lunches
It will enclose the prompt for the luncheon main dish name and the while loop above in an outer loop controlled on the maximum number of lunches to be surveyed
When the inner loop ends, increment the number of lunches counter and reset the average, total and numItem back to zero, then end the outer loop
Your intermediate output will look like the JOptionPane - so I have to print out all the info in the Joptionpane - and if they say to reset? That is where I am stuck.
My program so far...
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.text.NumberFormat;
import java.util.Locale;
public class LunchSurvey
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance(Locale.US);
double averagecost = 0.0;
double totalcollected = 0.0;
double amount = 0.0;
double burgersurvey = 0.0;
double burgertotal = 0.0;
double burgeraverage = 0.0;
int numofitems = 0;
int maxlunch = 0;
String lunchname = "";
String lunchtotal = "";
lunchtotal = JOptionPane.showInputDialog("Please enter the maximum number of lunches in your survey");
// lets say 3
maxlunch = Integer.parseInt(lunchtotal);
for (int j = 1; j <= maxlunch; j++)
{
// Getting the order
lunchname = JOptionPane.showInputDialog(null,"Enter lunch name: Burger, Hotdog, Pizza or Grilled Cheese ", "Input", JOptionPane.QUESTION_MESSAGE);
System.out.println("For " + lunchname + " enter all amounts collected separated by spaces and terminated with a -1" );
// lets say the amounts are 1.00 1.00 2.00 -1
while (amount >= 0)
{
totalcollected = totalcollected + amount;
numofitems = numofitems + 1;
amount = keyboard.nextDouble();
}
numofitems--;
averagecost = totalcollected / numofitems;
System.out.println(lunchname + ": Total surveyed: " + numofitems + " Total collected: " + money.format(totalcollected) + " Average Cost: " + money.format(averagecost));
totalcollected = 0;
numofitems = 0;
amount = 0;
}
/*Here is where I think that I am to print out all the lists same things like the println, all in one JOption pane. But if it clears all of the numbers to do another lunch number, then what is the secret to printing all of the lunch numbers in a JOptionPane? JOptionPane.showMessageDialog (null, lunchname????
*/
}
}
Related
I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.
Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.
Ex:
Inputs: 10000 30000 50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000
**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();
Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();
//Declarations
int total = 0;
int average = 0;
//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
System.out.println("Enter the income of job #" + i + " : ");
arrayOfIncomes[i] = scan.nextInt();
total = total + arrayOfIncomes[i];
}
average = total/jobNum;
//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] > max) {
max = arrayOfIncomes[i];
}
}
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] < min) {
min = arrayOfIncomes[i];
}
}
//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
System.out.println("");
} else {
System.out.println("Goodbye.");
}
//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);
//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
out.close();
}
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding. You will also need to instantiate three integer variables: total, max and min, each at zero.
For every iteration of the loop, you should add the following code:
jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];
When you print the average, you can cast the formula average = total/jobNum. You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.
Example:
double ave = (double) sum / jobNum;
I'm just starting to learn my first programming language as of yesterday, so I'm writing simple test programs from my java book.
What I'm attempting to do is to have a user enter a static monthly investment and how many months they will be saving for, then display their total savings after that period of time.
when I compile the program it says that in system.out.println at the end of the program that total has not been initialized. I have tried initializing total in just the loop but I figured that would put the scope of it in the loop So I tried initializing it at the top and figured it runs through the loop until the condition is met but doesn't go back to the top of the program to put the value back in so I make another variable at the end of the loop to hold the total at the end of the loop. What's Wrong with my logic
thank you for the help!
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 0){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
thanks everyone for the help it now compiles however it seems when going through the math it doesn't take in account the first month of savings for example if I do $100 each month its total at the end is %502.08 which I don't believe is right
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount = 0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 1){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
monthCountDown = monthCountDown - 1;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
set totalAmount = 0,that will instialize it, let me know if this fixes the problem
when you declare it declare it like this double totalAmount = 0;
try 2 steps:
double totalAmount; ==> double totalAmount = 0;
while (monthCountDown > 0); ==> while (monthCountDown-- > 0);
Hava a nice day, my friend.
This problem is a little intricate although the compiler (javac program) provides following helpful message:
Compound.java:33: error: variable totalAmount might not have been
initialized double total = totalAmount;
What could be happening you may wonder. The easy answer is to go to line 20 in your program and initialize the value of totalAmount to 0. Then your program would compile.
The reason the compiler does that is rather complicated, but you can reason about it this way:
What if, just what if the while loop did not get run even once (as written, in your program, opposite is happening as you will soon figure out that you are forgetting something about the loop variable)? Then Java would execute the (next) statement double total = totalAmount; and the way this assignment statement is executed is roughly like this:
read the variable on the right side of =, that is totalAmount in a temporary location
transfer the contents of that location to the memory for the variable on the left side of =, i.e. total.
Now, Java does not like to read a local variable's (such as totalAmount) value that is never written to because it may contain some garbage value. When you initialize it with a value like 0, this problem goes away.
First of all there is no need of using intitalAmount and totalAmount. Because each time you are inserting same values to them. Secondly if you make
monthCountdown > 1
then it will count a month less. Because suppose you are counting for 6 months. Now for monthCountdown > 1 the loop will iterate for 5 times and calculate interest for 5 times. Which I believe is not the logic you want to implement.
So it should be,
monthCountdown > 0
Lastly your mathematical logic is not correct because each time you are calculating the interest on the monthly value and adding it with the previous balance. But it should be like each time interest should be calculated on the total current balance.
while (monthCountDown > 0){
totalAmount = ( amountSavedMonthly + totalAmount ) * monthlyInterestRate;
}
Please let me know if any concern.
First of all, it isn't necessarily the case that totalAmount will not be initialized. However, depending on the user input, it is POSSIBLE that totalAmount will not have been initialized, which will then throw an exception when the program attempts to assign the value of totalAmount to total. To avoid this, you need to ensure that totalAmount gets initialized, which is easy to do. When you declare totalAmount, simply assign 0 as its value.
You also have a problem with your while loop. Because the value of monthCountDown is never changed within the loop, there is no way for the condition monthCountDown > 0 to become false. I'm assuming you intended for monthCountDown to be reduced by 1 each time the loop is run, so you should include monthCountDown--; within the loop to prevent it from becoming an infinite loop.
Initialize totalAmount to 0...
Make in while condition greater than 1..
cricket-007 is right about initializing totalamount = 0; But it looks like your while loop keeps going. Try this!
changed your arrow key from > to <, on the while loop
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount =0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown < 0) {
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
I am making a simple average grade calculator. Basically takes in users mark and the percentage of that module and displays the average percentage. The program does work but it has a few glitches which happens in the while loop.
The while loop should end as soon as the user enters any value under -1 but it continues on for a few times and then exits the while loop. Also, it first lets the user enter a number to ensure to start the while loop and then the text 'Enter Mark' comes up which makes the user enter their marks again. Im trying to make the while loop automatically start but dont know how too.
import java.util.ArrayList;
import java.util.Scanner;
public class percentage {
static ArrayList<Double> marks = new ArrayList<>();
static ArrayList<Double> percentage = new ArrayList<>();
static Scanner input = new Scanner(System.in);
static void addingToMarks(double currentmark) {
marks.add(currentmark);
}
public static void main(String[] args) {
System.out
.println("Type in the number of marks you got \n"
+ "in the module. And then type the percentage weight of it.\n"
);
double exitLoop = input.nextDouble();
while (exitLoop > -1) {
System.out.println("Type in your marks");
marks.add(input.nextDouble());
System.out
.println("Type in the weighted percentage of the module: ");
percentage.add(input.nextDouble());
exitLoop = input.nextDouble();
}
System.out.println(percentage);
System.out.println(marks);
System.out.println("Your average percent for the module is: "
+ gradeCalculate());
}
static double gradeCalculate() {
double totalaverageweight = 0;
for (int x = 0; x < marks.size(); x++) {
totalaverageweight += ((marks.get(x) / 100) * percentage.get(x));
}
return totalaverageweight;
}
}
I think a do... while loop will work in this case since the test condition will happen at the end of the loop
do{
////your code goes here
}while(exitLoop!=-1);
Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}
This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result
How do you formatt output?
my code is:
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
int cuToComp;
int cuPerTerm;
public static void main(String[] args) {
final double COST = 2890.00; //flat-rate tuition rate charged per term
final int MONPERTERM = 6; //number of months per term
int cuToCompTotal = 0;
int numTerm;
int numMonToComp;
double tuition;
//prompt for user to input the number of CUs for each individual course remaining.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
//add all CUs from individual courses to find the Total number of CUs left to complete.
while (cuToComp > 0)
{
cuToCompTotal += cuToComp;
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
cuToComp = in.nextInt();
}
System.out.println("The total number of CUs left is " + cuToCompTotal);
//prompt for user to input how many CUs they plan to take per term.
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm < 12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
{
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
while(cuPerTerm < 12){
System.out.print("How many credit units do you intend to take per term? ");
cuPerTerm = in.nextInt();
}
}
//Calculate the number of terms remaining, if a remain is present increase number of terms by 1.
numTerm = cuToCompTotal/cuPerTerm;
if (cuToCompTotal%cuPerTerm > 0)
{
numTerm = numTerm + 1;
}
System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");
//Calculate the number of Months left to complete
numMonToComp = numTerm * MONPERTERM;
System.out.println("Which is " + numMonToComp + " Months. ");
//calculate the tuition cost based on the number of terms left to complete.
tuition = numTerm * COST;
System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
}
}
the final line System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
I need to format it so that it has two decimal places (amount.00) as well as commas for place holders.
I've tried
System.out.printf("Your Total Tuition Cost is: " + "$%.2f" + tuition +" . ");
however I get an error!!!!
so I added
NumberFormat my = NumberFormat.getInstance(Locale.US);
my.setMaximumFractionDigits(2);
my.setMinimumFractionDigits(2);
String str = my.format(tuition);
System.out.printf("Your Total Tuition Cost is: $", (NumberFormat.getInstance(Locale.US).format(tuition)));
which outputs
Your Total Tuition Cost is: $BUILD SUCCESSFUL (total time: 13 seconds)
What is my mistake???
also there will never be a decimal value the xx.00 will always be .00 (does that matter?)
The best alternative is to use the NumberFormat class, which is better when you want to customize things like decimal separators and placeholders.
Since the output you seem to be looking for is the US standard, you can simply use this:
NumberFormat my = NumberFormat.getInstance(Locale.US);
my.setMaximumFractionDigits(2);
my.setMinimumFractionDigits(2);
String str = my.format(123456.1234);
Another alternative that could be used if it weren't for your placeholder-requirement is to use String.format-method.
An easy way in many cases is to use the String.format method, this line will output like 123456.12
String.format("Your total cost is : $%.02f", tuition);
For some reason, none of the answers here have mentioned currency formatting:
System.out.println("Your Total Tuition Cost is: " +
NumberFormat.getCurrencyInstance().format(tuition));
You can also do the same thing with MessageFormat, which you might or might not find easier to use:
System.out.println(
MessageFormat.format("Your Total Tuition Cost is: {0,number,currency}",
tuition));