thales78
thales78

Reputation: 43

How do i make this function of chars work in java

Given a character from A to U, print the character and the next 5 characters in the alphabet (space-separated). Print the characters in the same case as the given one.

    static void doStuff(char c){
    for(char i='c'; i<='c'+5;i=i+1){
        System.out.print(c+"");
    }
}

Upvotes: 1

Views: 57

Answers (4)

Error in your code. In for loop remove singlequotes around c , use preincrement i(i++) and print i not c .Below code work fine.

static void doStuff(char c){
   for(char i=c; i<=c+5;i++){
      System.out.print(i+" ");
   }
}

Upvotes: 2

k.shamsu
k.shamsu

Reputation: 69

You may try this -

static void doStuff(char c){

        for(int i = c; i<=c+5; i++){
            System.out.print((char)i +" ");
        }
}

Upvotes: 0

Razib
Razib

Reputation: 11163

Try this -

public class Alphabets{

    public static void main(String args[]){

        //char c = 'p';
        char c = 'P';

        for(int i = c; i<=c+5; i++){
            System.out.print((char)i +" ");
        }
    }
}  

Some points at for at you loop -

for(char i='c'; i<='c'+5;i=i+1)

1. char i='c'. Which is incorrect in this context. Now it is referencing the character 'c' whatever the given character to you function is. I have changed it to i=c.

2. if you write i<='c'+5 then there may be an error occurred (based on you jvm version) - possible loss of precision while converting the int result of the assignment (from right side) to the i (at left side).

Upvotes: 1

sziolkow
sziolkow

Reputation: 173

class Alphabets
{
    public static void main(String args[])
    {
        char ch;

        for( ch = 'a' ; ch <= 'a'+4 ; ch++ )
            System.out.println(ch);
    }
}

Upvotes: 1

Related Questions