import java.util.Scanner;
import java.text.DecimalFormat;
public class BasicOperator {
public static void main(String[] args) {
// this program will ask user for grades
//declare variables
DecimalFormat f = new DecimalFormat("#,##0.00");
double quiz1, quiz2, quiz3, quiz4, quiz5, sum1;
double hWork1, hWork2, hWork3, hWork4, hWork5, sum2;
double lab, fTest, extra, average1, average2, average3;
double letterGrade = 0;
//create scanner object
Scanner kb = new Scanner(System.in);
//get user quiz grade
System.out.println("Please enter your 1st quiz grade. ");
quiz1 = kb.nextDouble();
System.out.println("Please enter your 2nd quiz grade. ");
quiz2 = kb.nextDouble();
System.out.println("Please enter your 3rd quiz grade. ");
quiz3 = kb.nextDouble();
System.out.println("Please enter your 4th quiz grade. ");
quiz4 = kb.nextDouble();
System.out.println("Please enter your 5th quiz grade. ");
quiz5 = kb.nextDouble();
//get user homework grade
System.out.println("Please enter your 1st homework grade. ");
hWork1 = kb.nextDouble();
System.out.println("Please enter your 2nd homework grade. ");
hWork2 = kb.nextDouble();
System.out.println("Please enter your 3rd homework grade. ");
hWork3 = kb.nextDouble();
System.out.println("Please enter your 4th homework grade. ");
hWork4 = kb.nextDouble();
System.out.println("Please enter your 5th homework grade. ");
hWork5 = kb.nextDouble();
//get user lab exercise, final test, and extra credit grades
System.out.println("Please enter your lab grade. ");
lab = kb.nextDouble();
System.out.println("Please enter your final test grade. ");
fTest = kb.nextDouble();
System.out.println("Please enter your extra credits grade. ");
extra = kb.nextDouble();
//calculate the weighted average grade
sum1 = quiz1 + quiz2 + quiz3 + quiz4 + quiz5;
sum2 = hWork1 + hWork2 + hWork3 + hWork4 + hWork5;
average1 = lab;
average2 = fTest;
average3 = extra;
letterGrade = (sum1 / 5 * 0.15 + sum2 / 5 * 0.5 + average1 * 0.15 + average2 * 0.2 + average3 * 0.05);
//calculate the weighted average grade
sum1 = quiz1 + quiz2 + quiz3 + quiz4 + quiz5;
sum2 = hWork1 + hWork2 + hWork3 + hWork4 + hWork5;
average1 = lab;
average2 = fTest;
average3 = extra;
letterGrade = (sum1 / 5 * 0.15 + sum2 / 5 * 0.5 + average1 * 0.15 + average2 * 0.2 + average3 * 0.05);
//display the weighted average and letter grade
System.out.println("The weighted average is " + f.format(sum1 / 5 * 0.15 + sum2 / 5 * 0.5 + average1 * 0.15 + average2 * 0.2 + average3 * 0.05));
if(letterGrade >= 90 && letterGrade <= 100)
{
System.out.println("Your letter grade is A ");
}
else
if(letterGrade >= 80 && letterGrade <= 89 )
{
System.out.println("Your letter grade is B ");
}
else
if(letterGrade >= 70 && letterGrade <= 79)
{
System.out.println("Your grade is C ");
}
else
if(letterGrade >= 60 && letterGrade <= 69)
{
System.out.println("Your letter grade is D");
}
else
{
if(letterGrade < 60)
{
System.out.println("Your letter grade is F");
}
}
}
}
I've tried getting help from the tutors at my college. They kept saying the code is correct but do not know why the letter grade will not display in the console. What I am expecting is to see is Your letter grade is D after typing in 68 62 45 55 92 71 70 66 73 33 58 75 100. However, when I type in 78 75 90 85 68 90 92 84 78 93 75 81 100 I see The weighted average is 88.03 and Your letter grade is B.
Related
Im trying to get my test score program to work. Whenever I type in the pathfile to read from the text file the program would read 4 out of the 5 numbers that are there.Also, no matter what number there are it is always going to display my minimum as 0 when it is not true. Any help is truly appreciated!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Exam{
public static void main(String[] args) throws IOException {
System.out.println("Welcome!" + "\n");
//File location
System.out.println("Where is the data file:");
Scanner userInput = new Scanner(System.in);
String userFile = userInput.nextLine();
int i = 0;
int scores[] = readScores(userFile);
System.out.println("Minimum score: " + scores[0]);
System.out.println("Maximum score: " + scores[(scores.length - 1)]);
//Average Calculation
double gradesTotal = 0;
for (i=0; i<scores.length; ++i){
gradesTotal = gradesTotal + scores[i];
}
double mean = gradesTotal/scores.length;
System.out.println("Average score: " + mean);
//Mean Calculation
double median;
if (scores.length % 2 == 0)
median = ((scores[(scores.length/2) - 1]) + scores[(scores.length/2)]) / 2;
else
median = scores[(scores.length/2)];
System.out.println("Median score: " + median + "\n");
//Number of Grades
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
int gradeF = 0;
for (i=0; i<scores.length; i++)
{
if (scores[i] >= 90 && scores[i] <=100){
gradeA++;
}
else if (scores[i] <= 89 && scores[i] >=80){
gradeB++;
}
else if (scores[i] <= 79 && scores[i] >=70){
gradeC++;
}
else if (scores[i] <= 69 && scores[i] >=60){
gradeD++;
}
else if (scores[i] <= 59 && scores[i] >=1){
gradeF++;
}
}
System.out.println("Scores by letter grade: ");
System.out.println("A: " + gradeA);
System.out.println("B: " + gradeB);
System.out.println("C: " + gradeC);
System.out.println("D: " + gradeD);
System.out.println("F: " + gradeF);
}
//Reads the data from the submitted file
private static int[] readScores(String userFile) throws FileNotFoundException
{
File inputFile = new File(userFile);
Scanner stats = new Scanner(inputFile);
try {
int scores[] = new int[stats.nextInt()];
int i = 0;
while (stats.hasNext()){
scores[i] = stats.nextInt();
i++;
}
System.out.println("\n" + "There are " + (i) + " scores" + "\n");
Arrays.sort(scores);
return scores;
}
finally {
stats.close();
}
}
}
Text file:
72
31
13
39
74
Program output:
There are 4 scores
Minimum score: 0
Maximum score: 74
Average score: 2.1805555555555554
Median score: 0.0
Number of scores by letter grade:
A: 0
B: 0
C: 1
D: 0
F: 3
int scores[] = new int[stats.nextInt()];
here you take the first of your values and then you dont have it where you need it.
That is probably also the reason why your calculations are so messed up. you create an array of lenght 72 and use that lenght for the number of values.
Maybe you want to use a list instead. It allows you to add as many values as you want without specifying a number like you have to do when you use an array.
NOT ABLE TO CORRECT THIS CODE..
import java.text.DecimalFormat;
public class PeopleWeights {
public static void main(String[] args) {
DecimalFormat decFor = new DecimalFormat("0.00");
int i = 0;
int n = 5;
double arr[]=new double[n];
for(i = 0; i < n; i++){
System.out.println("Enter weight " + (i+1)+": ");
}
System.out.print("\nYou entered: ");
for(i = 0; i < n; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
double total = 0;
double max = 0;
for(i=0; i<n; i++){
if(max < arr[i]){
max = arr[i];
}
total = total + arr[i];
}
DecimalFormat df = new DecimalFormat("#.##");
double average = total/n;
System.out.println("Total weight: "+ df.format(total));
System.out.println("Average weight: "+ df.format(average));
System.out.println("Max weight: "+ df.format(max));
return;
}
}
THIS ARE THE ERRORS I KEEP GETTING.
Compare output
0/1
Input 236
89.5
142
166.3
93
Your output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 0.0 0.0 0.0 0.0 0.0
Total weight: 0
Average
Expected output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 236.0 89.5 142.0 166.3 93.0
Compare output
0/1
Input 123.4
56
98
174
215.8
Your output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 0.0 0.0 0.0 0.0 0.0
Total weight: 0
Average
Expected output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 123.4 56.0 98.0 174.0 215.8
Compare output
0/1
Input 236
89.5
142
166.3
93
Your output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 0.0 0.0 0.0 0.0 0.0
Total weight: 0
Average weight: 0
Max weight: 0
Expected output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 236.0 89.5 142.0 166.3 93.0
Total weight: 726.8
Compare output
0/1
Input 236
89.5
142
166.3
93
Your output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 0.0 0.0 0.0 0.0 0.0
Total weight: 0
Average weight: 0
Max weight: 0
Expected output starts with Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 236.0 89.5 142.0 166.3 93.0
Total weight: 726.8
Average weight: 145.35999999999999
Compare output
0/1
Input 236
89.5
142
166.3
93
Your output Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 0.0 0.0 0.0 0.0 0.0
Total weight: 0
Average weight: 0
Max weight: 0
Expected output Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 236.0 89.5 142.0 166.3 93.0
Total weight: 726.8
Average weight: 145.35999999999999
Max weight: 236.0
Compare output
0/1
Input 123.4
56
98
174
215.8
Your output Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 0.0 0.0 0.0 0.0 0.0
Total weight: 0
Average weight: 0
Max weight: 0
Expected output Enter weight 1:
Enter weight 2:
Enter weight 3:
Enter weight 4:
Enter weight 5:
You entered: 123.4 56.0 98.0 174.0 215.8
Total weight: 667.2
Average weight: 133.44
Max weight: 215.8
You are not taking the input from the user. Use Scanner or BufferedReader to get what the user is entering at the console.
Read this question for more details:
How can I get the user input in Java?
You are not getting the output because you are not taking the input from the user. what you have to do is to get the input to a variable and add it to the array. To get the input from the console you can use Scanner.
Below is the edited code. Try this, I think you can get the output.
import java.text.DecimalFormat;
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
DecimalFormat decFor = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
int i = 0;
int n = 5;
double arr[]=new double[n];
for(i = 0; i < n; i++){
System.out.println("Enter weight " + (i+1)+": ");
double weight = Double.parseDouble(sc.nextLine());
arr[i] = weight;
}
System.out.print("\nYou entered: ");
for(i = 0; i < n; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
double total = 0;
double max = 0;
for(i=0; i<n; i++){
if(max < arr[i]){
max = arr[i];
}
total = total + arr[i];
}
DecimalFormat df = new DecimalFormat("#.##");
double average = total/n;
System.out.println("Total weight: "+df.format(total));
System.out.println("Average weight: "+df.format(average));
System.out.println("Max weight: "+df.format(max));
return;
}
}
still getting a different error.Output 4, "Max weight:2".36 is highlighted with orange, Average weight: 145.3"6"- 6 is highlighted with orange EXPECTED OUTPUT Average weight: 145.3"5999999999999" the " " is highlighted. COMPARE OUTPUT 5: Your output Average weight: 145.3"6" - " " IS HIGHLIGHTED....expected output Average weight: 145.3"5999999999999" Max weight: 23"6.0" the " " are highlighted. Do you have a clue on how to fix it.
This is due to the use of DecimalFormat.
try:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = 0;
int n = 5;
double total = 0;
double max = 0;
double arr[]=new double[n];
for(i = 0; i < n; i++){
System.out.println("Enter weight " + (i+1)+": ");
double weight = Double.parseDouble(sc.nextLine());
arr[i] = weight;
if(max < arr[i]){
max = arr[i];
}
total = total + arr[i];
}
System.out.printf("%nYou entered: ");
for(i = 0; i < n; i++){
System.out.printf("%s ", arr[i]);
}
System.out.println();
double average = total/n;
System.out.printf("Total weight: %.1f%n", total);
System.out.println("Average weight: " + average);
System.out.printf("Max weight: %.1f%n" + max);
return;
}
}
This is what I used:
import java.util.Scanner;
/**
* Handles an array of peoples weights.
*/
public class PeopleWeights
{
// static variables that we can access in our static methods.
static final int WEIGHT_ARRAY_SIZE = 5;
static double[] weightsOfPeople = new double[WEIGHT_ARRAY_SIZE];
static double weightElement;
static double sum = 0.0;
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args)
{
GetWeights();
WeightsSum();
WeightsAverage();
WeightsMax();
return;
}
/**
* Takes input for the weights and store them inside our array.
*/
public static void GetWeights()
{
int i = 0; // Local count variable.
// Take input for the weights and store them in our array.
for(i = 0; i < WEIGHT_ARRAY_SIZE; i++)
{
System.out.println("Enter weight " + (i + 1) + ": ");
weightElement = scnr.nextDouble();
weightsOfPeople[i] = weightElement;
}
// Display what the user entered
System.out.print("\nYou entered: ");
for(i = 0; i < WEIGHT_ARRAY_SIZE; i++)
{
System.out.print(weightsOfPeople[i] + " ");
}
return;
}
/**
* Gets the sum of our weights and then displays that sum.
*/
static void WeightsSum()
{
int i = 0;
for(i = 0; i < WEIGHT_ARRAY_SIZE; i++)
{
sum += weightsOfPeople[i];
}
System.out.println("\nTotal weight: " + sum);
return;
}
/**
* Gets the average of our weights and then displays that average.
*/
static void WeightsAverage()
{
double averageWeight = 0.0;
// Convert WEIGHT_ARRAY_SIZE to a double for good calculation.
averageWeight = sum / (double)WEIGHT_ARRAY_SIZE;
System.out.println("Average weight: " + averageWeight);
return;
}
/**
* Gets the max of our weights and then displays that max.
*/
static void WeightsMax()
{
int i= 0;
double maxWeight = 0.0;
for(i = 0; i < WEIGHT_ARRAY_SIZE; i++)
{
if(weightsOfPeople[i] > maxWeight)
{
maxWeight = weightsOfPeople[i];
}
}
System.out.println("Max weight: " + maxWeight);
return;
}
}
When try to run I got wrong answer. What's wrong in my program?
Got answer is only for discount_amount not able to get total amount.
Scanner input = new Scanner(System.in);
double dicount_amount = 0;
double discount1 = 0;
double total = 0;
System.out.println("Enter the cost of the software: ");
double cost = input.nextDouble();
System.out.println(" Enter the quantity sold: ");
int quantity = input.nextInt();
if (cost > 0 && quantity > 0){
if(quantity >= 10 && quantity >=19){
discount1 = 20/100;
}
else if(quantity >= 20 && quantity >=49){
discount1 = 30/100;
}
else if(quantity >= 50 && quantity >=99){
discount1 = 40/100;
}
else if(quantity <=100){
discount1 = 50/100;
}
}
else {
System.out.println( " please enter valid input ");
}
double total1 = cost * quantity;
dicount_amount = total1 * discount1;
total= total1 - dicount_amount;
System.out.println("Total Cost: " + total);
}
Simplest thing you can do is not to divide discount1 = 20/100;, instead that you can set directly value discount1 = 0.2;
Also you should check your if statement
Example:
if(quantity >= 10 && quantity >=19)
is equal to
if(quantity >=19)
I think you want to check if quantity is between. So you should use
if(quantity >= 10 && quantity <=19)
Guess what was your mistake? You were dividing int by int and you are excepting a double result. Typecast the division to double or do 20.0/100. Also, I assume you are want to give a discount if the quantity is between 10 and 19. What you have been doing doesn't make sense because every time you run your program it will never fall in else if() statement because you are setting quantity>=19 in if statement.
here are few changes I made in your code :
Scanner input = new Scanner(System.in);
double dicount_amount = 0;
double discount1 = 0;
double total = 0;
System.out.println("Enter the cost of the software: ");
double cost = input.nextDouble();
System.out.println(" Enter the quantity sold: ");
int quantity = input.nextInt();
if (cost > 0 && quantity > 0){
if(quantity >= 10 && quantity <=19){
discount1 = (double)20/100;
}
else if(quantity >= 20 && quantity <=49){
discount1 = (double)30.0/100;
}
else if(quantity >= 50 && quantity <=99){
discount1 = (double)40.0/100;
}
else if(quantity >=100){
discount1 = (double)50.0/100;
}
}
else {
System.out.println( " please enter valid input ");
}
double total1 = cost * quantity;
dicount_amount = total1 * discount1;
total= total1 - dicount_amount;
System.out.println("Total Cost: " + total);
Output :
Enter the cost of the software:15
Enter the quantity sold:16
Total Cost: 192.0
So I have Been working on a Program and it has been awhile since I have last used java. I was wondering how to get my program to accept decimals. I have tried looking it up but I couldn't find anything helpful and anything I really understood.Below is what I have done so far...
package test;
import java.util.Scanner;
/**
*
* #author Thao
*/
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
double cash; // double makes it allow decimals
int hundred;
int twenty;
int ten;
int toonies ;
int lonies;
int quarters;
int dimes;
int nickels;
int pennies;
int money;
int change;
System.out.println();// blank line
System.out.print("Hello ");
System.out.println();
System.out.println("Please enter a number with no decimal places ");
cash = input.nextInt(); // read first integer
System.out.println("you have Entered "+cash);
hundred = 100;
change = (int)hundred - (int)cash;
System.out.println("The change from $100.00 is:" + (double)change);
change = 100 * change; // multiply cash by 100
money = (int)change; //cash is now a int
twenty = money / 2000;
money = money - (twenty * 2000);
toonies = money / 200; // money is multiplied by 100 than / by 200
money = money - (toonies * 200); // ex. money = 1586 - (7.93 * 200 )
lonies = money / 100 ;
money = money - (lonies * 100);
quarters = money / 25;
money = money - (quarters * 25);
dimes = money / 10;
money = money - (dimes * 10);
nickels = money / 5;
money = money - (nickels * 5);
pennies = money / 1;
money = money - (pennies * 1);
if(twenty>0){
System.out.println();
System.out.print("You will have this many Twenties ");
System.out.print(twenty + ".");
}
else{
}
if(toonies>0){
System.out.println();
System.out.print("You will have this many Toonies ");
System.out.print(toonies + ".");
System.out.println();
}
else{
}
if(lonies>0){
System.out.print(" You will have this many Lonies ");
System.out.print(lonies + ".");
System.out.println();
}
else{
}
if(quarters>0){
System.out.print(" You will have this many quarters ");
System.out.print(quarters + ".");
System.out.println();
}
else{
}
if(dimes>0){
System.out.print(" You will have this many dimes ");
System.out.print(dimes + ".");
System.out.println();
}
else{
}
if(dimes>0){
System.out.print(" You will have this many nickels ");
System.out.print(nickels);
System.out.println();
}
else{
}
if(pennies>0){
System.out.print(" You will have this many pennies ");
System.out.print(pennies);
System.out.println();
}
else{
}
System.out.println();
System.out.println("Thank you for using my app ");
}
}
You can use double or float for the variable's data type. To read a double from your input you would do:
double cash = input.nextDouble();
or
float cash = input.nextFloat();
I am creating a program that calculates users grades based on their input. All is good except that I need to deal with users inputting invalid entries.
Example: The user enters three exam scores on a single line (95 90 87 for example). If one of these scores is negative (95 90 -87) I need the program to NOT enter those three scores and assign a letter grade and instead prompt the user to re-enter the scores correctly.
Here is my code:
public class GradeCalculator {
public static void main(String[] args) {
int classSum = 0; // variable used to hold sum of entire classes exams
int classExams = 0; // variable used to hold number of exams taken by whole class
Scanner s = new Scanner(System.in);
System.out.println("Welcome to Gradecalculator!");
System.out.println("Please enter the number of students:");
int students = s.nextInt();
System.out.println("Please enter the number of exams:");
int exams = s.nextInt();
int i = 0;
int studentnumber = 1;
int sum = 0;
while (i < students) { // loop until it matches number of students entered above
i++;
sum = 0;
System.out.println("Enter student " + studentnumber++ + "'s name :");
String studentname = s.next();
System.out.println("Enter exam scores :");
int input = 0;
for (; input < exams; input++) {
int n = s.nextInt();
sum+=n;
if (n < 0) {
System.out.println("Invalid exam scores, reenter: "); //if one of the scores entered is negative, display message
}
}
double average = sum/exams; // assign letter grade based on average of exams
if (average <= 100 && average >= 90) {
System.out.println("Letter grade: A");
System.out.println(studentname + " gets 4 stars! ****");
} if (average <= 89 && average >= 80) {
System.out.println("Letter grade: B");
System.out.println(studentname + " gets 3 stars! ***");
} if (average <= 79 && average >= 70) {
System.out.println("Letter grade: C");
System.out.println(studentname + " gets 2 stars! **");
} if (average <= 69 && average >= 60) {
System.out.println("Letter grade: D");
System.out.println(studentname + " gets 1 star! *");
} if (average <= 59) {
System.out.println("Letter grade: F");
System.out.println(studentname + " gets 0 stars!");
}
classSum += sum; // add sum of this student's scores to the classSum
classExams += exams; // add exams taken by this student to amount of exams taken by whole class
}
int classAverage = classSum/classExams; // compute class average
System.out.println("Class statistics:");
System.out.println("\tAverage: " + classAverage);
}
}
Clearly I have this code in the wrong place:
if (n < 0) {
System.out.println("Invalid exam scores, reenter: "); //if one of the scores entered is negative, display message
}
}
Because this is the output I get when entering a negative score:
Enter exam scores :
70 70 -70
Invalid exam scores, reenter:
Letter grade: F
joe gets 0 stars!
As you can see, it still assigns a letter grade and stars and asks for the next student's name. I need it to instead ask to re-enter this student's scores. Can't figure out how to do that.
You can subtract one from the input inside that for loop so that it stays in that loop and other inputs aren't wiped out (and also make sure that the sum doesn't add those negative inputs)
int input = 0;
for (; input < exams; input++) {
int n = s.nextInt();
if (n>=0)
sum+=n;
else {
input--;
System.out.println("Invalid exam score entered, reenter: ");
}
}
EDIT: Use interactive input, which should be more user friendly.
You need to reset your loop counter to start the loop again:
// Delete first output and counter variable initialization before loop
for (int input = 1; input < exams; input++) {
System.out.println(String.format("Enter %d. exam score: ", input + 1));
int n = s.nextInt();
if (n < 0) {
System.out.println("Invalid value (must be positive)!");
input--; // Reenter last value
} else {
sum+=n; // Only use correct scores.
}
}