for the following code:
System.out.println("How many types of food do the gerbils eat?");
int F = keyboard.nextInt();
food = new food[F];
for
(int a = 0; a<F; a++){
System.out.println("Name of food number " + (a+1));
foodname = keyboard.next();
System.out.println("Max amount of food " + (a+1));
maximum = keyboard.nextInt();
food[a] = new food(foodname, maximum);
for (int n = 0; n<F; n++){
System.out.println(food[n]);
}
}
I get the following output:
How many types of food do the gerbils eat?
2
Name of food number 1
p
Max amount of food 1
5
p 5
null
Name of food number 2
r
Max amount of food 2
5
r 5
r 5
As you can see, every time the loop restarts, the new input values for food name and food maximum are reset. why is it doing that, and how do i fix it so that it stores my original input for food 1 name and maximum?
Class food:
public class food {
public static String foodname;
public static int maximum;
public food(String foodname, int maximum) {
this.foodname = foodname;
this.maximum = maximum;
}
public String getFood(){
return foodname;
}
public int getmaxamount(){
return maximum;
}
public String toString() {
return (this.getFood() + " " + this.getmaxamount());
}
}
In your Food class, you declared
foodname
maximum
as static.
It means, those values will be the same for every Food you create.
As you want different kind of Food, simply remove those modifiers
Although this question has already been answered, I thought I'd go ahead and add this:
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.
Link: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Related
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.
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++;
}
I'm a beginner in java and it is my only code I know how to use so far. I'm working on a food system for an RPG game. Basically it displays a list of the available food items and ask you to press number to eat . After pressing a number, it prints out what you have decided to eat based on what your number corresponded to. I then need to retrieve what "food" you ate so that I can use it's stats. Here's what I have so far:
public String eatmenu() {
System.out.print ( "Consumables: ");
for ( Sustenance consum : consumables ) {
System.out.print ( "[" + consum + "], " );
}
int number = consumables.size();
int counter = 1;
while ( counter <= number ){
System.out.print ("\nPress " + counter + " to consume " + consumables.get(counter-1));
counter++;
}
int choice = reader.nextInt();
String eatchoice = "You decided to consume " + consumables.get(choice-1);
return eatchoice;
}
public String eat3(){
//the food just eaten,
}
Heres the code for the Food Class or "Sustenance":
public class Sustenance extends Item {
String n;
int v;
int s;
public Sustenance ( String name, int Nvalue, int size ){
n= name;
Nvalue = v;
size = s;
}
public String toString() {
String str = "The " + n + "increased your Nutrition level by " + v + ".\nYour backpack is also " +
s + " pounds lighter.";
return str;
}
}
Any ideas are appreciated as to what to put for the eat3 method. I know I will be using the toString method in order to print out the effects of eating the specific item but how do I refer to the item I just ate? I will take everything as critique. Thank you for your time.
Use JavaBeans to set the food and then get it. For example:
public class FoodBean{
public FoodBean(){}
private String foodName;
// other fields which you wana set or get
public void setFoodName(String foodName){
this.foodName = foodName;
}
public String getFoodName(){
return this.foodName;
}
// override the toString() if you want the object to represent the foodName stored
#Override
public String toString(){
return this.foodName;
}
}
Ok so now we have a BeanClass..
now you need to create a bean object whenever the user clicks any item
FoodBean fb = new FoodBean();
fb.setFoodName("get food name from the mapped list here against its number");
now use getFoodName() anywhere in the program, just be careful, the bean object above has local scope if you create it in a method, you need to make a same reference to FoodBean globally and assign the new created object to it, and then use that global reference anywhere in the class.
Further take a look at this simple tutorial
I am studying loops and am attempting a sample question here to use only a loop to ask the user to enter in the name of the person, height in feet first, then inches and then to find the tallest. I understand how to do the majority of it.
Could anyone point out where I am going wrong? I began writing the code and realised that I can't declare the persons names without knowing how many people the user will enter. I can't get my head around it.
I want to prompt the user with the questions but also update it to person [2], person [3], person [4] etc. depending on how many people they entered in initially.
Apologies for not wording this correctly. Any help is appreciated. I understand lines 10, 11 and 12 are probably wrong.
class HeightTest
{
public static void main(String[] args)
{
int noOfPeople;
int index;
int feet;
int inches;
String personOne;
String personTwo;
String personThree;
System.out.print("Enter a number of people ");
noOfPeople = EasyIn.getInt();
for (index = 1; index <=noOfPeople; index++)
{
System.out.println("Enter the name of person " + index);
personOne = EasyIn.getString();
System.out.println("Enter feet portion for " + personOne);
feet = EasyIn.getInt();
System.out.println("Enter inches portion for " + personOne);
inches = EasyIn.getInt();
}
}
}
You have a very good start. All you need to do now is keep track of the heights that are entered, and compare them to the largest one input so far. If the height for the current loop iteration is larger than the current largest, store it as the largest.
In pseudocode:
int largestHeightInches = 0;
for( i = 1; i <= noOfPeople; index++ ) {
currentHeightFeet = GetInt();
currentHeightInches = GetInt();
currentHeight = currentHeightInches + currrentHeightFeet * 12;
if( largestHeightInches < currentHeight ) {
largestHeightInches = currentHeight;
}
}
You would have to create an array of Persons to acheive what you want.
Here's a snippet.
Create a class called Person
public class Person
{
int index;
int feet;
int inches;
String name;
}
create a main Test class to contain your main method, and do something like this
public class Main{
public static void main (String[] args)
{
// get the number of people in noOfPeople as you do now.
Person[] pArray= new Person[nOfPeople]
for(Person p: pArray)
{
System.out.println("Enter the name of person " + index);
p.name = EasyIn.getString();
// ...etc
}
}
}
I wrote a program which counts the number of rooms for each class (art, sport, etc).
For example, each class contains a maximum of 3 students. If I have 9 students, with 6 music students and 3 art students,the results have to be: 1 room for art and 2 rooms for music.
When I run the code, I get these wrong results: the number of rooms for art equals 2 instead of 1 and the number of rooms for music equals 1 instead of 2.
Here is the result of execution of this program:
Insert numbers of participants:
9
Insert student in class:
1
Insert student in class:
1
Insert student in class:
1
The number of rooms for Music is:1
Insert student in class:
1
Insert student in class:
1
Insert student in class:
1
Insert student in class:
2
Insert student in class:
2
Insert student in class:
2
The number of rooms for Art is:2
This is my code:
import java.util.Scanner;
public class GroupActivity
{
public static void main()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int countM=0; //This variable contains the number of the participants in music class.
int countA=0; //This variable contains the number of the participants in art class.
int countT=0; //This variable contains the number of the participants in theatre class.
int countS=0; //This variable contains the number of the participants in sport class.
int countOFR=0;
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.int
if(p==music)
//for(
{
countM++;
int M=countM;
//System.out.println("student in class:"+music);
//System.out.println("Total music class:"+M);
if(M==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
}
else if(p==art)
{
countA++;
int A=countA;
// System.out.println("student in class:"+art);
if(A==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Art is:"+countOfRoom);
}
//System.out.println("Total student in art class:"+A);
}
else if(p==theatre)
{
countT++;
int T=countT;
// System.out.println("student in class:"+theatre);
//System.out.println("Total thaetre class:"+T);
if(T==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Theatre is:"+countOfRoom);
}
}
else{
countS++;
int S=countS;
if(S==3)
{
countOFR++;
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Sport is:"+countOfRoom);
}
//System.out.println("Total sport class:"+S);
}
}
}
}
The problem is with countOFR. You are using this to store the no of rooms for all classes, instead of any one. Thus when you read data for class, the older value of countOFR gets added.
if(M==3)
{
countOFR++; // This should not be common for all
int countOfRoom=+countOFR;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
instead use different variables
int countOFR_music = 0;
int countOFR_art = 0;
int countOFR_theatre = 0;
int countOFR_sport = 0;
then use it like this
if(M==3)
{
countOFR_music++; // This should not be common for all
int countOfRoom=+countOFR_music;
System.out.println("The number of rooms for Music is:"+countOfRoom);
}
likewise for arts class
if(A==3)
{
countOFR_art++;
int countOfRoom=+countOFR_art;
System.out.println("The number of rooms for Art is:"+countOfRoom);
}
I think you should count students on each class, then process them at the end.
First, declare one or more object to hold number of student. Your declaration could work fine, but to shorten your code, you should use an array:
int numOfStudent[] = new int[4]; // 4 is for 4 types of class
Then in the for loop, do a check before increase counter, may be ask use input again (it's up to you):
// ...
int p= GActivity.nextInt();
int idx = p - 1; // Convert to zero-base index
if (idx >= 0 && idx < numOfStudent.length()) {
numOfStudent[idx]++;
}
Finally, out of for loop, just process them. Because each class contains maximum 3 student, we have:
int numOfMusicClass = (int)Math.ceil(numOfStudent[music - 1] / 3.0);
// ... Do the same for other class
Hopefully, this solution help you!
In addition, your class type is defined by number, thus, you should print out what number represents. For example:
Insert student in class (1 - music, 2 - art, 3 - theatre, 4 - sport):
It will make user aware what he/she input.
Here is a much shorter code:
public class GroupActivity
{
public static void main()
{
Scanner GActivity=new Scanner(System.in);
System.out.println("Insert numbers of participants:");
int participantNo= GActivity.nextInt();//Insert numbers of participants
int music= 1;int art=2; int theatre= 3; int sport= 4; // Representation of each class by numbers.
int[] counts = new int[4]; //This variable contains the number of the participants in music, arts, theatre and sports classes in its 4 cells.
for(int i=0;i<participantNo;i++)
{
System.out.println("Insert student in class:");
int p= GActivity.nextInt();// // Representation of student by number.int
if(p<=4)
counts[p-1]++;
}
System.out.println("The number of rooms for Music is:" + Math.ceil(counts[music-1]/3.0));
System.out.println("The number of rooms for Art is:" + Math.ceil(counts[art-1]/3.0));
System.out.println("The number of rooms for Theatre is:" + Math.ceil(counts[theatre-1]/3.0));
System.out.println("The number of rooms for Sports is:" + Math.ceil(counts[sport-1]/3.0));
}
}
Write smaller functions. This is too big to read.