I am trying to create a program that generates random sentences in English (according to general English syntax rules).
I keep getting a bug with my subroutine randomSentence(). What have I missed? Also any suggestions on how I can simplify everything?
The error I am receiving is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(boolean) in the type PrintStream is not applicable for the arguments (void)
at SentenceGenerator.randomSentence(SentenceGenerator.java:80)
at SentenceGenerator.main(SentenceGenerator.java:86)
Code:
import java.util.ArrayList;
import java.util.Random;
public class SentenceGenerator {
private StringData[] stringData;
// An array containing all of the possible words. This is a nested class.
/**
* An object of this type holds the word that will be randomly chosen and printed
*/
public class StringData {
String[] conjunction = {"and", "or", "but", "because"};
String[] proper_noun = {"red", "Jane", "Richard Nixon", "Miss America"};
String[] common_noun = {"man", "woman", "fish", "elephant", "unicorn"};
String[] determiner = {"a", "the", "every", "some"};
String[] adjective = {"big", "tiny", "pretty", "bald"};
String[] intransitive_verb = {"runs", "jumps", "talks", "sleeps"};
String[] transitive_verb = {"loves", "hates", "sees", "knows", "looks for", "finds"};
//find out how many words there are in each list
int conjunctionLength = conjunction.length;
int proper_nounLength = proper_noun.length;
int common_nounLength = common_noun.length;
int determinerLength = determiner.length;
int adjectiveLength = adjective.length;
int intransitive_verbLength = intransitive_verb.length;
int transitive_verbLength = transitive_verb.length;
//Generate random numbers
int rand1 = (int) (Math.random()*conjunctionLength);
int rand2 = (int) (Math.random()*proper_nounLength);
int rand3 = (int) (Math.random()*common_nounLength);
int rand4 = (int) (Math.random()*determinerLength);
int rand5 = (int) (Math.random()*adjectiveLength);
int rand6 = (int) (Math.random()*intransitive_verbLength);
int rand7 = (int) (Math.random()*transitive_verbLength);
String word1 = conjunction[rand1];
String word2 = proper_noun[rand2];
String word3 = common_noun[rand3];
String word4 = determiner[rand4];
String word5 = adjective[rand5];
String word6 = intransitive_verb[rand6];
String word7 = transitive_verb[rand7];
}
static void Sentence() {
String sentence() = SimpleSentence();
}
/**
* subroutine that defines how SimpleSentence is put together, nesting NounPhrase and VerbPhrase subroutines
*/
public static String SimpleSentence() {
String simple_sentence = NounPhrase() + VerbPhrase();
return "";
}
/**
* subroutine that defines the nested variable NounPhrase
*/
public static String NounPhrase() {
String noun_phrase = proper_noun[word2], determiner[word4], common_noun[word3];
return "";
}
/**
* subroutine that defines the nested variable VerbPhrase
*/
static void VerbPhrase() {
String verb_phrase = intransitive_verb[word6], transitive_verb[word7], NounPhrase();
}
/**
* Final subroutine that prints out the random sentence
*/
public static void randomSentence() {
System.out.print(randomSentence());
}
public static void main(String[] args) {
while (true) {
randomSentence();
System.out.println(".\n\n");
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {}
}
}
}
This is the most evident error:
public static void randomSentence() {
System.out.print(randomSentence());
}
You call the method recursively.
Furthermore, the program is full of conceptual errors, you need to study the OO programming paradigm better.
Ok. The first issue :
System.out.print(randomSentence());
randomSentence() returns void, So basically there is nothing for print() to print.
Next --> even if you happen to fix this issue. You are calling randomSentence() recursively and you will get a StackOverflowError. Kindly check your design / code.
Related
Hi I am unable to know what I am doing wrong.
I have a string which is pass as an argument to a my class.
I have to split that string and assign the respective values to the member variable but it is not working properly.
Here is my class.
package virtusa;
public class pratice {
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public pratice()
{
}
public pratice(String rawInput)
{
temp = rawInput.split("$$##",2);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity =Integer.parseInt( temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
}
here is my main class
package virtusa;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String stub = in.nextLine();
pratice temp = new pratice(stub);
System.out.println(temp.getName);
System.out.println(temp.getQuantity);
System.out.println(temp.getPrice);
}
}
My Input = apple$$##12.5$$##9
error i am having -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at virtusa.pratice.<init>(pratice.java:17)
at virtusa.demo.main(demo.java:12)
String::split take regex as a parameter, so the $ has special meaning. You will need to escape it with a \
One of problems in your code in not escaping special characters as some comments are mentioning. In my opinion clearest solution is to use Patter quote
rawInput.split(Pattern.quote("$$##"), 3);
Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]
So the final code should look something like this
String getName;
Double getPrice;
int getQuantity;
String temp[] = null;
public Practice() {
}
public Practice(final String rawInput) {
temp = rawInput.split(Pattern.quote("$$##"), 3);
getName = temp[0];
getPrice = Double.parseDouble(temp[1]);
getQuantity = Integer.parseInt(temp[2]);
}
public String getGetName() {
return getName;
}
public Double getGetPrice() {
return getPrice;
}
public int getGetQuantity() {
return getQuantity;
}
I'm trying to fill a 2D array with the reference variable called letters with randomly generated upper case letters using the Random object. I've tried doing it in both classes now but I still get a few errors that I've never encountered before. Any help on this is greatly appreciated.
Below are the errors I'm getting in the WordSearch class and where they are located:
I get an error that says, "char someChar = (char)(rand.nextInt(26) + 65);"
The error reads, "Syntax error on token ";", { expected after this token."
I'm also getting an error at the end of my for loop where the } is.
The error reads, "Syntax error, insert "}" to complete Block."
Lastly, I'm getting an error on the line that says, "public search(){"
The error reads, "Return type for the method is missing."
import java.util.Random;
import java.util.Scanner;
public class WordSearchTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int seed;
String word = " ";
String again = "y";
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number from 1 - 9999:\n");
seed = keyboard.nextInt();
keyboard.nextLine(); //Consume the remaining new line
while(seed < 1 || seed > 9999) {
System.out.print("You must choose a number between 1 and 9999:\n");
seed = keyboard.nextInt();
keyboard.nextLine(); //Consume the remaining new line
}
while(again.equalsIgnoreCase("y")) {
System.out.print("Choose a word to search for:\n");
word = keyboard.nextLine();
System.out.print("Would you like to search for another word? (Y = Yes and N = No)\n");
again = keyboard.nextLine();
System.out.print(again);
while(!again.equals("Y") && !again.equals("y") && !again.equals("N") && !again.equals("n")) {
System.out.print("Invalid response. Y or N?\n");
again = keyboard.nextLine();
}
}
//Random rand = new Random(seed);
//char someChar = (char)(rand.nextInt(26) + 65);
//Instantiates a WordSearch object with reference variable puzzles and passes the arguments to the WordSearch constructor
WordSearch puzzles = new WordSearch(seed, word);
puzzles.search();
System.out.print("Terminating...");
System.exit(0);
}
}
import java.util.Random;
public class WordSearch {
private int seedNum;
private String wordGiven;
private int index = 0;
private char someCharz;
char[][] letters;
private char[][] lettersFound;
public WordSearch(int seeded, String wordUser) {
seedNum = seeded;
wordGiven = wordUser;
//someCharz = charz;
}
Random rand = new Random(seedNum);
char someChar = (char)(rand.nextInt(26) + 65);
letters = new char[4][4];
lettersFound = new char[4][4];
for(int col = 0; col < letters[0].length; col++)
{
for(int rowz = 0; rowz < letters.length; rowz++)
{
System.out.print(someCharz);
}
index++;
}
public search() {
System.out.print(letters);
}
/**
* #return the seedNum
*/
public int getSeedNum() {
return seedNum;
}
/**
* #param seedNum the seedNum to set
*/
public void setSeedNum(int seedNum) {
this.seedNum = seedNum;
}
/**
* #return the wordGiven
*/
public String getWordGiven() {
return wordGiven;
}
/**
* #param wordGiven the wordGiven to set
*/
public void setWordGiven(String wordGiven) {
this.wordGiven = wordGiven;
}
}
I am looking to see if I can find the cause of your first errors, but initially, the error about return type is easy; every method in Java must specify a return type. If the method returns nothing, and say--in this case--simply prints something to the console, the return type would be void.
Change the method declaration to public void search() {} and it will eliminate that error.
I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";
I need help with this code
Problem
Write a Java class having a String array, with global visibility.
Add a method that adds a given sting to the string array.
Add a method that searches for a given string in the string array.
Add a method that searches for a given character in the string array. The method should count and returns the occurrence of the given character.
Write an appropriate main method to test these class methods.
and this is the code. First, I created a class for method I create scound class for TestString array
my question is i have error in scound class ,and i try to fix it but it dose not work
this the first class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ooplab3;
public class StringArray {
String[] sTA = null;
int index = 0; //last added sring position in the string array
public StringArray() {
}
public String[] getsTA() {
return sTA;
}
public String getsTAindex(int i) {
return sTA[i];
}
public int getcounter() {
return index;
}
public void setCounter(int counter) {
this.index = counter;
}
public void addStrinToArray(String st) {
if (this.index < sTA.length) {
sTA[this.index] = st;
this.index++;
}
}
public int searchStringInArray(String sT) {
int n = 0;
for (int i = 0; i < this.index; i++) {
for (int j = 0; j < 10; j++) {
int indexOf = sTA[i].indexOf(sT);
n += searchStringInArray(sTA[i]);
return n;
}
}
return n;
}
public int searchcharInArray(String sT) {
int n = 0;
int Startindex = 0;
do {
n += sT.indexOf(Startindex);
} while (n > Startindex);
return n;
}
public boolean containsChar(String s, char search) {
if (s.length() == 0) {
return false;
} else {
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
}
public void containsChar(Object object, String search) {
}
}
Sound class :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ooplab3;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class testStringarray {
public static void main(String[] args) throws FileNotFoundException {
String[] testArray = new String[30];
Scanner infile = new Scanner(new FileReader("input_txt"));
// System.out.println("contents of testArray");
int i = 0;
while (infile.hasNext()) {
String j = infile.next();
addString(j, i);
System.out.println(testArray[i] + "\n");
i++;
}
}
}
the input file contain: hello this is my java program
As near as I can tell, you have a class named StringArray, and a second class which is intended to test the capabilities of StringArray. But that second class doesn't actually use StringArray at all; instead, it creates its own array, and calls a method addString() which has a similar, but not identical, name as a method in StringArray.
One significant problem with StringArray is that it never creates an actual array -- its array member variable remains null. You need a "new" expression to create the actual array. Then your test class should be doing something like
StringArray sa = new StringArray();
sa.addStringToArray("Hello, world");
String[] array = sa.getsTA();
for (String s: array)
System.out.println(s);
A number of problems exist.
Here's one of them:
In your StringArray.addStrinToArray() method, you attempt to assign a string to an element of a null array:
String[] sTA = null;
sTA[index] = st; //this will throw NullPointerException
You need to initialise the array:
String[] sTA = new String[initialSize];
Where initialSize is an integer containing the initial size of the array.
public static String s1 = "team A won the match historically to clinch series which made surprise around the world ";
public static String s2 = "He did his part";
t1=s1.length();
t2=s2.length();
t3=Math.abs(t1-t2);
for(i=0;i<t3;i++)
{
Sub_string.add(s1.substring(i,t2++));
}
How can I solve this?
tried it. doesn't seem to throw an exception
I guess you defined your list to have max size? if you define it like this it will work.
public class TestCode {
public static String s1 = "team A won the match historically to clinch series which made surprise around the world ";
public static String s2 = "He did his part";
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> Sub_string = new ArrayList<String>();
int t1=s1.length();
int t2=s2.length();
int t3=Math.abs(t1-t2);
try {
for(int i=0;i<t3;i++)
{
Sub_string.add(s1.substring(i,t2++));
}
} catch (Exception e) {
System.err.println();
}
}
}
Code derived from your pseudocode, with the input strings you provided, will not throw any exception.
The exception you posted (StringIndexOutOfBoundsException: String index out of range: -1) is thrown when substring is called with beginIndex (in your case i) larger then endIndex (in your case t2).
You will also get a StringIndexOutOfBoundsException when you call your code with a s1 that is shorter then s2.
The following code would serve your purpose...
gives no problem. Prints sum as 73 and a designer output..;)
Hope its helpful!!!!
import java.util.ArrayList;
public class Trial {
public static String s1 = "team A won the match historically to clinch series which made surprise around the world ";
public static String s2 = "He did his part";
public static void main(String[] args) {
ArrayList<String> Sub_string = new ArrayList<String>();
int t1=s1.length();
int t2=s2.length();
int t3=Math.abs(t1-t2);
try {
for(int i=0;i<t3;i++)
Sub_string.add(s1.substring(i,t2++));
Object ia[] = Sub_string.toArray();
for(int i=0; i<ia.length; i++)
System.out.println(ia[i]);
} catch (Exception e) {
System.err.println();
}
}
}