javastringincompatibletypeerror

Java "incompatable types" still not understood; What is wrong?


It seems that it is correct, I just need help to find out why it is giving me this error. Here is the prompt:

1.Create a MyStr class

2.Write a method in MyStr Class called break( ). The method break( ) accepts a string as its parameter and returns the string with last two characters in the front.

Here is an example of the output:

  1. MyStr.break(Hello) returns loHel

    Mystr.break(Active) returns veActi

Here is my code so far:

public class Main {
  public static void main(String[] args) {
    MyStr.strBreak("Morse");
    MyStr.strBreak("School");
  }
}

public class MyStr{
  public static void strBreak(String word){
    int x = word.length() - 2;
    return(word.substring(x) + word.substring(0, x));
  }
}

Solution

  • change

    public static void strBreak(String word){
    

    to

    public static String strBreak(String word){
    

    because this method returns a string.

    a keyword void means 'nothing' and it's used to declare a method that returns nothing. If a method returns anything, you should specify a correct data type in the method declaration.