-2

In the following snippet:

static Scanner userInput = new Scanner(System.in);
static String str;

public static void main(String[] args) {

    str = userInput.nextLine();

}

 public String wordSplitter() {     
    char b;     

    for(int i = 0; i < numbers.length(); i += 1) 
    b = str.charAt(i);
    return b;       
}

the statement "return b;" gives me an error because my method should return a String, but b is a char.

So how do I somehow make b into a String? Or is there a better way to split Strings into letters of type String?

thanks

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
DDC ll
  • 5
  • 1

5 Answers5

1

How about this?

public String splitStringIntoLetters(){
        String toBeSplit = "abcdefg";
        char [] toBeSplitChar = toBeSplit.toCharArray();
        return java.util.Arrays.toString(toBeSplitChar);
}

this returns something like: [a, b, c, d, e, f, g]

Once you get the string just perform the operation that you want on the string. e.g.

String testStr = splitStringIntoLetters();
System.out.println(testStr.replace("["," ").replace("]"," ").split(","));
0

There are many ways to achieve that, you can use/return Character.toString(b) or String.valueOf(b) static methods.

here and here the Doc

public String wordSplitter() {     
    char b;     
    ....// do something and assign b
    return Character.toString(b);       
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0
public String wordSplitter() {     
    char b;     

    for(int i = 0; i < numbers.length(); i += 1) 
    b = String.valueOf(str.charAt(i));
    return b;       
}

You can try above code.

   String string = Character.toString(ch);
   String string = String.valueOf(ch);

This both above method can convert your character to String. Hope this will helps you.

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38
0

You can try it like these,first of all I think it should be i<str.legth; and you can handle it like this, return b+"";

Pshemo
  • 122,468
  • 25
  • 185
  • 269
jean wong
  • 1
  • 1
0

Seems your code is mainly designed to eat CPU performance.

Normally you would replace :

for(int i = 0; i < numbers.length(); i += 1) 
    b = str.charAt(i); 
return b;

By

return str.charAt(numbers.length()-1);

And if you insist on returning a String you would do

 return String.valueOf(str.charAt(numbers.length()-1));

... but I struggle understanding what the purpose of this could be

j3App
  • 1,510
  • 1
  • 17
  • 26