如何将void语句转换为返回字符串的return语句?

时间:2012-10-29 16:33:35

标签: java apache-pig

好吧所以我尝试将下面的语句转换为返回finalString的return语句,但它始终告诉我,即使我确实返回finalString“这句话 必须返回一个String类型的变量“。我已经尝试将return finalString放在for语句中的每个if语句中,但它不起作用。我非常感谢任何帮助或建议。 [更新代码]仍然无法正常工作。 finalString值不会被修改 if语句,这正是我想要的。我想也许finalString值不会通过if语句?

[代码]

import java.util.Scanner;
public class pLat//pig latin program
{

    /**
       * Method to test whether a character is a letter or not.
       * @param c The character to test
       * @return True if it's a letter
       */
      private static boolean isLetter(char c) {
        return ( (c >='A' && c <='Z') || (c >='a' && c <='z') );
      }


    ///////////////////////////////////////////
      private static String output(String input)//processes the word using basic rules including the q and u rule
      {

          //the string that will hold the value of the word entered by the user
          char s;//the first character of the string
          char m;
          int l = input.length();//determines the length of the string
          String endString;
          String startString;
          String finalString = ""; //the final output
          String mtr;
          String lowercase;//the entered string all converted to lowercase

          for(int k =0;k<l;k++)//checks all letters in order to see which is a vowel
          {

              s = input.charAt(k);

          if(s == 'q'|| s=='Q' && input.charAt(k+1)=='u')//if the first vowel is a "u" and the letter before it is a "q"
          {


                  endString = input.substring(0,k+2);//makes the endString also include u
                  endString = endString +"ay";
                  startString = input.substring(k+2,l);
                  finalString = startString + endString;
                  //System.out.println(finalString);
                  return finalString;


          }

          if(s=='a'||s=='e'||s=='i'||s=='o'||s=='u'||s=='A'||s=='E'||s=='I'||s=='O'||s=='U'||s=='y'||s=='Y')//if its a vowel or "y" than executes commands below
          {

              endString = input.substring(0, k);//gets the letters before the vowel
              endString = endString + "ay";
              startString = input.substring(k,l);//gets the letters after the vowel
              finalString = startString + endString;
              //System.out.println(finalString);//prints the final result which is the combination of startString with endString
              //stops code after doing the above
              return finalString;

          }


          else if(k==l-1)//if its the end of the word
          {
              finalString = "ERROR";
              return finalString;

          }

         }
          System.out.println(finalString);
          return finalString;
}///////////////////////////////////

//   public static void process(String input)//will take care of the punctuation
//   {
//       String latin = "";
//          int i = 0;
//          while (i<input.length()) {
//
//            // Takes care of punctuation and spaces
//            while (i<input.length() && !isLetter(input.charAt(i))) {
//              latin = latin + input.charAt(i);
//              i++;
//            }
//            latin = latin + output(input);
//            System.out.println(latin);
//          }
//          
//    }


    public static void main(String[] args)
    {

        String str;//this will be the input string by the user
        Scanner scanner = new Scanner(System.in);//this scanner will register the input value
        System.out.println("Enter a Word: ");
        str = scanner.next();//stores the input string

        output(str);//outputs it using basic gramatical rules

    }

}

3 个答案:

答案 0 :(得分:1)

您的方法中的每个return本地块都应该有一个top-level语句。如果您没有,那么在该顶级块内的每个return中都有一个block语句。等等。

让我们考虑一组 if - else if - else 中最简单的情况: -

您需要从每个ifelse块中返回字符串,因为只会执行其中一个。所以,如果你错过了其中一个中的return语句,那么很可能在执行block时,肯定会错过return语句。如果您在method

结尾处没有任何退货声明

所以,基本上,你的return语句必须出现在每个块中,其执行不需要执行任何其他块,如果这些块涵盖条件可能具有的所有可能性,那么你不需要返回街区外的声明。因为其中一个块肯定会执行。

另外,如果那些blocks未涵盖特定条件(like if you are not having an其他for a set of if-else-if)的所有可能性,那么您必须在这些块之外添加return语句。因为,如果这些块都不执行,那么method将错过return语句。

所以,例如您可以看到以下代码集,涵盖最可能的可能性: -

public String returnString() {
        if (..) {
             return "someString";

        } else if (...) {
             return "someString";

        } else {
             return "someOtherString";
        }
       // return statement here is not needed. Because at least `else` will execute
}

因此,ifelse ifelse中至少有一个将始终执行。因此,您可以在其中添加return语句,并将return语句保留在这些块之外。

但是,如果您的上一个else块是else if,那么blocks可能无法执行。在这种情况下,您必须在这些块之后放置一个return语句。

public String returnString() {
        if (..) {
             return "someString";

        } else if (...) {
             return "someString";

        } else if (...){
             return "someOtherString";
        }
       // return statement here is needed. 
       // Because its possible that none of the blocks in `if-else` set get executed.
}

另一种可能性是,您可以将return value存储在某个局部变量中,而不是从每个块返回,并在所有块的末尾返回value局部变量作为你方法中的最后一个陈述。

public String returnString() {
    int returnValue = 0;
    if (..) { returnValue = someValue; }
    else if(...) { returnValue = someOtherValue; }

    return returnValue;
}

注意: - 您可以使用代码中的最后一种方式,因为您将return value存储在finalString中。所以,只需在方法的最后一行返回该字符串。

答案 1 :(得分:0)

private static String output(String input)//processes the word using basic rules including the q and u rule
{

    //the string that will hold the value of the word entered by the user
    char s;//the first character of the string
    char m;
    int l = input.length();//determines the length of the string
    String endString;
    String startString;
    String finalString;//the final output
    String mtr;
    String lowercase;//the entered string all converted to lowercase

    for(int k =0;k<l;k++)//checks all letters in order to see which is a vowel
    {

        s = input.charAt(k);

    if(s == 'q'|| s=='Q' && input.charAt(k+1)=='u')//if the first vowel is a "u" and the letter before it is a "q"
    {


            endString = input.substring(0,k+2);//makes the endString also include u
            endString = endString +"ay";
            startString = input.substring(k+2,l);
            finalString = startString + endString;
            System.out.println(finalString);
            break;


    }

    if(s=='a'||s=='e'||s=='i'||s=='o'||s=='u'||s=='A'||s=='E'||s=='I'||s=='O'||s=='U'||s=='y'||s=='Y')//if its a vowel or "y" than executes commands below
    {

        endString = input.substring(0, k);//gets the letters before the vowel
        endString = endString + "ay";
        startString = input.substring(k,l);//gets the letters after the vowel
        finalString = startString + endString;
        System.out.println(finalString);//prints the final result which is the combination of startString with endString
        break;//stops code after doing the above

    }


    else if(k==l-1)//if its the end of the word
    {
        System.out.println("ERROR");
        break;
    }
   }
   return finalString;
} 

下面。试试这个: - /

我不知道你要做什么。如果您突破循环,则会超出for()while()do..while()循环,这几乎就是您案例中方法的结束。我将返回的finalString放在那里,并将方法output的返回类型从void更改为String

答案 2 :(得分:0)

对不起,这不是一个真正的答案,Rohit Jain很好地解释了为什么你的代码不起作用。从那里你应该能够弄明白。

查看你的代码让我感到震惊的是,这段代码远比它需要的复杂得多。当我粘贴你的代码时,我的IDE(Eclipse)会警告我有关未使用的变量。正如你的情况所说,复杂的代码是导致问题的原因。

我认为在你的情况下,一点点重构可以提供帮助。而且你没有问题。为了帮助您入门,请尝试将查找切割位置的问题分为两部分和实际切割。这应该有所帮助。也许是这样的:

private static int firstVowel(String input) {
    for (int i = 0; i < input.length(); i++) {
        char aChar = input.charAt(i);
        if ("aeiouyAEIOUY".indexOf(aChar) >= 0) {
            if (aChar == 'u' && i > 0 && Character.toLowerCase(input.charAt(i-1)) == 'q') {
                return i-1;
            }
            // else
            return i;
        }
    }
    // if we get here no vowel was found
    return -1;
}

// /////////////////////////////////////////
private static String output(String input)
{
    int firstVowel = firstVowel(input);
    if (firstVowel < 0) {
        return "ERROR";
    }
    // else
    String start = input.substring(firstVowel);
    String end = input.substring(0, firstVowel) + "ay";
    return start + end;
}// /////////////////////////////////


public static void main(String[] args) {

    String str;// this will be the input string by the user
    Scanner scanner = new Scanner(System.in);// this scanner will register
                                                // the input value
    System.out.println("Enter a Word: ");
    str = scanner.next();// stores the input string

    System.out.println(output(str));// outputs it using basic gramatical rules

}