So I have my code working to tell me what the grade is for the average, however, what I need it to actually do is tell me what the grade is for each individual grade itself, example user enters for test1 80, I need it to say that the grade is a B and so on. This is what I have so far. Im not sure if I can even put multiple variables into 1 if else statement or not, or if Ill have to have 5 different else if statements.
import java.util.Scanner; //user input
import java.text.DecimalFormat; //formats decimal places
/*This program is made to recieve 5 test grade inputs from the
user and then calculate their average and return their grade.
*/
public class Lab
{
public static void main(String[] args)
{
//place holders for test scores
double test1,test2,test3,test4,test5;
System.out.println("Enter 5 of your test grades: ");
//create scanner for user imput
Scanner keyboard = new Scanner(System.in);
test1 = keyboard.nextDouble();
test2 = keyboard.nextDouble();
test3 = keyboard.nextDouble();
test4 = keyboard.nextDouble();
test5 = keyboard.nextDouble();
keyboard.nextLine();
//calls method 1
double average = calcAverage(test1, test2, test3, test4, test5);
//calls method 2
getGrade(average);
//formats how the average will be displayed
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("The average is: " + df.format(average));
System.exit(0);
}
/*
The calcAverage method takes the test inputs from the
user and divides them by 5 getting the average of all 5.
*/
public static double calcAverage(double test1, double test2, double test3, double test4, double test5)
{
double average = (test1 + test2 + test3 + test4 + test5) / 5;
return average;
}
/*
The getGrade method will take what was produced in the calcAverage method
and find out where the average falls, thus giving the user his/her grade.
*/
public static void getGrade(double average)
{
if (average>90)
{
System.out.println("You have an A");
}
else if (average>=80)
{
System.out.println("You have a B");
}
else if (average>=70)
{
System.out.println("You have a C");
}
else if (average>=60)
{
System.out.println("You have a D");
}
else if (average<60)
{
System.out.println("You have a F");
}
}
}
Your getGrade() should probably return the grade. Something like,
public static String getGrade(double average)
{
if (average>90)
{
return "A";
}
else if (average>=80)
{
return "B";
}
else if (average>=70)
{
return "C";
}
else if (average>=60)
{
return "D";
}
else
{
return "F";
}
}
Then you call it for an individual test (or the average) -
System.out.printf("You got a %s on test1.", getGrade(test1));
Just call getGrade on individual tests like shown below and rename the getGrade parameters name to score instead of average (this is just for readability)
import java.util.Scanner; //user input
import java.text.DecimalFormat; //formats decimal places
/*This program is made to recieve 5 test grade inputs from the
user and then calculate their average and return their grade.
*/
public class Lab
{
public static void main(String[] args)
{
//place holders for test scores
double test1,test2,test3,test4,test5;
System.out.println("Enter 5 of your test grades: ");
//create scanner for user imput
Scanner keyboard = new Scanner(System.in);
test1 = keyboard.nextDouble();
test2 = keyboard.nextDouble();
test3 = keyboard.nextDouble();
test4 = keyboard.nextDouble();
test5 = keyboard.nextDouble();
keyboard.nextLine();
//calls method 1
double average = calcAverage(test1, test2, test3, test4, test5);
//calls method 2
getGrade(average);
// Gets grade for individual tests
getGrade(test1);
getGrade(test2);
getGrade(test3);
getGrade(test4);
getGrade(test5);
//formats how the average will be displayed
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("The average is: " + df.format(average));
System.exit(0);
}
/*
The calcAverage method takes the test inputs from the
user and divides them by 5 getting the average of all 5.
*/
public static double calcAverage(double test1, double test2, double test3, double test4, double test5)
{
double average = (test1 + test2 + test3 + test4 + test5) / 5;
return average;
}
/*
The getGrade method will take what was produced in the calcAverage method
and find out where the average falls, thus giving the user his/her grade.
*/
public static void getGrade(double score)
{
if (average>90)
{
System.out.println("You have an A");
}
else if (average>=80)
{
System.out.println("You have a B");
}
else if (average>=70)
{
System.out.println("You have a C");
}
else if (average>=60)
{
System.out.println("You have a D");
}
else if (average<60)
{
System.out.println("You have a F");
}
}
}
I would put your tests into an Array:
double[] myTests = {test1, test2, test3, test4, test5};
and then iterate through:
for(int i=0; i<myTest.length; i++){
getGrade(myTests[i]);
}
as for your getGrade method you might want to just return a char for each grade: A, B, C, ect and then only have one System.out.print statement. And my personal preference in a situation like this is to use a switch-case instead of if-else. Clearly this is school work though so I don't know what education level you are expected to code with
For some more OO design you can create a Test class and encapsulate the data within it:
public class Test
{
public double Score;
public String GetGrade()
{
if (this.Score > 90)
{
return "A";
}
else if (this.Score >= 80)
{
return "B";
}
else if (this.Score >=70)
{
return "C";
}
else if (this.Score >= 60)
{
return "D";
}
else
{
return "F";
}
}
}
I assume your question includes the instruction to just accept 5 test scores so we can use an array of size 5 (otherwise you could create an ArrayList and just add to it for each input):
Test[] tests = new Test[5];
Rather than accepting 5 inputs in a row, a better solution may be to print out the grade as each score is entered:
System.out.println("Enter test scores:");
//create scanner for user imput
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < tests.length; i++)
{
System.out.printf("Test %d: ", i + 1);
tests[i].Score = keyboard.nextDouble();
System.out.printf("Grade is %s", tests[i].GetGrade());
}
Your calcAverage can then be more generic as well rather than hardcoding the number 5:
public static double calcAverage(Test[] tests)
{
double scoreSum;
for (int i = 0; i < tests.length; i++)
{
scoreSum += tests[i].Score;
}
return scoreSum / test.length;
}
Related
I have been working on these programs.
They don't have any errors but I need to make them return a result in order for them to work properly. More specifically to add a method that returns a result.
The instructions were the following:
Write a program that is split in to methods at least one of which returns a result
This is the first program:
import java.util.Scanner; // Needed to make Scanner available
public class onlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
This is the second program:
import java.util.Scanner; // Needed to make Scanner available
public class BodyAge {
public static void main(String[] args) {
CalculateAge();
} // END of main method
// Inserting age and heart rate and stretch distance
//and calculates the body age based on conditions
public static void CalculateAge() {
int age;
int heartRate;
int stretch;
Scanner input = new Scanner(System.in);
System.out.print("What is your age? ");
age = input.nextInt();
System.out.print("What is your heart rate? ");
heartRate = input.nextInt();
if (heartRate <= 62) {
age -= 5; // block of code to be executed if condition1 is true
} else if (62 <= heartRate && heartRate <= 64) {
age--; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (65 <= heartRate && heartRate <= 70) {
age++; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age += 2; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.print("How far can you stretch? ");
stretch = input.nextInt();
if (stretch <= 20) {
age += 4; // block of code to be executed if condition1 is true
} else if (20 <= stretch && stretch <= 32) {
age++; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (33 <= stretch && stretch <= 37) {
age = age + 0; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age = age + 3; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.println("Your body's age is " + age);
} //END of CalculateAge
}
Here's an example of one possible way you might consider breaking up a class into using some methods with returns. Let's take your first class for this example. You frequently are taking input from your user.
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
This could potentially be broken out into another method for condensed reusability.
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
From there you can replace your calls for information with this method. Full example:
import java.util.Scanner; // Needed to make Scanner available
public class OnlineCalculator {
public static void main(String[] args) {
calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
a = askForInt(scanner, "Amount of loan at start of year? ");
b = askForInt(scanner, "Amount paid off this year? ");
scanner.close();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
}
First program,
You could for example split your calculate() method into 2 method and move your int variable "a" and "b" in the main() method
1ST method:
void getInput(){
...
}
2nd method:
int calculateAndreturnResult(int a, int b) {
...
}
Finally use those method in the main() and print the result :
getInput();
int result = calculateAndreturnResult(){
}
system.out.println(result);
So how Java will work is the compiler will only read commands from the "main" method. So in the case of the calculator, Java will see that you want to run the calculator method, which has a return type of "void" It goes PUBLIC (meaning other classes can see and interact with it) STATIC (basically meaning that the method belongs to the class itself, not instances of the class) VOID ( this is your return type, meaning after the method is done, what is being put back into main) so if you want a method to return something, you need to change the return type. In the case of your calculator project something like this would split it up into 2 methods one of which returns something:
public class OnlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
//this will return an int type
public static int loanDifference(int amountOwed, int amountPaid) {
int c = amountOwed - amountPaid;
return c;
}
// this will return a double type
public static double newAmountOwed(double d) {
double e = (int)d / 10.0;
return e;
}
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
scanner.close();
int c = loanDifference (a, b);
double d;
d = c * 1.07 * 10.0;
final double e = newAmountOwed(d);
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
seems like they want you to put more code in, but the idea is that they want you to know how to use methods that work together to make something at the end!
use the same idea with the other one!
I do not understand how the for loop works and what it is doing. The code is for a project that averages a users test scores and is based on how many test scores he wants to input.
I know that the program is returning as many inputs the user asks but I do not know how the for loop is doing that. I am trying to understand how it operates and what it is doing.
import java.util.Scanner;
public class average
{
public static String getLetterGrade(double average) {
if (average < 60) {
return "F";
} else if (average < 70) {
return "D";
} else if (average < 80) {
return "C";
} else if (average < 90){
return "B";
}
else;{
return "A";
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Welcome, please type your first name. ");
String name = scan.nextLine();
System.out.println("Welcome, please type your last name. ");
String last = scan.nextLine();
int n;
System.out.println("How many tests would you like the average of?");
n = scan.nextInt();
while(n<0)
{
System.out.println("Invalid input.");
System.out.println("How many tests would you like the average
of?");
n = scan.nextInt();
}
double sum = 0, grade;
System.out.println("Enter " + n + " scores.");
for(int i = 0;i<n;i++)
{
grade = scan.nextDouble();
sum += grade;
}
double average = (sum/n);
System.out.println("Okay " + name.charAt(0) + last.charAt(0) + ", Your
average score is " + (average));
System.out.println("Your letter grade is " + getLetterGrade(average));
}
}
The program runs normally and does not have errors. I am trying to understand how the for loop is working.
the for loop is trying to get the numbers(scores) which we want to calculate average on them.
for loop runs for n times which is the number of inputs (user gives this number as input).
in its body, it calls scan.nextDouble to get the nex number from the console. then adds this number to sum.
I am a beginning programmer and we were assigned to implement methods into a code. I had this grade average code working fine, but once I broke it up into methods, I could not get the return functions to work. I have tried moving brackets and rearranging the code but to no avail. I believe it may have to do with the scope of my variables... Thanks in advance :)
package milsteadgrades;
import java.util.Scanner;
public class MilsteadGrades {
public static void main(String[] args)
{
//Call methods to execute program.
displayInfo();
double numOfgrades = getInput();
double average = getAverage(numOfgrades);
char letgrade = determineLetterGrade(average);
displayGrades(average, letgrade);
}
public static void displayInfo()
{
System.out.println("Mallory Milstead");
System.out.println("This program will prompt the user for a number of
grades"
+ " and each grade. Then the program calculates and displays the average and
letter"+" grade.");
}
public static double getInput()
{
//Prompt user to enter number of grades and assign that number to
numOfgrades.
System.out.print("How many grades would you like to average? ");
Scanner keyboard = new Scanner(System.in);
double numOfgrades = keyboard.nextDouble();
return numOfgrades;
}
public static double getAverage(numOfgrades)
{
//Prompt the user to enter grades.
System.out.println("Enter exam scores : ");
Scanner keyboard = new Scanner(System.in);
double total = 0;
for (double i = 0; i < numOfgrades; i++) {
double grade = keyboard.nextDouble();
total+=grade;}
double average = total/numOfgrades;
return average;
}
public static char determineLetterGrade(average)
{ double testscore = average;
char letgrade;
if (testscore >= 90)
{
letgrade = 'A';
} else if (testscore >= 80)
{
letgrade = 'B';
} else if (testscore >= 70)
{
letgrade = 'C';
} else if (testscore >= 60)
{
letgrade = 'D';
} else
{
letgrade = 'F';
}
return letgrade;
}
public static void displayGrades(average, letgrade)
{
System.out.println("The average of the grades is "+average+ " and the
letter grade"+ " is " + letgrade+".");}
}
Beginning with the line -public static double getAverage(numOfgrades)-, I continuously get "cannot find symbol" error message. None of my variables is being recognized.
You need to declare the type of the argument of getAverage. Like
public static double getAverage(double numOfgrades)
Similiarly for your other methods(not modules). Have a read of this or this for tips.
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question.
Firstly, here is what I am trying to use as my main program:
import java.util.Scanner;
public class TheATMGame
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double newBalance = 0;
double monthlyInterest = 0;
int answer = 0;
int i=1;
while (i < 100) {
System.out.print ("Please enter your ID: ");
answer = input.nextInt();
System.out.println(" ");
if (answer >=0 && answer<10)
TheATMGame.runGame (answer);
else
System.out.println("Sorry, this ID is invalid.");
}
}
public static void runGame(int id) {
double amount = 0;
int continueOn = 0;
while (continueOn < 4) {
ATMGame myATM = new ATMGame();
Scanner input = new Scanner(System.in);
System.out.println ("---Main menu--- ");
System.out.println ("1: Check balance ");
System.out.println ("2: Withdraw ");
System.out.println ("3: Deposit ");
System.out.println ("4: exit ");
int answer = input.nextInt();
if (answer == 1)
System.out.println("your balance is: " + myATM.getBalance (id));
else if (answer == 2){
System.out.println("Enter an amount to withdraw: ");
amount = input.nextInt();
myATM.withdraw(amount, id);
}
else if (answer == 3)
{
System.out.println("Enter an amount to deposit: ");
amount = input.nextInt();
myATM.deposit(amount, id);
}
else if (answer == 4)
continueOn = 4;
else if (answer > 4)
System.out.println ("Please review the main menu. " +
"Your selection must be between 1-4.");
}
}
//ATM class (balance, annualInterestRate2, id2)
//ATM myATM = new ATM (20000, 4.5, 1122 );
//newBalance = myATM.withdraw(2500);
//newBalance = myATM.deposit(3000);
//monthlyInterest = myATM.getMonthlyInterestRate();
//System.out.println("Your current balance is: " + newBalance);
//System.out.println ("Your monthly interest rate is: " + monthlyInterest);
}
Now here are all of the classes I want to impliment into that program:
import java.util.Date;
public class ATMGame {
private double annualInterestRate = 0;
private double balance = 0;
private int id = 11;
private int[] ids = {0,1,2,3,4,5,6,7,8,9};
private int[] balances = {100,100,100,100,100,100,100,100,100,100};
public Date dateCreated;
public ATMGame() {
}
public ATMGame (double balance2, double annualInterestRate2, int id2) {
balance = balance2;
annualInterestRate = annualInterestRate2;
id = id2;
dateCreated.getTime();
}
public double getMonthlyInterestRate() {
double monthlyInterest = annualInterestRate/12;
return monthlyInterest;
}
public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account
double newBalance = balances[id] - amountWithdrawn;
System.out.println("Your withdrawel has processed. New balance: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double deposit(double amountDeposited, int id) { //This method deposits money in the account
double newBalance = balances[id] + amountDeposited;
System.out.println("Your deposit has processed. New Balance is: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double getBalance(int id) {
double myBalance = balances[id];
balance = myBalance;
return myBalance ;
}
}
When I try to run the first program it says "No Main classes found."
As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong?
Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found." :/
http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg
I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
You should use:
public static void main(String[] args)
Instead of Main because the JVM calls this method first. It is a convention.
You've just misdefined main. Should be:
public static void main(String[] args) {
....
}
You're going to run into some other problems with your code, though. From a quick glance...
Your main() is a function, as well as runGame() - one shouldn't be defined within the other.
You cannot name your two classes the same thing - call the main() class something different than ATMGame.
Not sure where you're going with ATM class (balance, annualInterestRate2, id2), but it's not valid Java.
Your method signature must be:
public static void main(String[] args) {
...
}
That's the convention you have to follow. Anything else won't work.
In your class ATMGame, replace the following:
public void Main() {
with:
public static void main(String[] args) {
Additionally, since this method has to be static, you'll need to change the following:
if (answer >=0 && answer<10)
runGame (answer);
else
with:
if (answer >=0 && answer<10)
ATMGame.runGame (answer);
else
Then finally, you need to change the method signature of rungame to also be static. Change it from:
public void runGame(int id) {
to:
public static void runGame(int id) {
The names of your public classes should match the file names. This is not the case in your screenshot. Also make sure that everything compiles correctly and then retry (using a public static void main(String[] args) { ... } method).