简体   繁体   English

缺少 While 循环逻辑

[英]Missing While loop logic

found this code on the internet, it's missing the while loop logic "while(i....)" for some reason and though I found other working solutions for the PigLatin* problem, I really want to understand how this one is working.在互联网上找到了这段代码,由于某种原因,它缺少 while 循环逻辑“while(i....)”,虽然我找到了 PigLatin* 问题的其他工作解决方案,但我真的很想了解这个是如何工作的。

*PigLatin problem: take a sentence, take the first letter from each word and place it at the end of the same word, then suffix "ay". *PigLatin 问题:取一个句子,取每个单词的第一个字母放在同一个单词的末尾,然后加上后缀“ay”。 So "I am confused" becomes "Iay maay onfusedcay".所以“我很困惑”变成了“Iay maay onfusedcay”。

Here is the code:这是代码:

        import java.util.*;
        public class PigLatin {
            
            public static void main(String[] args) {
                        
                Scanner input = new Scanner(System.in);
                    
                System.out.println("Please enter an English sentence: ");
                String sentence = input.nextLine();
                
                System.out.println("Original sentence: "+sentence);
                System.out.println("PigLatin conversion: "+convert(sentence));
            }
            
        private static String convert (String sentence) {
                
                String []words = sentence.split(" ");
                int i = 0;
                String pigLatin = "";
                while(i ){ //MISSING CODE
                    pigLatin+=words[i].substring(1,words[i].length())+words[i].charAt(0)+"ay"+" ";
                    i++;
                }
                return pigLatin;
            }
        }

Thank you.谢谢你。

PS: I basically found the "convert" method on the internet and wrote the rest of the code, tried a few things but could not get the while loop to work. PS:我基本上在互联网上找到了“转换”方法并编写了其余的代码,尝试了一些东西但无法使while循环起作用。

The loop appears to be iterating the words array.循环似乎在迭代words数组。 So it should just be something like所以它应该是这样的

while(i < words.length) {
    pigLatin += words[i].substring(1, words[i].length())
            + words[i].charAt(0) + "ay ";
    i++;
}
import java.util.Scanner;

public class PigLatin {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter an English sentence: ");
        String sentence = input.nextLine();

        System.out.println("Original sentence: "+sentence);
        System.out.println("PigLatin conversion: "+convert(sentence));
    }

    private static String convert (String sentence) {

        String []words = sentence.split(" ");
        int i = 0;
        String pigLatin = "";
        while(i<words.length){ //CORRECTION CODE
            pigLatin+=words[i].substring(1,words[i].length())+words[i].charAt(0)+"ay"+" ";
            i++;
        }
        return pigLatin;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM