Method returns zero - java

It is suppose to return a value of 19 full seats and 68 students remaining!
please help, with my understanding I am returning the right values and assigning them to the correct variables!
public class JetCalculator
{
public static void main(String[] args)
{
int totalStudents = 3013;
int jetCapacity = 155;
int jets;
int students;
jets = calculateJets(jetCapacity, totalStudents);
students = calculateStudents(jetCapacity, totalStudents, jets);
System.out.println("A total of "+ totalStudents + " student require "+ jets + " full seated jets.");
System.out.println("There will be " + students + " students remaining");
System.out.println("_____________________________________________");
System.out.println(jets);
System.out.println(jetCapacity);
System.out.println(students);
}
public static int calculateJets(int totalStudents, int jetCapacity)
{
int fullJets;
fullJets = totalStudents / jetCapacity;
return fullJets;
}
public static int calculateStudents( int jetCapacity, int totalStudents, int jets)
{
int remainingStudents;
remainingStudents = jetCapacity * jets;
return remainingStudents;
}
}

You call calculateJets this way
jets = calculateJets(jetCapacity, totalStudents);
But the argument names for this method imply that you've switched their order in the call
public static int calculateJets(int totalStudents, int jetCapacity)
This means you're actually doing 155 / 3013 which is 0 using integer arithmetic.

You're passing in your parameters back to front.
You call calculateJets by passing capacity then students: calculateJets(jetCapacity, totalStudents); but the method asks for students then capacity: calculateJets(int totalStudents, int jetCapacity).
This is a good argument for consistency in parameter order throughout a class interface.
To help debug this in future, try throwing in a println at the start of methods to see what is happening:
System.out.println("Called calculateJets with totalStudents of " + totalStudents + " and jetCapacity of " + jetCapacity);

Based purely on method names: did you mean to say remainingStudents = totalStudents - (jetCapacity * jets); ?

Related

How do i assign and obtain values to objects created in an array?

Currently learning Java as a hobby and am making small game projects to reinforce the concepts. So for this one, I've made a method that creates an array of objects, in this case, a "Computer" object. I'm doing this because I want the user to decide at startup how many computer opponents they want to play against, instead of hard coding a set number of them. Now I want to assign and retrieve a value for each Computer object. For example a Computer name, bet amount, and a dice roll guess.
public class Computer {
static int bet;
static int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
bet = Rng.rand(Game.startCash / 50) * 50;
return bet;
}
public static int guess() {
guess = Dice.roll();
return guess;
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + " i bet " + bet + " and guess " + guess);
}
}
When i do Computer.create(5) i get
My name is Computer i bet 150 and guess 9
My name is Computer i bet 50 and guess 3
My name is Computer i bet 450 and guess 11
My name is Computer i bet 250 and guess 11
My name is Computer i bet 50 and guess 10
This output gives the appearance of working but i don't think i'm on the right track. For the name i want the syntax to be something like, name = "Computer " + c[i]. Resulting in "Computer 1", "Computer 2", "Computer 3" etc, not sure how to do that correctly. And an individual bet and guess to be assigned to each individual object. Right now i think its just displaying a random number rather than assigning that value to the particular object.
The bet and guess member variables shouldn't be static.
To display the id you can add a new int member variable, set it to i for each computer when you initialize them in the loop, and update the display() method to print it.
public class Computer {
int id;
int bet;
int guess;
int cash;
static Computer[] c;
public static void create(int numComps) {
c = new Computer[numComps];
for (int i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i;
c[i].cash = Game.startCash;
c[i].bet = bet();
c[i].guess = guess();
c[i].display();
}
}
public static int bet() {
return Rng.rand(Game.startCash / 50) * 50;
}
public static int guess() {
return Dice.roll();
}
public void display() {
String name = "Computer ";
System.out.println("My name is " + name + id + " bet " + bet + " and guess " + guess);
}
}

School Assignment Multidimensional Array Trouble

I am currently working on an assignment for my Java programming class. I seem to have got myself in a bit of a bind. Any assistance in helping me realize what I am doing wrong would be greatly appreciated.
Assignment
Write a program that does the following:
Put the data below into a multi-dimensional array
Prompts the user for the company they would like employee salary statistics.
Write a method that returns the average employee salary as a double. Pass the company number and employee Wages to this method.
Write a method that returns the total employee salary as an int. Pass the company number and employee Wages to this method.
Write a method that returns the number of employees as an int. Pass the company number and employee Wages to this method.
In the main method call the other methods and out put the results.
Keep in mind that I am still new and struggling to understand some of the principles of programming.
When I run the program I am getting locations instead of method calculations (bad output):
Here is what I have so far:
package salaries;
import java.util.Scanner;
public class Salaries {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//declare, instantiate, and define value of multi array [3] [12]
double [][] mSalary = { { 49920, 50831, 39430, 54697, 41751, 36110,
41928, 48460, 39714, 49271, 51713, 38903},
{ 45519, 47373, 36824, 51229, 36966, 40332,
53294, 44907, 36050, 51574, 39758, 53847},
{ 54619, 48339, 44260, 44390, 39732, 44073,
53308, 35459, 52448, 38364, 39990, 47373}};
//declare, instantiate, and define value
//of single array for company names
//and output values to user for selection
String [] company = { "Alhermit", "Logway", "Felter" };
for( int i = 0; i < company.length; i++ )
System.out.println( "Company " + i + " : " +company[i] );
Scanner scan = new Scanner( System.in );
int cCompany;
do{
//ouput for user to select a company
System.out.print("Select company: (0)" +company[0]+ ", (1)"
+company[1]+ "; (2)" +company[2]+ " > ");
//scan user input into cCompany
cCompany = scan.nextInt();
//call number method
num nums = new num();
nums.number(mSalary, cCompany);
//call total method
total sum = new total();
sum.total(mSalary, cCompany);
//call average method
avg cAvg = new avg();
cAvg.average(mSalary, cCompany);
//output statistics to user on selected company
System.out.println( "You have selected the company " + company[cCompany] + ". " );
System.out.println( company[cCompany] + " has " + nums + " of employees." );
System.out.println( "A total employee salary of " + sum + "." );
System.out.println( "The average employee salary is " + cAvg );
}
while( cCompany < 0 || cCompany > 2);
}
}
//total class to calculate
//salary of user selected company
class total {
public static int total( double [][] mSalary, int cCompany ){
//assign variables
int sum = 0;
//for loop to calculate salary total of user input company
for( int j = 0; j < mSalary[cCompany].length; j++ ){
sum += mSalary[cCompany][j];
}
//return statement
return sum;
}
}
//average class to calculate
//average of user selected company
class avg {
public static double average( double [][] mSalary, int cCompany){
//assign variables
int cAvg = 0;
int sum = 0;
int count = 0;
//totals the values for the selected company by
//iterating through the array with count.
while( count < mSalary[cCompany].length){
sum += mSalary[cCompany][count];
count +=1;
}
cAvg = sum / mSalary[cCompany].length;
return cAvg;
}
}
//number class to calculate amount of
//employees in user selected company
class num {
public static int number( double [][] mSalary, int cCompany){
//assign variables
int nums = 0;
//number of employees based on length of colomn
nums = mSalary[cCompany].length;
return nums;
}
}
nums, sum, and cAvg are all instances of classes that you have, you're printing out the instances of those classes.
(By the way - you should change the name of these classes. Classes start with a capital letter. It differentiates them from variables.)
There are two things wrong with this.
You are instantiating a class which contains no data and has no toString method.
You're instantiating a class which only has static methods to return the data from. You don't need to instantiate the class at all; instead, just print the result of the method call.
That would change at least one of these calls to something like:
System.out.println( company[cCompany] + " has " + num.number(mSalary, cCompany); + " of employees." );
I leave the rest as an exercise for the reader.

How to return two values in Java

I know that java can't normally return two values, but I'm trying to return the value as a method.. From there I want to use the values of score1 and maxScore1 in a string in the main method. getHwGrades is the method I'm having issues with. I get "error: cannot find symbol". I'm not allowed to use arrays for this program. On another note, I'm also not supposed to use any if/else statements, but I could not find any other way to limit the value of discussionGrade to 20. Any help is appreciated
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
Scanner getG = new Scanner(System.in);
int weight1;
int weight2;
int weight3;
int score2 = 0;
int maxScore2 = 0;
int sections;
int discussionGrade;
System.out.println("What is the weight for the HW and Exam 1?");
weight1 = getG.nextInt();
weight2 = getG.nextInt();
weight3 = getWeight(weight1, weight2);
System.out.println("Using weights of " + weight1 + " " + weight2 + " " + weight3);
getHwGrades();
sections = numberSections();
discussionGrade = calcDGrade(sections);
System.out.println("What is your grade for exam1?"); //move under hw total points and final grade, add curve
score2 = getG.nextInt();
maxScore2 = getG.nextInt();
System.out.println("Total Points =" + (score1+ discussionGrade) + "/ "(maxScore1 + 20));
}
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
int nOfA;
Scanner getG = new Scanner(System.in);
System.out.println("How many HW assignments are there?");
nOfA = getG.nextInt();
for (int i = 1; i <= nOfA; i++) //loop that asks for the grades corresponding to the amount of hw assignments there were
{
System.out.println("What is your grade and then the max grade for assignment " + i + "?");
score1 += getG.nextInt();
maxScore1 += getG.nextInt();
}
return new getHwGrade(score1, maxScore1); //returns results of inputs into method holding the 2 variables
}
public static int numberSections() //finds out how many sections the student attended
{
Scanner getG = new Scanner(System.in);
System.out.println("How many sections did you attend?");
return getG.nextInt();
}
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4)); if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
public static int getWeight(int weight1, int weight2)//returns the weight that will be used for weight3
{
return (100-(weight1 + weight2));
}
public static double round2(double number)
{
return Math.round(number * 100.0) / 100.0;
}
}
Since you can only return a single value, you need to return a single value. :-) Normally if a method needs to return complex information, the way you have it do that is either:
Return a newly-created instance of a class that has fields for the individual pieces of information
Have the method fill in an instance of such a class that's passed to it (usually not ideal barring a good reason for doing it)
So for instance:
class HwGrades {
private int score1;
private int maxScore1;
ScoreInfo(int _score1, int _maxScore1) {
this.score1 = _score1;
this.maxScore1 = _maxScore1;
}
// ...accessors as appropriate, presumably at least getters...
}
Then return an instance of HwGrades from getHwGrades:
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
// ...
return new HwGrades(score1, maxScore1);
}
If you needed, you could further decouple things by making HwGrades an interface, which you then implement with a private class, so that the API isn't tied to a specific class. Almost certainly overkill for a small school project.
getHwGrade is expected to be a class.
Have a class like this
class getHwGrade{
int a;
int b;
public getHwGrade(int a,b){
this.a=a;this.b=b;
}

Java program not returning any values

I am currently working on a class assignment and cannot figure out why I am getting the output that I am getting. The programming question is:
You operate several hotdog stands. Define a class named HotDogStand
that has an instance variable for the hot dog stand's ID number and an
instance variable for how many hot dogs the stand has sold that day.
Create a constructor that allows a user of the class to initialize
both variables. Also create a method named justSold that increments by
one the number of hot dogs the stand has sold. The idea is that this
method will be invoked each time the stand sells a hot dog so the
total can be tracked. Add another method that returns the number of
hot dogs sold.
Add a static variable that tracks the total number of hot dogs sold by
all the stands and a static method that returns the value in this
variable.
So my code is:
public class HotDogStand {
// instance variable declaration
private int IDNumber;
private int hotDogsSold = 0;
private static int totalSold = 0;
public HotDogStand(int ID, int sold) {
IDNumber = ID;
hotDogsSold = sold;
}
public int getID() {
return IDNumber;
}
public void setID(int ID) {
IDNumber = ID;
}
public void justSold() {
if (hotDogsSold > 0) {
hotDogsSold++;
}
}
public int sold() {
return hotDogsSold;
}
public static int getTotal() {
return totalSold;
}
}
And my testing class is:
public class HotDogTest {
public static void main(String[] args) {
HotDogStand stand1 = new HotDogStand(1, 11);
HotDogStand stand2 = new HotDogStand(2, 17);
HotDogStand stand3 = new HotDogStand(3, 6);
stand1.getID();
stand2.getID();
stand3.getID();
stand1.setID(1);
stand2.setID(2);
stand3.setID(3);
stand1.justSold();
stand2.justSold();
stand3.justSold();
stand1.justSold();
stand1.justSold();
stand1.justSold();
stand3.justSold();
stand1.getTotal();
stand2.getTotal();
stand3.getTotal();
int grandTotal = stand1.getTotal() + stand2.getTotal() + stand3.getTotal();
System.out.println("Stand " + stand1.getID() + " sold a total of " + stand1.getTotal() + " hotdogs.");
System.out.println("Stand " + stand2.getID() + " sold a total of " + stand2.getTotal() + " hotdogs.");
System.out.println("Stand " + stand3.getID() + " sold a total of " + stand3.getTotal() + " hotdogs.");
System.out.println("The total amount of hotdogs sold by all the stands was " + grandTotal);
}
}
My output is:
Stand 1 sold a total of 0 hotdogs.
Stand 2 sold a total of 0 hotdogs.
Stand 3 sold a total of 0 hotdogs.
The total amount of hotdogs sold by all the stands was 0
you are never updating totalSold field. Increment that as well inside justSold() method's if condition.
There is no point at which you change the totalSold variable. justsold increments the instance variable hotDogsSold but getTotal return totalSold.
You need a method getSold which returns the instance variable hotDogsSold.
The other problem is that totalSold is a static variable (it's a class variable; it's not tied to any individual instance of the class like hot dog seller 1 or 2 but rather to the entire model of hot dog sellers). As a result, your grand total would, if totalSold were incremented correctly, give 3 times the number of sold hot dogs for everyone.
Try this:
public void justSold() {
if (hotDogsSold > 0) {
totalSold = hotDogsSold++;
}

Return value executing a method?

import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.

Categories

Resources