Returning/Passing Variables in Java - java

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.

Related

How are these inputs being recorded and passed to the method?

This is example code of a simple grade calculation. I don't understand how we are able to take multiple inputs when there isn't a scanner directly in the next line.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avg;
String[] name = new String[10]; //craeting a string array named "name" that has 10
for (int j = 0; j<10; j++)
{
System.out.println("What is the name of the student?");
name[j] = sc.nextLine(); // nextLine because we want the string of the input
System.out.println("What are their test scores?");
avg = calculateAverage(j);
System.out.println("Their average is " + avg + ", that is a " + calculateGrade(avg));
}
}
public static double calculateAverage(int j) {
double [][]gradebook = new double[10][5];
Scanner sc = new Scanner(System.in);
double sum = 0;
for (int v=0; v<5; v++)
{
gradebook[j][v] = sc.nextDouble();
sum = gradebook[j][v] + sum;
}
double avg = sum / 5;
return avg;
}
public static String calculateGrade (double avg)
{
if (avg >= 90 && avg <= 100) {
return "A";
}
else if (avg >= 80) {
return "B";
}
else if (avg >= 70) {
return "C";
}
else if (avg >= 60) {
return "D";
}
else {
return "F";
}
}
}
I know that there's a scanner in calculateAverage, but what makes it possible for a user to respond with multiple numbers and those inputs being pushed into calculateAverage? Shouldn't there be a scanner in main that directly records the inputs? Are the inputs somehow being directly pushed into calculateAverage?
The scanner in calculate average reads in numbers from gradebook[j][v] = sc.nextDouble();
whenever this line is reached the code will stop and wait for input.
After input, the loop continues and asks for another number as input.

Need help trying to understand what this for loop does and how it works

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.

Else-if statement

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

BMI calculator errors

While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java

Java methods and classes, how do they fit together?

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

Categories

Resources