I know the problem exists on the forum, but I am really stuck. I would like to call my grade() method into my display() method to appear the grade. I don't know how to do...
Here is my grade() method
public static void grade(int note){
String grade = "";
if (note <= 70){
grade = "Satisfaction";
}
else{
grade = "Great Satisfaction";
}
}
In my display() method, I want to retrieve the grade for the student.
public static void display(String[] tabStudent, int[] tabNote, char code){
for(int i=0; i<tabStudent.length;i++){
if (code == 'e'){
if (tabNote[ i ] < 50){
System.out.println(tabStudent[i] + " " + tabNote[i] );
}
}
else if(code == 's'){
if (tabNote[ i ] > 50){
System.out.println(tabStudent[i] + " " + tabNote[i] + grade() );
}
}
}
}
My problem is this line below:
System.out.println(tabStudent[i] + " " + tabNote[i] + grade() );
Here is an image
Thank you for your help.
tl;dr you're missing a return statement
Imagine you have a bunch of people around you who can either do a task (hopefully...) perfectly or can calculate some value (again, hopefully...) perfectly. When you tell one person, "go put coins into a vending machine", they go do it and walk back. They don't say anything, they just kind of...go. At most, you might get an "Ok" or a "HEY SOMETHING WENT WRONG" when they come back but that's the extent of their verbal capacity.
On the other hand, you have people who you ask "What are the 1st through 3rd letters of 'hello'?" And they will say, "'el'." They may go grab a calculator or a book to figure out the answer, but they can do it and will report the value back to you.
The former is an example of a void function, while the latter is what you get when you return from a function. When you have a function simply calculate values in a void function, it's equivalent to asking a friend, "What's 5+3?", them doing the calculation in their head and saying "done! :D". Not super helpful.
While there are ways to get around needing to return while not having to literally return (such as using global variables), they are heavily frowned up much like passing notes to relay information was in middle school by your teacher.
Well, it needs to actually return something:
public static String grade(int note){
String grade = "";
if (note <= 70) {
grade = "Satisfaction";
} else {
grade = "Great Satisfaction";
}
return grade;
}
I can see two issues in your code:
1. you should change return type of grade() method and return grade.
2. Your grade() method expect one parameter but you are not passing any while calling it. Try below code.
public static String grade(int note){
String grade = "";
if (note <= 70){
grade = "Satisfaction";
}
else{
grade = "Great Satisfaction";
}
return grade;
}
public static void display(String[] tabStudent, int[] tabNote, char code){
for(int i=0; i<tabStudent.length;i++){
if (code == 'e'){
if (tabNote[ i ] < 50){
System.out.println(tabStudent[i] + " " + tabNote[i] );
}
}
else if(code == 's'){
if (tabNote[ i ] > 50){
System.out.println(tabStudent[i] + " " + tabNote[i] + " " + grade(tabNote[i]) );
}
}
}
}
The first problem is that you do not have a method grade(). Instead, you have defined grade(int note) which expects an integer.
Even if you correct this problem and call grade like
System.out.println(tabStudent[i] + " " + tabNote[i] + grade(80));
it won't work because you have declared grade as
public static void grade(int note)
which should be
public static String grade(int note)
i.e. return type should be String instead of void as per your requirement.
Define it as
public static String grade(int note){
String grade = "";
if (note <= 70){
grade = "Satisfaction";
}
else{
grade = "Great Satisfaction";
}
return grade;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner (System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake,BMR);
//this is what you actually ate
actualCalories(actualIntake,BMR);
//gym with protein
gym (30,40,50,100, actualIntake);
}
//testing method
testingMeth(actualIntake);
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR){
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0 ){
calorieDifference = Math.abs (BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0){
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories (int actualIntake, int BMR ) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR ) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR ) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin." );
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym (int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50 ) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50 ) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth (int actualIntake) {
System.out.println(actualIntake);
}
}
//Take calories in then calculate BMR and compare, return value
So I am currently learning java, just learning and making random calorie deficit and BMR program. I created a new method called:
public static int testingMeth(actualIntake) {
System.out.println(actualIntake);
}
The issue is when i try to call the method after the gym method, it creates an error.
gym (30,40,50,100, actualIntake);
}
testingMeth(actualIntake);
If i was to delete the gym method from the main method, all my other methods has errors. I do not necessarily need a solution for this program but rather why am i receiving these errors? Just want to learn and improve! Thanks.
In other words, I can call the testingMeth before the Gym method and it works fine, but why not after the gym method? and if i get rid of the gym method, multiple errors occur amongst the other methods within the program?
If you see below code, i am able to run both method in any sequence and it's working fine as well.
You need to go through with basics of method declaration and method call.
It will help you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner(System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake, BMR);
//this is what you actually ate
testingMeth(actualIntake);
actualCalories(actualIntake, BMR);
//gym with protein
gym(30, 40, 50, 100, actualIntake);
}
//testing method
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR) {
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0) {
calorieDifference = Math.abs(BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0) {
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories(int actualIntake, int BMR) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin.");
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym(int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth(int actualIntake) {
System.out.println(actualIntake);
}
}
You need to understand for every opening braces of class/method/switch-case/or condition must have closing braces.
In your case you are try to call some method after closing braces of class, so those elements are not part of your class and that's why it's throwing an error.
I'm new here, and to code in general. What I'm trying to accomplish is to create a simple guessing game that prompts a user for a number, and checks that number against a computer generated number between 1 and 100. I've tried to make it so the player can continue guessing until they get the correct answer, as well as display a counter to let the player know how many guessing attempts they have made. The problem is, the program won't terminate after the correct answer has been given, and I can't figure out what I'm doing wrong. I'll paste the entire code at the bottom for reference, but I feel like the problem lies within the following statement in the "determineAnswer" method:
} else if (userAnswer == computerNumber) {
message = "Correct"
+ "\nNumber of Guesses: " + count;
success++;
I'm trying to use the value of the integer "success" as the condition to terminate the do/while loop, but even though I try to increment the value, the loop continues as if the value is being continuously reset. If that's the case, I can't see where I've gone wrong. Again, I'm quite new at this but I would appreciate any input.
import javax.swing.JOptionPane;
public class GuessingGame {
public static void main(String[] args) {
// generate a random number from 1 to 100
int computerNumber = (int) (Math.random() * 100 + 1);
// declare other variables
int success = 0;
int count = 0;
// display the correct guess for testing purposes
System.out.println("The correct guess would be " + computerNumber);
// prompt user for a guess
do {
count++;
String response = JOptionPane.showInputDialog(null,
"Enter a guess between 1 and 100");
int userAnswer = Integer.parseInt(response);
// display result
JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber, success, count));
} while (success == 0);
}
public static String determineGuess(int userAnswer, int computerNumber,int success, int count) {
String message = null;
if (userAnswer <= 0 || userAnswer > 100) {
message = "Invalid guess"
+ "\nNumber of Guesses: " + count;
} else if (userAnswer == computerNumber) {
message = "Correct"
+ "\nNumber of Guesses: " + count;
success++;
} else if (userAnswer > computerNumber) {
message = "Incorrect, Too High"
+ "\nNumber of Guesses: " + count;
} else if (userAnswer < computerNumber) {
message = "Incorrect, Too Low"
+ "\nNumber of Guesses: " + count;
}
return message;
}
}
You do not update the value of success and every time the loop runs, it will be getting success value as 0 and thus it is causing infinite loop.
int success = 0;
int count = 0;
// display the correct guess for testing purposes
System.out.println("The correct guess would be " + computerNumber);
// prompt user for a guess
do {
count++;
String response = JOptionPane.showInputDialog(null,
"Enter a guess between 1 and 100");
int userAnswer = Integer.parseInt(response);
// display result
JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber, success, count));
success=1;
} while (success == 0);
In Java everything is pass by value.
In this case have passed primitive (int) to method and then changing its value and expecting same to reflect in calling method. Java doesn't work like that
public class SuccessTest {
public static void main(String[] args) {
int success = 0;
updateSuccess(success);
System.out.println(success); //will print 0
}
private static void updateSuccess(int success) {
//changing value of success here will not reflect in main method
success=2;
System.out.println(success);//will print 2
}
}
In order to make this work declare success as class level variable
private static int success = 0;
then no need to pass this success to determineGuess method, now if you update value of success in determineGuess method it will be available in main method
The reason that the success variable is not being updated in the main method is that it does not have access to any changes to the determineGuess method's success variable. They are two separate variables in separate scopes.
determineGuess receives success as an int method parameter. In Java, types such as int, char and float are pass-by-value: this means that the value is essentially copied when it is given to a method or set as a variable, so that if you modify the copied value, the original one is not modified. (actually, all types are pass-by-value, but the contents of an object is by reference).
There are a few ways of updating the success variable for the main method, two of which are:
Make success a field in the class, that way it is accessible by all methods in the class. Because you are doing all of this in main, for now you will need success to be static: private static int success = 0;. A better way can be to make everything non-static, and have main instantiate a GuessingGame object and then call a run method on it.
Return a value from determineGuess that will let you know what category the answer fits into: success, incorrect, too high or too low. You would then have a second method that uses this output to select the message to display. If main sees that the output is success, it updates its success variable. This might be better, but is more involved.
For this simple example, I suggest option 1. In fact, because you only check for one success, the success variable can just be a boolean value. This would make your code the following (with modifications):
import javax.swing.JOptionPane;
public class GuessingGame {
// Determines whether the user has successfully guessed the number
private static boolean success = false;
public static void main(String[] args) {
// Generate a random integer between 1 and 100 inclusive
int computerNumber = (int) (Math.random() * 100 + 1);
// Count the number of guesses that the user makes, to report it to them
int count = 0;
// FIXME: only for testing purposes, remove this
System.out.println("The correct guess would be " + computerNumber);
do {
count++;
String response = JOptionPane.showInputDialog(null, "Enter a guess between 1 and 100");
int userAnswer = Integer.parseInt(response);
JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber, count));
} while (!success);
}
public static String determineGuess(int userAnswer, int computerNumber, int count) {
if (userAnswer <= 0 || userAnswer > 100) {
return "Invalid guess\nNumber of Guesses: " + count;
} else if (userAnswer == computerNumber) {
success = true;
return "Correct\nNumber of Guesses: " + count;
} else if (userAnswer > computerNumber) {
return "Incorrect, Too High\nNumber of Guesses: " + count;
} else if (userAnswer < computerNumber) {
return "Incorrect, Too Low\nNumber of Guesses: " + count;
}
return null;
}
}
If you were to go with option 2, then you might have an enum GuessOutcome { INCORRECT, SUCCESS, TOO_LOW, TOO_HIGH } that you return from determineGuess. You would then have a getOutcomeMessage(GuessOutcome outcome) method with a switch (outcome) { ... } to select which message to display. If outcome == GuessOutcome.SUCCESS, then success = true. In this version, success can be a local variable to main.
I need to take this "over" statement under the overallmethod as finalmethods' parameter, how can I do this. I want to learn the final letter but to do that I want to access over statement.
public static void overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade){
double quizzes = ( ((quiz1*10) + (quiz2*10) + (quiz3*10)) *25) /300;
double finalg = ( grade * 40) / 100;
double mid = (midterm * 35) / 100;
double over = quizzes + finalg + mid;
System.out.println("Your overall score is: " + over);
}
public static void finalmethod(double over){
if(over <= 100 && over >= 90){
System.out.println("Your final letter is: A");
}
else if(over >= 80) {
System.out.println("Your final letter is: B");
}
else if (over >= 70) {
System.out.println("Your final letter is: C");
}
else if (over >= 60) {
System.out.println("Your final letter is: D");
}
else{
System.out.println("Your final letter is: F");
}
}
You're going to need to return the variable over and change your return type to double.
public static double overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade)
{
//Your code
return over;
}
Then simply pass the value returned from the overallmethod to finalmethod.
over is not a statement, it is a local variable now. Just make it class attribute:
public static double over
Make your overall function return the value of over. Then just call the overall function inside the parameter list of finalmethod
The best solution would be to declare over as a private int outside both the methods, i.e. it should have visibility to all the methods in that class (class variable).
Now compute the overall score in the overallMethod and store it to the over variable.
Next, make a public method getOver() which returns the value of over, and call finalMethod in this way : ClassName.finalMethod(objectOfClass.getOver())
By changing the return type of your method to double, and then passing the value in that method to the final method.
Rookie mistake?
Hello, I'm a first-year computer science student and I keep getting cannot find symbol errors. I declared the variable in the main method, passed it to another method, modified it, and then returned it. For some reason, the compiler cannot find the symbols result, input, and points. I'm sure it's the same reason for all of them. Any help would be appreciated.
public class Fishing
{
public static void main(String[] args)
{
do
{
String input; //Holds user input
int points; // Holds player's points
int score = 0; // Sets player's score to 0
final int DIE_SIDES = 6; // # of sides for the die
//Create an instance of the Die class
Die die = new Die(DIE_SIDES);
//Roll the die once and store value in result
die.roll();
int result = die.getValue();
getScore(points, result);
String input = getInput();
//Keeps running total of player's score
score = score + points;
} while (input == "yes");
System.out.print(0);
}
/**
The getScore method will calculate the player's score
depending on what the player rolled. It will also show
a message and return the score.
#return A reference to an integer object containing
the player's score for one roll.
*/
public static int getScore(int points, int result)
{
if (result == 1)
{
JOptionPane.showMessageDialog(null, "Waaaaahhhhh, you have caught " +
"a shark. Sharks are dangerous. You " +
"have been awarded zero points.");
points = 0;
return points;
}
else if (result == 2)
{
JOptionPane.showMessageDialog(null, "You have caught a jellyfish. " +
"This beautiful creature has awarded you " +
"50 points!!");
points = 50;
return points;
}
else if (result == 3)
{
JOptionPane.showMessageDialog(null, "You have caught an old boot. " +
"Maybe you can sell this old boot after it " +
"dries out. You have been awarded 1 point.");
points = 1;
return points;
}
else if (result == 4)
{
JOptionPane.showMessageDialog(null, "You have caught an Alaskan salmon. " +
"This delicious and popular fish has awarded you " +
"75 points!!!");
points = 75;
return points;
}
else if (result == 5)
{
JOptionPane.showMessageDialog(null, "You have caught a small fish. You " +
"have been awarded 20 points!");
points = 20;
return points;
}
else
{
JOptionPane.showMessageDialog(null, "You have caught a treasure chest!! " +
"It is filled with shining pieces of gold, and " +
"you have been awarded 100 points!!!!");
points = 100;
return points;
}
}
/**
The getInput method will receive the user's input
and return it to the main method.
#return A reference to a String input value containing
the user's response.
*/
public static String getInput()
{
//Prompt user to enter response
response = JOptionPane.showInputDialog("Would you like to play another " +
"round of fishing? Enter yes or no.");
return response;
}
}
We need to make the following changes:
Result is declared in main() method and hence, it is local to main() only. getScore has no knowledge of it. If we want to access result, input and points in getScore() method then we need to pass all of them to getScore().
getInput() returns an input. So, we don't need to pass any argument to it. We can change getInput(String response) to getInput() and modify main() so that value returned by getInput() is assigned to input variable (input = getInput();)
Here are some basics of parameter passing in java. I would recommend going through it.
I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
Here is part of my program (in the class PressureInput) and where my issues start:
public void setSystolic(int sys)
{
sys = sysAvrg;
}
So, assuming the avrgSys has a number (it does), I then want to pass the info to the other class (BPChecker).
I don't feel like I'm doing this right, or at least, not in such a way as to facilitate passing the 'int' of sysAvrg from the class its in into another class (BPChecker).
I'm not sure whether to use a getSystolic since I'm not sure what the return would be.
I can't just initialize sys in the other class (BPChecker) without giving sys a value (which defeats the purpose), but it keeps telling me to.
In the end, I need to move the number of avrgSys into BPChecker without rewriting the whole program. So far, I keep getting a lot of 0s or errors...
Any help is appreciated, though my newness may have more complicated explanations go over my head (sorry to say).
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
In Object-oriented programming, you can create an instance of an object in any class you want. In order to access class variables from other classes, you can use accessor methods.
i.e.
public class PressureInput {
private static int sysAvrg;
public PressureInput(int sysAvrg){
this.sysAvrg = sysAvrg;
}
public void setSystolic(int sys){
this.sysAvrg = sys;
}
public int getSystolic() {
return this.sysAvrg;
}
}
You have a variable called sys so if you want to set it with the average create a setter Method:
public void setSystAve(float sysAvrgParameter){
sysAvrg = sysAvrgParameter;
}
if you want to get the sysAvrg create a getter Method:
public float getSystAve(){
return sysAvrgParameter;
}
now somewhere in your code:
sys = yourObject.getSystAve();