Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 返回由整数指定的字_Java_String_Methods_Indexof - Fatal编程技术网

Java 返回由整数指定的字

Java 返回由整数指定的字,java,string,methods,indexof,Java,String,Methods,Indexof,我知道我错过了一些东西,这就是我真正需要帮助的地方。代码并非在所有情况下都有效,我正在寻求帮助来改进/修复它 任务: 到目前为止,我掌握的代码是: public String word(int num, String words) { int l = words.indexOf(" "); int r = words.indexOf(" ", l+1); for(int i = 3; i <= num; i++){ l = r; r =

我知道我错过了一些东西,这就是我真正需要帮助的地方。代码并非在所有情况下都有效,我正在寻求帮助来改进/修复它

任务:

到目前为止,我掌握的代码是:

public String word(int num, String words)
{
    int l = words.indexOf(" ");
    int r = words.indexOf(" ", l+1);

    for(int i = 3; i <= num; i++){


     l = r;
     r = words.indexOf(" ", l+1);

    //if(i != num)
//  l = r;

    }       
String theword = words.substring(l,r);
    return theword;


}
}
公共字符串字(int num,字符串字)
{
int l=单词。indexOf(“”);
int r=words.indexOf(“,l+1);

对于(inti=3;i,因为这显然是家庭作业,所以我只给你文本

您的方法最终可能会起作用,但它既费力又过于复杂,因此很难调试,也很难正确使用

  • 通过使用
    split()
    方法使用字符串的API
  • 将句子拆分为字符串数组后,返回
    num
    less one处的元素(数组从零开始索引)
  • 首先检查数组的长度,以防单词少于
    num
    ,并在这种情况下采取您认为合适的任何操作
对于第2部分,简单形式的解决方案可以是:

  • 为结果创建一个新的空白字符串
  • 迭代给定字符串的字符,将字符添加到结果字符串的前面
  • 使用字符串的
    toUpperCase()
    方法

因为这是家庭作业,你已经付出了一些努力。这就是你如何完成问题的第一部分。这段代码非常明显

1) 如果数字大于字符串中的字数,我将返回null,因为当字符串中只有2个字时,我们不希望用户输入5
2) 按空格分割字符串,基本上返回用户提到的数字数组

您必须了解更多的条件,例如告诉用户输入字符串长度的数字,因为它不会给用户任何结果,并从
扫描仪
获取输入,而不是直接在方法中添加输入

public static String word(int num, String words)
{
  String wordsArr[] = words.split(" ");

  if(num <= 0 || num > wordsArr.length) return null;

  return (wordsArr[num-1]);

}
公共静态字符串字(int num,字符串字)
{
字符串字R[]=words.split(“”);
if(num wordsArr.length)返回null;
返回(wordsArr[num-1]);
}

问题的第二部分必须由你来尝试。

嗯……你不经常看到有人带着家庭作业来这里,同时表现出努力(太棒了:)

这是如何拆分字符串并从该字符串返回[x]元素的示例

public class SO {

    public static void main(String[] args) throws Exception {
        int number = 3;
        String word = "Hello this is sample code"; 

        SO words = new SO();
        words.returnWord(number, word);
    }
    private void returnWord(int number, String word) throws Exception {
        String[] words = word.split("\\s+");
        int numberOfWords = words.length;

        if(numberOfWords >= number) {
            System.out.println(words[number-1]);
        } else {
            throw new Exception("Not enought words!!!");
        }
    }
}

是的,这是一个有效的例子,但不要只是把它复制粘贴到你的家庭作业中——作为老师的简单问题——这是在做什么,或者这是如何工作的,以及你的答案:)!所以要理解代码,试着用你熟悉的方式修改它。同样值得买一些Java书籍——我建议O'真的对于第一个问题,我将给你两种方法(推荐1

  • 使用该方法将单词拆分为一个单词数组,其中每个元素都是一个单词。它将创建一个单词数组,而不是一个包含所有单词的字符串,例如
    “hello my name is Michael”
    ,例如
    [hello,my,name,is,Michael]
    这样,您就可以使用数组访问单词。非常简单:

    public static String word(int num, String words)
    {
        // split words string into array by the spaces
        String[] wordArray = words.split(" "); // or = words.split("\\s+");
    
        // if the number is within the range
        if (num > 0 && num <= wordArray.length) {
            return wordArray[num - 1]; // return the word from the word array
        } else { // the number is not within the range of words
            return null;
        }
    }
    

    你应该在这里发布代码,而不是在图像中。我刚刚编辑了它,谢谢。你应该研究split()方法。它在什么情况下不起作用?首先拆分单词,它会给你一个数组,然后只返回给定位置-1的元素('因为数组是0-索引)首先,您必须检查给定的数字是否>=array.length,并在这种情况下返回null。在这里犯错误需要人才。在您的解决方案中,如果整数大于字母数而不是单词数,则返回null。仍然错误,您得到了一个off-by-one错误,请检查括号中的条件。仍然错误!您的检查是正确的,但return不是。这个问题指定单词从1开始计数,而java数组从0开始。这个问题允许取任何整数,而不仅仅是正数。要获得完整的学术答案,你还需要检查int的下限。我没有像你提到的那样为这些条件编写所有代码,因为这是一个家庭作业,我将做I但是你的观点必须得到考虑,我将用你的建议编辑我的答案。你能为第2部分添加一个类似的提示以获得完整的答案吗?比如说,一个好的类,它的API可以使问题变得简单?我想更多的是按照StringBuilder.reverse()的思路为了避免代码点问题,但我想可以。我给了你一个算法。至于类设计,考虑你的类是什么,并为这些动作提供方法。因为方法不需要状态(在调用它时对类没有影响)。,方法可以而且应该是静态的。
    static
    @Ordous是的,StringBuilder会更好,但是我给了你一个我能想到的最简单的东西作为起点。
    public static String word(int num, String words)
    {
        for (int i = 0; i < words.length(); i++) { // every character in words
            if (words.substring(i, i+1).equals(" ")) { // if word is a space
                num = num - 1; // you've found the next word, so subtract 1 (number of words left is remaining)
            }
            if (num == 1) { // found all words
                // return this word
                int lastIndex = i+1;
                while (lastIndex < words.length()) { // until end of words string
                    if (words.substring(lastIndex, lastIndex+1).equals(" ")) {
                        break;
                    }
                    lastIndex = lastIndex + 1; // not a space so keep moving along the word
                }
                /*
                // or you could use this to find the last index:
                int lastIndex = words.indexOf(" ", i + 1); // next space after i+1
                if (lastIndex == -1) { // couldn't find another space
                    lastIndex = words.length(); // so just make it the last letter in words
                }*/
                if (words.substring(i, i+1).equals(" ")) { // not the first word
                    return words.substring(i+1, lastIndex);
                } else {
                    return words.substring(i, lastIndex);
                }
            }
        }
        return null; // didn't find word
    }
    
    public static String reverse(String str) {
        String reversedString = ""; // this will be the reversed string
    
        // for every character started at the END of the string
        for (int i = str.length() - 1; i > -1; i--) {
            // add it to the reverse string
            reversedString += str.substring(i, i+1);
        }
        return reversedString.toUpperCase(); // return it in upper case
    }