printing a toString() method output in a test class - java

Hi guys I have been making a test class for my word puzzle game and the out put is printing the objects reference number to the object. Anyone got the solution to print the return statement of the object.
Output:
Generator stats: word-puzzles generated from words of length 3
Puzzle.WordPuzzleGenerator#c68c3Puzzle.WordPuzzleGenerator#b2002fPuzzle.WordPuzzleGenerator#2a4983Puzzle.WordPuzzleGenerator#406199Puzzle.WordPuzzleGenerator#c7b00cPuzzle.WordPuzzleGenerator#1f6f296Puzzle.WordPuzzleGenerator#1df5a8fPuzzle.WordPuzzleGenerator#b2a2d8Puzzle.WordPuzzleGenerator#1e13d52Puzzle.WordPuzzleGenerator#80fa6f
Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
int sizeTest1 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest1);
for (int i = 0; i < 10; i++) {
WordPuzzleGenerator puzzle = new WordPuzzleGenerator(sizeTest1);
System.out.print(puzzle);
}
int sizeTest2 = 3;
System.out
.println("Generator stats: word-puzzles generated from words of length "
+ sizeTest2);
for (int i = 0; i < 10; i++) {
new WordPuzzleGenerator(sizeTest2);
}
}
}
Main program:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public WordPuzzleGenerator(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord) && !puzzleListY.contains(randomXWord)) {
finished = false;
break;
}
puzzleListX.add(randomXWord);
}
}
toString(puzzleListX, puzzleListY);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
public static String toString(ArrayList<String> ArrayList1, ArrayList<String> ArrayList2){
StringBuilder group1 = new StringBuilder();
for (int i = 0; i < ArrayList1.size(); i++) {
group1.append(ArrayList1.get(i) + " ");
}
String wordsInString1 = group1.toString();
StringBuilder group2 = new StringBuilder();
for (int i = 0; i < ArrayList2.size(); i++) {
group2.append(ArrayList2.get(i) + " ");
}
String wordsInString2 = group2.toString();
return String.format("\t( %s) ( %s)", wordsInString1, wordsInString2);
}
}

Your WordPuzzleGenerator class does not override Object's toString. Instead it contains a static toString method with a different signature.
You need a method of this signature in your WordPuzzleGenerator class :
#Override
public String toString()
{
...
}
After taking another look, it appers your WordPuzzleGenerator has only static methods and no instance members, so it's unclear what you expect toString to return, or in other words - it's not clear what System.out.print(puzzle); is expected to print.
EDIT:
If you want toString() to print the Lists created in your constructor, you should make them instance members :
ArrayList<String> puzzleListY;
ArrayList<String> puzzleListX;
public WordPuzzleGenerator(int size) throws FileNotFoundException {
puzzleListY = new ArrayList<String>();
puzzleListX = new ArrayList<String>();
...
}
Then you can override toString like this :
#Override
public String toString()
{
return WordPuzzleGenerator.toString (puzzleListX,puzzleListY);
}

you'll have to override the toString method of your objects, since your object inheris from java object
#Override
public String toString(){
\\mystring build up...
return mystring;
notice the override annotation, thats what does the trick ;)
happy coding!

try to override 'toString' method in your class as follows:
#Override
public String toString()
{
//your code
}

Related

why my program don't recognize the .txt file

I try to made a program which print the top 20 frequently words in a text file in java, and i have 3 classes but i don't know why can not compile it help me please. I show you the tree classes just to have an idea:
1)
public class Client {
public static void main(String[] args) {
Map<String, Integer> frequencies = new TreeMap<String, Integer>();
while(file.hasNext()){//Este lazo lee las palabras y crea el TreeMap
String word= clean(doc.next());
Integer count = frequencies.get(word);
if(count==null){
count = 1;}
else {
count = count + 1;
}
}
Object[] Claves = frequencies.keySet().toArray();
Object[] Valores = frequencies.values().toArray();
Par[] par = new Par[frequencies.size()];
for (int i=0;i<frequencies.size();i++){
Par p = new Par(Claves[i].toString(),(int) Valores[i]);
par[i]=p;
}
Arrays.sort(par);
showResult(par);
}
public static void showResult(Par[] arreglo){
System.out.println("The 20 most frequently words are ");
for(int i= 0; i<=19; i++){
System.out.print("Word "+ arreglo[i].Clave + " in " + arreglo[i].Valor + " times.");
}
}
}
2)
public class Par implements Comparable {
String Clave;
int Valor;
public int length;
public Par(String clave, int valor){
this.Clave = clave;
this.Valor = valor;
}
public int compareTo(Par p) {
if(this.Valor<p.Valor){
return 1;
}
else if(this.Valor==p.Valor){
return 0;
}
else{
return -1;
}
}
}
3)
public class ProcessText {
public void reader(Path r){
String name = clean(file.getName());
if(file.getName().equals(name + ".txt" || file.getName().equals(name + ".doc" ))){
try (Scanner sc = new Scanner(r)){
String doc = "";
while(sc.hasNextLine()){
String linea = (sc.nextLine());
doc = doc.concat(linea + "\n");
}
sc.close();
}
}
}
public static String clean(String s){
String r = "";
for (int i=0;i<s.length();i++){
char c = s.charAt(i);
if (Character.isLetter(c)){
r = r + c;
}
}
return r.toLowerCase();
}
}
If this is all the code you have, your problem might be that your main method never creates a variable called "doc" or "file", but you use them both at the beginning of Client's main method.
It would be more helpful if you could share the compile time error, though, so I can't be sure that this is your problem.

Word-Puzzle (ArrayList problems)

So I have been creating a Word-Puzzle which I recently got stuck on a index out of bounds problem. This has been resolved however the program is not doing what I would like it to do. The Idea i that the test class will print 3 words in an array e.g. [FEN, GNU, NOB] (and yes they are apparently real english words). Then check to see if the first letter of each word combined is a word and so forth e.g. FGN if so add it to the next ArrayList else start again. Ideal output would be [FEN, GNU, NOB] [FGN, ENO, NUB] for example. However the current output is [FEN, GNU, NOB] [SOY, SOY, SOY] or [FEN, GNU, NOB] [].
The Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Test 1: size 3");
int size = 3;
Puzzle.WordPuzzleGenerator.generatePuzzle(size);
}
}
WordGenerator:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
break;
}
puzzleListX.add(randomXWord);
if (puzzleListX.size() == size){
finished = false;
}
}
}
System.out.print(puzzleListY);
System.out.print(puzzleListX);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
}
I think you are confusing yourself with that finished variable. Replace the while condition with puzzleListX.size() != size and your code should work.

Main method not found in class ActivityTime, please define the main method as: public static void main(String[] args)

I tested my program on http://www.hackerearth.com/problem/algorithm/roys-life-cycle/ . However, I always got Error: Main method not found in class ActivityTime, please define the main method as:public static void main(String[] args)
This is my program
import java.util.Scanner;
/**
* Created by DUY on 10/12/2014.
*/
class EatSleepCode {
public static void main(String[] args){
int numberDay = 0;
int numberMinuteOfDay = 18;
Scanner input = new Scanner(System.in);
numberDay = input.nextInt();
input.nextLine();
String[] str = new String[numberMinuteOfDay];
for(int i = 0; i < numberDay; i++){
str[i] = input.nextLine();
}
ActivityTime code = new ActivityTime(numberDay,str,'C');
code.findLongestTime();
}
}
class ActivityTime{
public int longestTimeOfDay;
public int longestTimeOfTotal;
public int numberDay;
public String[] str;
public char act;
public ActivityTime(int numberDay, String[] str, char act){
this.numberDay = numberDay;
this.str = str;
this.act = act;
}
public void findLongestTime(){
int tmp1 = 0, tmp2 = 0;
for(int i = 0; i < numberDay; i++){
tmp1 = 0;
for(int j = 0; j < str.length; j++){
if(str[i].charAt(j) != act){
tmp1 = 0;
tmp2 = 0;
}
else {
tmp1 ++;
tmp2 ++;
}
if(tmp1 > longestTimeOfDay){
longestTimeOfDay = tmp1;
}
if(tmp2 > longestTimeOfTotal){
longestTimeOfTotal = tmp2;
}
}
}
System.out.println(longestTimeOfDay + " " + longestTimeOfTotal );
}
}
Can you help me solve this error? Thank you very much
You ought to separate these classes into two files, one called EatSleepCode.java and one called ActivityTime.java.
Once you've done that, you'll be clearer on which one you're running as your main class. It's EatSleepCode that has the public static void main in it, so presumably that is what you intend as your main class; ActivityTime doesn't have such a method, which is why you can't run that as your main class. That's what the error means that you're getting.

How to combine if statements in a loop

I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.

implementing a method from one class to another?

I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:
str= str + seats[i][j].toString();
I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?
Airplane class:
public class Airplane
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;
public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}
}
Seat Class:
public class Seat
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;
public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}
public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}
In Seat.toString you should print a " " not "".
You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.
seats seems to does not have Seat's instance.
Add this code :
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
seats[i][j] = new Seat();
}
}
below this :
seats = new Seat[FC_ROWS][ECONOMY_COLS];
I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.

Categories