2
votes

I'd like to start out that I'm new and in need of assistance.

Prompt: Write a method, public static boolean Language(String word), to recognize words from the following language:

{ a^n | n is a prime number }

If the input "word" is from the language the method returns true and false.

Test Examples:

Input: aaa     true
Input: aaaaaaaa false
Input: aaaaaaa true
Input: a false
Input: aba false

I appreciate the help and time taken.

EDIT:

Okay so I was extremely confused on the isPrime and what to input, but at this point I'm at isPrime(String word) And compiling gives me an error at "boolean F = isPrime(word.length())" cannot be applied to (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)

{

}

}
3

3 Answers

4
votes

I'm not sure what your specific question is, but you might start by checking the length of the input string to see if it's prime. (see http://en.wikipedia.org/wiki/Primality_test) Then, check to see if every character in the string is an 'a'.

1
votes

It will be easier for you if you break down the problem into smaller ones. Given the input you need to perform the following tasks:

  • Get all words from the input
  • Check each word if it belongs to the language

More specifically:

  • Get the input (via a function argument)
  • Split the input using space as separator
  • for each word:
    • Check if it only contains the letter 'a'; if not, return false
    • Count the number of characters
    • Check if the number of characters is a prime number; if not, return false
  • If your function reached this point, return true
-2
votes

There you go...

public static boolean Language(String word)
{
    if(word == null)
    {
        return false;
    }

    for(char c : word.toCharArray())
    {
        if(c != 'a')
        {
            return false;
        }
    }

    int len = word.length();

    if(len == 0 || len == 1)
    {
        return false;
    }

    for(int i = 2; i <= len - 1; i++)
    {
        if(len % i == 0)
        {
            return false;
        }
    }

    return true;
}