My for loop is only going through once - java

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.

Related

Make sure a String[] contains 5 letter "A" at different index

So i'm trying to make a program which create and print an array made of 29 index with 5 of those being "A" and the 24 others being "-". I've ran across the problem where it's either giving me an outofbound error or just not putting 5 "A" on the board.
Here is what i've tried so far.
static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{ //ADD "A" TO RANDOM INDEX IN BOARD
int x = 5;
while (checkForAInArray(board)==false) {
for (int i = 0; i < x; i++) {
int j = (int)(Math.random()*board.length);
while(board[j-1].equals("A") || board[j+1].equals("A")){ //Make sure there's no A beside another "A"
j = (int)(Math.random()*board.length);
}
board[j] = "A";
}
x = CountAInArray(board);
}
return board;
}
static boolean checkForAInArray(String[] board){ //Make sure there is 5 "A" in the program
int countOfA = 0;
for (int i = 0; i < board.length; i++) {
if(board[i].equals("A")){
countOfA++;
}
}
if(countOfA==5){
return true;
}
else{
return false;
}
}
static int CountAInArray(String[] board){ //Control the number of time the For-loop of
placeRandomAppleAroundBoard
iterate, which is 5 based and then change depending on how much "A" there's on the board
int countOfA = 0;
for (int i = 0; i < board.length; i++) {
if(board[i].equals("A")){
countOfA++;
}
}
if(countOfA==0){
return 5;
}
else{
return 5 - countOfA;
}
}
So as you can see, i've tried to control the number of time the ForLoop add "A" in the board, that didn't work. I've also tried check for the number of "A" already present in the board but that didn't seem to do the tricks
I am expecting a board printed like so :
static void printboard(String[] board){
System.out.println(board[0] + "|" + board[1] + "|" + board[2] + "|" + board[3] + "|" + board[4] + "|" + board[5] + "|" + board[6] + "|" + board[7] + "|" + board[8] + "|" + board[9]);
System.out.println(board[10] + "|" + board[11] + "|" + board[12] + "|" + board[13] + "|" + board[14] + "|" + board[15] + "|" + board[16] + "|" + board[17] + "|" + board[18] + "|" + board[19]);
System.out.println(board[20] + "|" + board[21] + "|" + board[22] + "|" + board[23] + "|" + board[24] + "|" + board[25] + "|" + board[26] + "|" + board[27] + "|" + board[28] + "|" + board[29]);
}
Thanks for you're help!!
So, i've found the trick ! ahahah, pretty simple actually, here it is :
static String[] placeRandomAppleAroundBoard(String[] board) throws java.lang.ArrayIndexOutOfBoundsException{
int iterationNumber = checkForNumberOfAInArray(board);
for (int i = 0; i < iterationNumber; i++) {
int j = (int)(Math.random()*board.length);
while(board[j-1].equals("A") || board[j+1].equals("A") || board[j].equals("A")){
j = (int)(Math.random()*board.length);
}
board[j] = "A";
}
return board;
}
static int checkForNumberOfAInArray(String[] board){
int countOfA = 0;
for (String x : board) {
if(x == "A"){
countOfA++;
}
}
System.out.println(countOfA);
return (5 - countOfA);
}
And then, you basically use the second function to iterate X number of time with the first function.
What about:
String[] board = new String[29];
Arrays.fill(board, "-");
for(int i = 0;i < 5;i++) {
board[i] = "A";
}
Collections.shuffle(Arrays.asList(board));
System.out.println(Arrays.toString(board));

How to receive data for object within a for-loop

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

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)+ " =");

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.");
}
}
}

Categories

Resources