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);
Related
Write the complete java program called Temperature that includes a for loop structure, prompting the user to enter 5 temperature values. The program should add up each temperature entered within the loop and this is stored in a variable called total. Using a system statement, output the total temperature value and the average temperature value. Use the sample output below as a guide:
The total temperature =
The average temperature =
My answer is the statement below but im still getting errors:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner temp = new Scanner (System.in);
double total = 0;
for(int=1;int<=5;int++);
{
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total = temperature;
}
System.out.println("The total temperature =" +total);
System.out.println("The average temperature=" +(double)(total/5));
}
}
The OP does not state what errors you are getting exactly, but I can guess some of them are from:
for(int=1;int<=5;int++);
You cannot use int like that. It is a type and should be used like the following:
for(int itr = 1; itr <= 5; itr++) { ...
Also, the semi-colon on your for loop doesn't need to be there.
for(int i=1;i<=5;i++) {
System.out.println ("Enter temperature #" + temp +":");
double temperature = temp.nextDouble ();
total += temperature;
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Hi I am new to programming and have been assigned "Minimum Coins Program" for a class I am taking. I have finished the main code for it and it runs fine. But part of the parameters is that if the user enters a zero the program will exit, if not the program will continue looping. I have tried looking up answers but none have worked so far.
Here is what I have, but I can't seem to grasp looping. This is our first non flowchart assignment. Also if you have any suggestions on improving what I already have that would also be appreciated(this professor is a very harsh grader).
How can I get the program to exit through the user entering zero, and how can I keep the programming looping until the user enters zero. As of now the program just runs once and when I enter zero it lists the minimum amount of change
package mincoins;
import java.util.Scanner;
public class MinCoins
{
public static void main(String[] args)
{ //start code
//initialization
Scanner input = new Scanner(System.in); //create input class to get change data
int amount, quartercount = 0, dimecount = 0, nickelcount = 0, penniecount = 0;
amount = 1;
while (amount != 0)
{
System.out.println("Please Enter amount of change (1-99) or ZERO to EXIT");
System.out.println("");
amount = input.nextInt();
{
while (amount > 25)
{
amount = amount - 25;
quartercount++;
}
while (amount > 10)
{
amount = amount - 10;
dimecount++;
}
while (amount > 5)
{
amount = amount - 5;
nickelcount++;
}
System.out.println("");
System.out.println("Quarters: " + quartercount);
System.out.println("Dimes: " + dimecount);
System.out.println("Nickles: " + nickelcount);
System.out.println("Pennies: " + amount);
System.out.println("");
}
}
}//main
}//class
Your program (often) ends after 1 loop because your code reduces amount as it progresses, and if the number of pennies required is zero, the loop ends because amount is reduced to zero.
Try this:
while (true) {
// print and read amount
if (amount == 0)
break;
// rest of code
}
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????
*/
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I have a problem with the following code. It's supposed to ask the user a series of questions about students' test scores and return the average test score, this part is working okay.
My problem is that I'm supposed to use a "while-loop" which will run the program, then ask the user if they want the program to end. If they respond "no," then it should restart and ask for a new set of test scores, etc.
When I try to execute the program it works fine up until the part where it's supposed to restart. After printing out the average it will ask me if I want to close the program, but it won't allow me to type anything in. It's like the program is ending on it's own.
I've made some comments around the while loop explaining my logic as I suspect that's where the problem will be.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class testScores {
public static void main(String[] args) {
NumberFormat formatter = new DecimalFormat("####.##");
Scanner keys = new Scanner(System.in);
// Initialize endProgram to "no"
String endProgram = "no";
// Declare there's going to be a string called end
String end;
double totalScore = 0;
double averageScore = 0;
do {
// Do all of this now before you check anything
int number = getNumber(keys);
totalScore = getScores(number, keys, totalScore);
averageScore = getAverage(totalScore, number, averageScore);
printAverage(averageScore, formatter);
System.out.println("Do you want to end the program?");
end = keys.nextLine();
// Now check if end and endProgram contain the same string
} while (end.equals(endProgram));
// Apparently not
}
public static int getNumber(Scanner keys) {
System.out.println("How many students took the test?");
int number = keys.nextInt();
return number;
}
public static double getScores(int number, Scanner keys, double totalScore) {
for(int counter = 1; counter <= number; counter++) {
System.out.println("Enter their score.");
double score = keys.nextDouble();
totalScore = totalScore + score;
}
return totalScore;
}
public static double getAverage(double totalScore, int number, double averageScore) {
averageScore = totalScore / number;
return averageScore;
}
public static void printAverage(double averageScore, NumberFormat formatter) {
System.out.println("The average is " + formatter.format(averageScore));
}
}
I've tried a few different things like using a while instead of a do-while, and switching out "end" for "endProgram" to have it check "endProgram" after resetting it's value, all with no success. If anyone could help me with this it would be greatly appreciated.
You should try something along this line. The gist is that - the do-while is wrong here because it checks against a non-existant String :
String end = "";
/* rest of variables */
while (!(end.equals(endProgram) )) {
// Do all of this now before you check anything
int number = getNumber(keys);
totalScore = getScores(number, keys, totalScore);
averageScore = getAverage(totalScore, number, averageScore);
printAverage(averageScore, formatter);
System.out.println("Do you want to end the program?");
end = keys.nextLine();
// Now check if end and endProgram contain the same string
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);