0

I'm trying code a basic application that will take the amount of numbers the user wants to input and then ask the user for the numbers, save the the numbers in a string array and then print them out in specific format.

this is what I have so far the only problem is I need to remove the last comma at the end of the output, I'm sure I'm going about this wrong... any assistance is appreciated.

import java.util.Scanner;
public class info {
    public void blue(){
        Scanner sc = new Scanner(System.in);
        Scanner dc = new Scanner(System.in);
        System.out.println("how many numbers do you have?");
        int a = dc.nextInt();
        System.out.println("enter your numbers");

        String index[]=new String [a];
        String i;

        for(int k = 0;k<index.length;k++){
            i = sc.nextLine();
            index[k]=i;
            }

            System.out.print("query (");

            for(int l = 0;l<index.length;l++){
            System.out.printf("'%s',",index[l]);
            }

            System.out.print(")");
    }
}
Snarf
  • 2,251
  • 1
  • 15
  • 17
  • 2
    You'll want to work on your code indentation. You might get marks for creativity but not for readability. – Hovercraft Full Of Eels Sep 23 '11 at 17:54
  • possible duplicate of [How to emit a comma-separated list?](http://stackoverflow.com/questions/6665441/how-to-emit-a-comma-separated-list) – starblue Sep 23 '11 at 18:03
  • possible duplicate of [Clearest way to comma-delimit a list (Java)?](http://stackoverflow.com/questions/668952/clearest-way-to-comma-delimit-a-list-java) – starblue Sep 23 '11 at 18:05
  • possible duplicate of [Last iteration of for loop in java](http://stackoverflow.com/questions/285523/last-iteration-of-for-loop-in-java) – starblue Sep 23 '11 at 18:08
  • possible duplicate of [What's the best way to build a string of delimited items in Java?](http://stackoverflow.com/questions/63150/whats-the-best-way-to-build-a-string-of-delimited-items-in-java) – starblue Sep 23 '11 at 18:10

10 Answers10

5
for(int l = 0;l<index.length;l++){
    if(l==index.length-1)
        System.out.printf("'%s'",index[l]);
    else
        System.out.printf("'%s',",index[l]);
}
Danny
  • 7,368
  • 8
  • 46
  • 70
3
 Arrays.toString(array).replaceAll("[\\[\\]]", "");
dacwe
  • 43,066
  • 12
  • 116
  • 140
2

This requires no if check for each element in your array:

if(index.length > 0) {
    for(int l = 0;l<index.length-1;l++){
        System.out.printf("'%s',",index[l]);
    }
    System.out.printf("'%s'",index[index.length-1]);
}
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
2

Much cleaner approach could be,

String comma="";

for(int l = 0; l<index.length; l++)
{
   System.out.printf("'%s''%s'", comma, index[l]);
   // Now define comma
   comma = ",";
}
tryurbest
  • 1,419
  • 1
  • 12
  • 22
  • I believe your parameters to `printf` need to be reversed. Right now, "a,b,c" would be printed as "ab,c," – Dilum Ranatunga Sep 23 '11 at 18:03
  • @DilumRanatunga Thanks for catching that. – tryurbest Sep 23 '11 at 18:07
  • Excellent answer (as it's almost the same as mine). Except you need to initialize comma for the first time through the loop, i.e. you should start with String comma=""; not just String comma; – Jay Sep 23 '11 at 18:17
  • @Jay smade the change.. sorry I am new to Java.. you should consider voting the answer up ;) – tryurbest Sep 26 '11 at 15:56
1

You can use substring method of String to strip the comma in the end. It is also better to use StringBuilder.append when doing concatenation in a loop.

Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43
  • 1
    I think that you meant StringBuilder rather than StringBuffer. I see nothing in his code to suggest the need for the overhead of this being thread-safe. But having said this, given the scale of his application, probably the use of StringBuffer or StringBuilder should be classified under *unnecessary optimization* as the rate limiting step will not be String object creation but rather user text entering. – Hovercraft Full Of Eels Sep 23 '11 at 17:55
  • Corrected. I was just pointing that instead of calling multiple sys outs one can construct the desired string and output it at once. – Narendra Yadala Sep 23 '11 at 18:00
1

This is displaying each string on its own line, with a comma at the end. If you want all of the words on one line, separated by commas, then replace

for(int l = 0;l<index.length;l++){
    System.out.printf("'%s',",index[l]);
}

with

StringBuilder buf = new StringBuilder();

for(int l = 0;l<index.length;l++){
   buf.append(index[l]);

   if (l != (index.length - 1)) {
       buf.append(",");
   }
}

System.out.println(buf.toString());
NRitH
  • 13,441
  • 4
  • 41
  • 44
1

Been in the C# world for a while so the code may not be exact, but this should work

StringBuilder sb = new StringBuilder();
for(int l = 0;l<index.length;l++){
  sb.Append(index[l] + ";");
}
sb.deleteCharAt(sb.Length - 1);
System.out.print(sb.ToString());

This will save your code from having to write to the output over and over, so there is less overhead as well.

DJ Quimby
  • 3,669
  • 25
  • 35
1
}
System.out.print("\b");//<---------
System.out.print(")");

Why not use a String buffer and output it in the end?

象嘉道
  • 3,657
  • 5
  • 33
  • 49
1

import apache StringUtils, then do

StringUtils.join( index, "," );
digitaljoel
  • 26,265
  • 15
  • 89
  • 115
1

Much simpler is:

String conj="";
for(int l = 0;l<index.length;l++){
  System.out.print(conj);
  System.out.print(index[l]);
  conj=",";  
}  

You have to do this sort of thing so often, I routinely write a little "joiner" class:

public class Joiner
{
  private String curr;
  private String conj;
  private StringBuilder value;

  public Joiner(String prefix, String conj)
  {
    this.curr=prefix;
    this.conj=conj;
    value=new StringBuilder();
  }
  public Joiner(String conj)
  {
    this("", conj);
  }
  public Joiner append(String s)
  {
    value.append(curr).append(s);
    curr=conj;
    return this;
  }
  public String toString()
  {
    return value.toString();
  }
}

Then you can build a concatenated string with code like:

Joiner commalist=new Joiner(",");
for (String one : many)
{
  commalist.append(one);
}
System.out.println(commalist.toString()); // or whatever you want to do with it

Or like to build a WHERE clause:

Joiner where=new Joiner(" where ", " and ");
if (foo!=null)
{
  where.append("foo="+foo);
}
if (bar!=null)
{
  where.append("bar="+bar);
}
String sql="select whatever from wherever"+where;
Jay
  • 26,876
  • 10
  • 61
  • 112