How to receive data for object within a for-loop - java

I'm trying to write a code where I have two object for a class. I want to use the same for-loop to produce sum of loop for each object. How do I do this? Also, I only have the code created for c1, is there a way I can also write it for c2 without redundancy in the code?
I only provided some code from the files where I am having issues with.
Calorie.java
public void setCalorieSum(int calorieSum) {
this.calorieSum = calorieSum;
}
public void setMealsAte(int mealsAte) {
this.mealsAte = mealsAte;
}
CalorieTester.java
Calorie c1 = new Calorie();
Calorie c2 = new Calorie();
int num = 1;
System.out.println("Information for Day #" + num +": ");
c1.setMealsAte(number(console, "\t how many meals did you eat? "));
for(int j = 1; j < c1.getMealsAte() + 1; j++) {
c1.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
int calorieSum += d1.setCalorieSum();
}
System.out.println("-- Total caloric intake = \n"/* + c1.getCalorieSum + " --"*/);
num++;

Your idea looks correct. Howver you need to intilize and delcare the int calorieSum before the for loop like:
int calorieSum=0
for(int j = 1; j < c1.getMealsAte() + 1; j++) {
c1.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
calorieSum += d1.setCalorieSum();
}
Also if I am understanding the purpose of your code right where c1 and c2 are different entities that need to be filled in by the user you can just make the for loop you have created to:
int calorieSum1=0;
int calorieSum2=0;
for(int j = 1; j < c1.getMealsAte()+c2.getMealsAte() + 1; j++) {
if (j<c1.getMealsAte()){
c1.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
calorieSum1 += d1.getCalorieSum();
}
else {
c2.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
calorieSum2 += d2.getCalorieSum();
}
}
}
d1.setCalorieSum(calorieSum1);
d2.setCalorieSum(calorieSum2);
And then make 1 getter methods
public void getCaloriesSum(){
return this.calorieSum;
}

Related

How to let a for loop do my objectList printing

Hi I want to put my prints in a for-loop. how to do it? So something like
if index = 0,1,2 print.
if index = 2,3,4 print.
if index = 4,5,6 print.
Code:
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.println("\n\nThis starts to look like calculations:");
System.out.print("\n" + objectList.get(0));
System.out.print(" "+ objectList.get(1));
System.out.print(" " + objectList.get(2) + " =");
System.out.print("\n\n" + objectList.get(2));
System.out.print(" " + objectList.get(3));
System.out.print(" " + objectList.get(4)+ " =");
System.out.print("\n\n" + objectList.get(4));
System.out.print(" " + objectList.get(5));
System.out.print(" " + objectList.get(6) + " =");
output:
This starts to look like calculations:
1 + 3432.123 =
3432.123 * 4535 =
4535 - 24.4 =
private String buildOperation(int pos){
String output;
if(pos == 0) {
output = "+";
}else if(pos == 1){
output = "*";
}else {
output = "-";
}
return output;
}
List<Object> objectList = new ArrayList(res);
for(int i = 0; i < objectList.size()-1; i++){
System.out.println(objectList.get(i) + buildOperation(i) + objectList.get(i+1) + "=");
}
Additionaly I'll use a HashMap with the operations to avoid all if/else conditions
Map<Integer,String> operations = new HashMap{}
operations.put(0,"+");
operations.put(1,"*");
operations.put(2,"-");
System.out.println(objectList.get(i) + operations.get(i) + objectList.get(i+1) + "=");
}
Final solution now the String size does not matter anymore.
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\n\nThis starts to look like calculations:");
int maxi= objectList.size();
maxi = maxi -2;
System.out.println("\n\nmaxi = " + maxi);
for (int i = 0; i < maxi; i+=2) {
System.out.println("");
System.out.println(i);
System.out.print("\n\n" + objectList.get(i));
System.out.print(" " + objectList.get(i + 1));
System.out.print(" " + objectList.get(i + 2)+ " =");

My for loop is only going through once

I wrote this code here. It is supposed to print out the iteNum.length (array) which is determined by the user input, but it only does one iteration and then it stops. I can't figure out why.
for (int i = 0; i < iteNum.length; i++) {
System.out.print("Num:" + (i+1) + " ");
for (i = 0; i < cMiles.length; i++) {
System.out.print(" (sc" + (i+1) + ":)" + cRandom[i] + " (tsc" + (i+1) + ":)" + df.format(cTimes[i]) + " ");
}
for (i = 0; i < fMiles.length; i++){
System.out.print(" (sf"+ (i+1) + ":)" + df.format(fRandom[i]) + " (tsf" + (i+1) + ":)" + df.format(fTimes[i])+ " " );
}
System.out.print("(cT:)" + df.format(cSum) + " (fT:)" + df.format(fSum));
if (cSum < fSum) {
System.out.print(" City is faster");
}
else {
System.out.print(" Freeway is faster");
}
}
You're reusing the same i variable in the inner and outer loops. Use separate variables.
for (int i = 0; i < iteNum.length; i++) {
for (int j = 0; j < cMiles.length; j++) {
...
}
}
As say #John you are using same iterator variable i, instread of using another one
And also this code can be simplified
if (cSum < fSum) {
System.out.print(" City is faster");
}
else {
System.out.print(" Freeway is faster");
}
like that
System.out.print((cSum < fSum) ? " City is faster" : " Freeway is faster");
On my opinion ternary operator more clear.

Java: Count every number in the array

I want to count the occurrence of every number that appears in the array. I've seen other answers, but I do not understand why my method does not work. I have an Array with random numbers:
int[] fält = new int[20]
This is what I did:
public static String statistik(int[] fält) {
String poäng[] = new String[20];
String output = "";
//Clear out the array:
for (int i = 0; i < poäng.length; i++) {
poäng[i] = "";
}
//Add a star for each time a number appears
for (int i = 0; i < fält.length; i++) {
for (int t = 0; t < fält.length; t++) {
if (fält[t] == i) {
poäng[i] += "*";
}
}
}
//Print it out
for (int i = 0; i < fält.length; i++) {
output += (i + 1) + ": " + poäng[i] + "\n";
}
JOptionPane.showMessageDialog(null, output);
return "";
}
Not all numbers get a star and it all ends up weird. Why?
You are checking if (fält[t] == i) please change it to if (fält[t] == fält[i])
This line :
output += (i + 1) + ": " + poäng[i] + "\n";
this will start to print "1 :" BUT you count from 0 that's why the output seems weird.
public static String statistik(int[] fält) {
String poäng[] = new String[fält.length];
String output = "";
//Clear out the array:
for (int i = 0; i < poäng.length; i++) {
poäng[i] = "";
}
//Add a star for each time a number appears
for (int i = 0; i < fält.length; i++) {
for (int t = 0; t < fält.length; t++) {
if (fält[t] == i) {
poäng[i] += "*";
}
}
}
//Print it out
for (int i = 0; i < fält.length; i++) {
output += i + ": " + poäng[i] + "\n";
}
System.out.println(output);
return "";
}
1)Hi, #Habbo, it is because the flat[] array only consists 0's
2) only in first iteration i value will be 0 and then it never be zero again.
if (fält[t] == i) {
poäng[i] += "*";
}
4)so poäng[i] inside this "i" will only zero and never increases
5) that is why you are having weird result
you should change the output message
from output += (i + 1) + ": " + poäng[i] + "\n";
to output += i + ": " + poäng[i] + "\n";
at all i think you could optimize your code
by sort it first this will cost 2 Loops
then loop upon the sorted array like this
int temp= fält[0];
output = temp + ": *";
for (int i = 1; i < fält.length; i++) {
if(fält[i] >temp){
temp = fält[i];
output +="\n"+ temp + ": *";
}
else{
output +="*";
}
}
you will have only 3 Loops In your Code not 4

How do I return the array values despite being inside a nested for loop?

for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}

Accessing variables of an instance stored in an Object

I can't seem to access any get/set methods or the variables directly from an object. I'm attempting to get the level of my enemy which is stored in a variable as below. The last line, I 'want' to do "World[i][j].enemy.getLevel()" but apparently that is an illegal move? At the moment it just prints the objects id reference.
Is there a conversion back to an object i'm missing?
The Monster class extends Player.
Creation:
World[i][j].enemy = spawnEnemy(World[i][j].mapLevel); //Spawn a monster.
Other code:
public static Object spawnEnemy(int level) {
//Spawns a monster and returns the Object.
Monster enemy = new Monster();
enemy.setLevel(level);
enemy.setMaxHealth(level * 5);
enemy.setHealth(enemy.getMaxHealth());
enemy.setDamage(enemy.getLevel() * 3);
return enemy;
}
public static void enemiesAlive() {
for (int i = 0; i < mapSizeX; i++)
{
for (int j = 0; j < mapSizeY; j++)
{
if (World[i][j].enemyAlive)
{
System.out.print(i + "-" + j + " with a level of " + World[i][j].enemy + ", ");
}
}
}
}
The last line, I 'want' to do "World[i][j].enemy.getLevel()"
The problem is that you forgot the call to getLevel() and simply print the object reference.
Change
System.out.print(i + "-" + j + " with a level of " + World[i][j].enemy + ", ");
for
System.out.print(i + "-" + j + " with a level of " + ((Player)World[i][j].enemy).getLevel() + ", ");

Categories

Resources