【问题标题】:Not sure how to approach english into latin pig java code不知道如何将英语转换为拉丁猪 java 代码
【发布时间】:2014-03-07 23:41:54
【问题描述】:

这是我编写此代码的尝试,但我迷失了主要部分。我不确定循环如何知道新单词何时开始。现在我只知道循环和 if-else 语句。我如果您能将我推向正确的方向,我将不胜感激,因为这个问题对我来说太难了。

猪拉丁语规则: 1)如果单词以元音开头,则在末尾添加破折号和“方式”。 2)否则,添加破折号,将第一个字母移到末尾,并添加“ay”

/*Enter a line of text: This is a test.

  Input: this is a test.
  Output: his-tay is-way a-way est-tay.
*/



import java.util.Scanner;
public class PigLatin
{
    public static void main(String[]args)
    {
       int count;
       String input;
       char empty = ' ',first;

       Scanner keyboard = new Scanner(System.in);
       System.out.print("Enter a line of text: ");
       input = keyboard.nextLine();
       System.out.println(); 

       for(count = 0; count < input.length(); count++)
            if(input.charAt(0) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
                System.out.print(input.charAt(count + 1) + "-" + input.charAt(0) + "ay");
            else if(input.charAt(count) == empty) 
                    first = input.charAt(count + 1)
                    if(input.charAt(first) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
                    System.out.print(input.charAt(first + 1) + "-" + input.charAt(first) + "ay");
            else if()
                    System.out.print("-way"); //I'm lost here.
     }
 }

【问题讨论】:

  • 提示:您可能应该首先将行拆分为一组单词,然后单独处理每个单词。尝试使用String[] parts = input.split(" ");
  • 我还不知道如何使用数组。据我所知,这个问题可以用 for 和 if-else 语句解决,但我遇到了麻烦。
  • 如果有空格,你可以检测到一个新单词的开始。

标签: java string if-statement for-loop


【解决方案1】:

尝试以下方法:

import java.util.Scanner;
public class PigLatin {

    static final char vowelRegex = "^[aeiouy]"; //Is y a vowel?

    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter a line of text: ");
        String input = keyboard.nextLine();
        String[] words = input.split(' ');

        for(int i=0; i<words.length; i++) {
            if(words[i].matches(vowelRegex)) {
                System.out.print(words[i] + "-way ");
            } else {
                System.out.println(words[i].substring(1) + words[i].charAt(0) + "-ay ";
            }
        }
    }
}

【讨论】:

  • 感谢 PlasmaPower,但我还没有接触到阵列。
  • @user3003920 正则表达式可以吗?
  • 考虑一个字符类而不是 or:[aeouy]
  • @aliteralmind 谢谢,我的忍者正则表达式技能让我失望了:/.
  • 没问题。你永远是我心中的忍者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2018-10-21
  • 2015-11-28
  • 1970-01-01
相关资源
最近更新 更多