首先我想知道我是新人并且需要帮助。
提示: 编写一个方法,public static boolean Language(String word),来识别以下语言的单词:
{ a^n | n is a prime number }
如果输入“单词”来自该语言,则该方法返回 true 和 false。
测试示例:
Input: aaa true
Input: aaaaaaaa false
Input: aaaaaaa true
Input: a false
Input: aba false
感谢您的帮助和所花费的时间。
编辑:
好吧,我对 isPrime 和要输入的内容感到非常困惑,但此时我在 isPrime(String word) 并且编译在“boolean F = isPrime(word.length())”处给了我一个错误不能应用于 (int)。
import java.io.*;
import java.util.*;
public class Homework_2F_2
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word from language \"A\" ");
String word = keyboard.nextLine();
boolean D = isTrue(word);
if(D == false)
System.out.println("This word is not part of the language");
boolean F = isPrime(word.length());
if(F == true && D == true)
System.out.println("This word is part of the language");
}
//Check for language Method
public static boolean isTrue(String word)
{
if(word.length() == 1)
return false;
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) != 'a')
return false;
}
return true;
}
//Method to find if word is prime
public static boolean isPrime(String n)
{
}
}
最佳答案
我不确定您的具体问题是什么,但您可以首先检查输入字符串的长度,看看它是否是素数。 (参见 http://en.wikipedia.org/wiki/Primality_test )然后,检查字符串中的每个字符是否都是“a”。
关于java - 如何编写一种方法来识别以下语言中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5387728/