1

this is not a homework assignment. I am just practicing to improve my skill. This question has been answered before, but I am confused. If someone could explain me step by step then I would be able to understand better. I do not want to copy and paste. I want to learn and my professor never taught me how to remove the last comma from the list. Thank you for your help and support.

public static void print(int[] list){    
    System.out.print("[ ");
    for(int i = 0; i < list.length; i++){      
        System.out.print(list[i]);    
        for(int j = 0; j <1; j++){      
            System.out.print(",");
        }
    }
    System.out.print("]"); 
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
happy face
  • 43
  • 9
  • I don't understand the question, what comma are you talking about? – Arash Saidi Dec 28 '14 at 00:39
  • @ArashSaidi OP is printing the element and printing the comma every time. The inner for loop always runs of exactly once. So the output is 1,2,3,4, when they want it to be 1,2,3,4 without the 4th comma – Evorlor Dec 28 '14 at 00:40
  • 1
    *"I want to learn and my professor never taught me how to remove the last comma from the list."* - And he shouldn't have to!! Your professor's job is to teach you how to program ... not to teach you the solution to every possible programming problem. You are supposed to be learning how to solve programming problems yourself. – Stephen C Dec 28 '14 at 00:47
  • Stephen C is right. But to clarify what he is saying, your early teachers show you how to do addition 1 through 10 or something. It is expected that you can do 372752+363627 on your own. Otherwise it would take a really long time to learn addition. It's the same idea with coding – Evorlor Dec 28 '14 at 00:52
  • That is true, but the analogy is not perfect. In the case of arithmetic your teachers teach you a *procedure* or *algorithm* that can be used to add numbers of any size. In the case or programming, no such procedure or algorithm exists ... even for solving relatively simple programming problems. Instead, you (the programmer) need to learn to apply your knowledge with reasoning and creativity to work out the solution to the problem. Some of that knowledge will be taught to you, but most of it you will need to learn (or work out) for yourself. – Stephen C Dec 28 '14 at 00:59

1 Answers1

2

Your inside for loop does nothing. It runs exactly once every time, so it may as well not be there. Change it to an if statement to check if it is (not) the last element.

Evorlor
  • 7,263
  • 17
  • 70
  • 141