Im having difficulty changing my boolean to true, if the word is found.
import java.util.Scanner;
public class WordSearch
{
private char[][] array;
private boolean found;
public WordSearch(char[][] inArray)
{
array = inArray;
}
public void play()
{
Scanner in = new Scanner(System.in);
String choice = "";
while(!choice.equals("end"))
{
print();
System.out.println("What word do you want to search for? (Type end to quit)");
choice = in.nextLine();
System.out.println();
switch (choice)
{
case "end":
break;
default:
search(choice);
break;
}
}
}
public void print()
{
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[0].length; j++)
{
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
}
public void search(String inWord)
{
// Puts inWord into an array
char[] word = new char[inWord.length()];
for(int i = 0; i < inWord.length(); i++)
{
word[i] = inWord.charAt(i);
}
for(int i = 0; i < array.length; i++)// goes to each row
{
for(int j = 0; j < array[0].length; j++)// goes through every letter
{
if(array[i][j] == word[0])// asks if it matches
{
lookHorizantal(word, array, i, j, found);
lookVertical(word, array, i, j, found);
lookDiagnal(word, array, i, j, found);
}
}
}
if(!found)
{
System.out.println(inWord + "was not found!");
}
System.out.println();
}
public void lookHorizantal(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
column += 1;
for(int i = 0; i < inWord.length; i++)
{
if(column < 15 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
column += 1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found horizontally at row " + row + " and column " + (column - counter) + "!");
}
}
public void lookVertical(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
row += 1;
for(int i = 0; i < inWord.length; i++)
{
if(row < 10 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
row += 1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found vertically at row " + (row - counter) + " and column " + column + "!");
}
}
public void lookDiagnal(char[] inWord, char[][] inArray, int row, int column, boolean ifFound)
{
int counter = 1; //set this to one because we already found the first letter
row += 1;
column += 1;
for(int i = 0; i < inWord.length; i++)
{
if(row < 10 && column < 15 && counter < inWord.length)
{
if(inArray[row][column] == inWord[counter])
{
//System.out.println("WE FOUND A LETTER AT COLUMN: " + row + " Row: " + column);
counter += 1;
row += 1;
column +=1;
}
}
}
if(counter == inWord.length)
{
ifFound = true;
System.out.println(printChar(inWord) + " found diagnolly at row " + (row - counter) + " and column " + (column - counter) + "!");
}
}
public String printChar(char[] inChar)
{
String complete = "";
for(int i = 0; i < inChar.length; i++)
{
complete += inChar[i];
}
return complete;
}
}
Every time I find a word it returns false and runs the not found. Am I not declaring the boolean right? or is it resetting when it gets out of a method?
Heres the driver if you want to test it out:
import java.util.*;
import java.io.*;
public class Driver
{
public static void main (String[] args)
{
// try block needed to read in file
try
{
//open the file "sampleSearch.txt"
FileReader fileName = new FileReader("sampleSearch.txt");
Scanner fileRead = new Scanner(fileName);
//read in the number of rows
int numRow = fileRead.nextInt();
fileRead.nextLine();
//read in the number of columns
int numCol = fileRead.nextInt();
fileRead.nextLine();
//create a 2d array to hold the characters in the file
char[][] array = new char[numRow][numCol];
//for each row in the file
for (int r = 0; r < numRow; r++)
{
//read in the row as a string
String row = fileRead.nextLine();
//parse the string into a sequence of characters
for (int c = 0; c < numCol; c++)
{
//store each character in the 2d array
array[r][c] = row.charAt(c);
}
}
//create a new instance of the WordSearch class
WordSearch ws = new WordSearch(array);
//play the game
ws.play();
}
catch (FileNotFoundException exception)
{
//error is thrown if file cannot be found. See directions or email me...
System.out.println("File Not Found");
}
}
}
and heres sampleSearch.txt:
10
15
fqexfecmxdvjlgu
cxomfslieyitqtz
nucatfakuxofegk
hfytpnsdlhcorey
pgrhdqsypyscped
ckadhyudtioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
hdskymmpkzokaao
amuewqvtmrlglad
You cannot modify your immutable primitive boolean (or even a Boolean wrapper) in a called method, changes to the reference will not be preserved outside of the method. Instead, you have two choices -
Store the state in an object field, and provide an accessor for that field (e.g. a getter),
Return boolean (or Boolean) from that method (instead of `void`).
When you pass found as an argument you are passing its value, and not a reference to it, so essentially you are creating a method instance variable.
I would suggest two options
The first would be to return the value:
found = lookHorizantal(word, array, i, j);
// Maybe check between these search calls if it is found?
found = lookVertical(word, array, i, j);
// Maybe check between these search calls
found = lookDiagnal(word, array, i, j);
// Maybe check between these search calls if it is found?
public boolean lookHorizantal(char[] inWord, char[][] inArray, int row, int column)
{
// OMITTED CODE
if(counter == inWord.length)
{
return true; /*******************/
// OMITTED CODE
}
}
or just reference the class variable:
public void lookHorizantal(char[] inWord, char[][] inArray, int row, int column)
{
// OMITTED CODE
if(counter == inWord.length)
{
found = true; /*******************/
// OMITTED CODE
}
}
These switches will change the class variable found directly.
Related
This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)
Okay, first off I can guarantee this has been asked, but I haven't found my specific problem and I don't have the rep to comment on an existing post. Basically I've instantiated a 2D array as a class object, since I need to access the array in multiple methods and changes have to stay permanent. However I don't know the actual needed size needed to create the matrix, and am getting null pointer exceptions when I try to change the size later.
Basically:
public static void sort(ArrayList<Character> line, int row)
{
System.out.println("line size " + (line.size()-1));
System.out.println("maze row check " + (maze[row] == null));
maze[row] = new int[line.size()-1];
for (int x = 0; x <line.size(); x++)
{
maze[row][x] = line.get(x);
System.out.println("final sopt " + maze[row][x]);
}
}
Is there a way to successfully do this? Or am I overlooking something very simple?
Thank you for taking the time to read / answer this,
Mark
And after what must be 10 edits going in circles here is the full code (full of printlns from testing and other code i just commented out because I didn't need it or wrote something better:
package maze;
import java.io.*;
import java.util.ArrayList;
import static java.lang.System.*;
public class Maze
{
private static int[][] maze;
public Maze(int size, String line)
{
}
public boolean hasExitPath(int r, int c)
{
return false;
}
public String toString()
{
String output="";
return output;
}
public static void doMaze(int x, int y)
{
}
public static void readMaze() throws IOException
{
System.out.println(0);
BufferedReader read = new BufferedReader(new FileReader("maze.dat"));
String numString;
int numLine;
String mazeLine;
int row = 0;
int x = 0;
int lastChar = 0;
while ((numString = read.readLine()) !=null && (mazeLine = read.readLine()) !=null)
{
System.out.println(1);
numLine = Integer.parseInt(numString.replaceAll("\\s+", ""));
System.out.println("numString" + numString + "numLine" + numLine); //both set to 5...
ArrayList<Character> curLine = new ArrayList<Character>();
for(int d = 0; d < numLine; d++) curLine.add('a');
System.out.println("curLine " + curLine.size());
for (int z = 0; z < mazeLine.length(); z++)
{
System.out.println(2);
// get first row of numbers >> need to check lastchar
// sort and send to get added
// if remainder of line is more than numLine
// go to step one, but start from lastchar
if (lastChar < curLine.size())
{
System.out.println(3);
for (x = 0; x < numLine; x++);
{
System.out.println(4);
curLine.add(mazeLine.charAt(x + lastChar));
}
lastChar = x + lastChar;
System.out.println("row " + row);
sort(curLine, row);
row++;
}
else{System.out.println("error"); System.out.println(lastChar); System.out.println(curLine.size());}
}
/*
numLine = Integer.parseInt(numString.replaceAll("\\s+", ""));
ArrayList<Character> curLine = new ArrayList<Character>(numLine);
for (int x = 0; x < numLine; x++)
{
//System.out.println(mazeLine.charAt(x));
System.out.println(maze[0][0]);
curLine.add(mazeLine.charAt(x));
}
y++; */
}
read.close();
}
public static void sort(ArrayList<Character> line, int row)
{
System.out.println("line size " + (line.size()-1));
System.out.println("maze row check " + (maze[row] == null));
maze[row] = new int[line.size()-1];
for (int x = 0; x <line.size(); x++)
{
maze[row][x] = Integer.parseInt(String.valueOf(line.get(x)));
System.out.println("final sopt " + maze[row][x]);
}
}
}
I have written a Java program to find duplicate characters in a string without Hashmap and set.
Below is the program,
package practice;
public class Duplicate {
public static void main(String[] args) {
String src= "abcad";
char[] srcChar= src.toLowerCase().toCharArray();
int len=srcChar.length;
int j=0;
boolean flag=false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k=0;
for(int i=0;i<len;i++)
{
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for(j=0;j<len;j++)
{
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if(srcChar[i]==srcChar[j])
{
k++;
}
}
if(k>1)
{
if(srcChar[i]>1)
{
System.out.println("This character "+srcChar[i]+" has repeated "+k+ " time");
}
else
{
System.out.println("There are no characters repeated in the given string");
}
}
k=0;
}
}
}
Output here is:
This character a has repeated 2 time
This character a has repeated 2 time
Here, I want the output like
This character a has repeated 2 time
i.e. not repeating the output twice. Since the character "a" is repeated twice, the output is also repeated twice.
kindly help me to get the output once instead of twice.
Thank you,
class PrintDuplicateCharacter
{
public static void main(String[] args)
{
String str = "HelloJava";
char[] ch = str.toCharArray();
int i=0,j=0;
for(i=0;i<ch.length;i++)
{
int count = 0 ;
for( j = i+1;j<ch.length;j++)
{// 4 6 , 8 , 10
if(ch[i] == ch[j] )
{
count++;
}
}
if(count != 0)
{
System.out.print(str.charAt(i) + " Occured " + count + " time");
}
}
}
}
private static void duplicateChar(String str){
char[] arr1 = str.toUpperCase().toCharArray();
int length = str.length();
int count = 1;
String s = "";
char c1 = '\u0000';
for(int i=0;i<length;i++){
count = 1;
for(int j=i+1;j<length;j++){
if(arr1[i] == arr1[j]){
count++;
c1 = arr1[i];
}
if(j == (length-1) && c1 != '\u0000' && !s.contains(String.valueOf(c1))){
s = s+" "+String.valueOf(c1)+" No of times: "+count+"\n";
}
}
}
System.out.println("\nDuplicate char are:\n"+s);
}
You can make a 2 dimensional array, 2 wide, the source strings height. In this array you store a character when it gets replaced and add one to the amount of times it has been replaced.
Something like(I don't know if these counters are correct):
replacements[j][0] = charAt(j);
replacements[j][1] += 1;
You would have to check if the character you are replacing already exists in this array and you can only print elements of the array if they aren't null.
You print this after the original loop.
All you need to fix is to start the second loop from i instead of 0.
for (int i = 0; i < len; i++) {
for (j = i; j < len; j++) {
...
}
...
}
Imports:
import java.util.ArrayList;
import java.util.List;
Code:
public static void main(String args[]) {
String input = "abcad"; // Input value
char[] chars = input.toLowerCase().toCharArray(); // Creates ArrayList
// of all characters
// in the String
List<Character> charR = new ArrayList<>(); // Creates a List used to
// saving the Characters it
// has saved
List<Integer> valR = new ArrayList<>(); // Creates a List that will
// store how many times a
// character is repeated
for (int i = 0; i < chars.length; i++) { // Loop through items in the
// ArrayList
char c = chars[i]; // Create Character value containing the value of
// the item at the "i" index of the ArrayList
if (charR.contains(c)) { // If the List contains item...
for (int i2 = 0; i2 < charR.size(); i2++) { // Loop through its
// items
if (charR.get(i2).equals(c)) { // If you find a match...
valR.set(i2, valR.get(i2) + 1); // Increase repeated
// value by 1
i2 = charR.size(); // Stop loop
} else { // Else...
i2++; // Increase index by 1
}
}
} else { // Else...
charR.add(c); // Add the Character to the List
valR.add(1); // Add the value 1 to the List (Meaning that the
// Character repeated once)
}
}
for (int i = 0; i < charR.size(); i++) { // Loop through all the items
// in the List
System.out.println("'" + charR.get(i) + "' : " + valR.get(i)); // Display
// what
// the
// character
// is
// and
// how
// many
// times
// it
// was
// repeated
}
}
Output:
'a' : 2
'b' : 1
'c' : 1
'd' : 1
char[] array=value.toCharArray();
int count=0;
char ch;
for(int i=0;i<array.length-1;i++)
{
ch=array[i];
count=1;
if(ch!='#'){
for(int j=i+1;j<array.length;j++)
{
if(ch==array[j]){
count++;
array[j]='#';
}
}
if(count>1)
{
System.out.println("char is " + ch + "count" + count);
}
}
}
You can also solve this problem with this code like :
public static void main(String[] args) {
String src = "abcad";
char[] srcChar = src.toLowerCase().toCharArray();
int len = srcChar.length;
int j = 0;
boolean flag = false;
char ch;
// System.out.println("Length of the String is "+len1);
// System.out.println("Length of the character array is "+len);
int k = 0;
for (int i = 0; i < len; i++) {
// System.out.println("i-----> "+i + " and character is "+srcChar[i]);
for (j = 0 + i; j < len; j++) {
// System.out.println("j-----> "+j + " and character is "+srcChar[j]);
if (srcChar[i] == srcChar[j]) {
k++;
}
}
if (k > 1) {
if (srcChar[i] > 1) {
System.out.println("This character " + srcChar[i] + " has repeated " + k + " time");
} else {
System.out.println("There are no characters repeated in the given string");
}
}
k = 0;
}
}
just we need to start the inner loop with j=0+i ;
for (j = 0 + i; j < len; j++)
This will you can observe above code;
How would I make it so that the line that says array.equals(guess) works and how would I change the load values method into not allowing duplicate numbers?
import java.util.Arrays;
import java.util.Random;
import javax.swing.JOptionPane;
public class Assignment {
private static int[ ] loadValues(){
int[] groupOfValues = new int[5];
Random randomized = new Random();
for (int index = 0; index < 5; index++) {
groupOfValues[index] = randomized.nextInt(39) + 1;
}
return groupOfValues;
}
private static void displayOutcome(int [ ] array, int guess){
if(array.equals(guess)){
JOptionPane.showMessageDialog(null, "Congrats, your guess of " + guess + " was one of these numbers:\n"
+ Arrays.toString(array));
}
else{
JOptionPane.showMessageDialog(null, "Sorry, your guess of " + guess + " was not one of these numbers:\n"
+ Arrays.toString(array));
}
}
public static void main(String[] args) {
int guessedConvert;
String guess;
do{
guess = JOptionPane.showInputDialog("Guess a number from 1-39");
guessedConvert = Integer.parseInt(guess);
}while(guessedConvert < 1 || guessedConvert > 39);
displayOutcome(loadValues(), guessedConvert);
}
}
Searching though an array requires a loop:
boolean found = false;
for (int i = 0 ; !found && i != array.length ; i++) {
found = (array[i] == guess);
}
if (found) {
...
}
To figure out if there are duplicates in loadValues add a similar code snippet inside the outer loop:
for (int index = 0; index < 5; index++) {
boolean found = false;
int next = randomized.nextInt(39) + 1;
// Insert a loop that goes through the filled in portion
...
if (found) {
index--;
continue;
}
groupOfValues[index] = next;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have been working on the UVa 630 problem for 2 days, http://acm.uva.es/p/v6/630.html
I have written a working code, however constantly getting the wrong answer result after the submission, my program works fine for the given input format and generate correct result, could someone please take a look at my code and find what's wrong with it please.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
class Main {
String[] init;
String[] sorted;
int voca = 0;
String[] test;
private String x;
private String y;
ArrayList<ArrayList> initial = new ArrayList<ArrayList>();
char[] charArray;
String input;
void initSort(String i) {
input = i;
charArray = input.toCharArray();
}
char[] get() {
return charArray;
}
void sort(int low, int high) {
int i = low;
char pivot = charArray[low];
for (int j = low + 1; j < high; j++) {
if (charArray[j] < pivot) {
if (j > i + 1) {
exchange(i + 1, j);
}
i++;
}
}
exchange(low, i);
if (i > low + 1)
sort(low, i);
if (i + 2 < high)
sort(i + 1, high);
}
void exchange(int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// ********************************************
void begin() {
// System.out.println("begin test");
int numOfdataSet;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
numOfdataSet = Integer.parseInt(in.readLine());
do {
ArrayList currentSet = new ArrayList();
int numberOfdic;
String tempStringV;
String tempStringT;
int i = 0;
try {
String emptyLine = in.readLine();
numberOfdic = Integer.parseInt(in.readLine());
;
currentSet.add(emptyLine);
currentSet.add(Integer.toString(numberOfdic));
// System.out.println("enter numberOfdic is " +
// numberOfdic);
while (i < numberOfdic) {
tempStringV = in.readLine();
currentSet.add(tempStringV);
i++;
}
// System.out.println("input test word");
tempStringT = in.readLine();
currentSet.add(tempStringT);
while (!tempStringT.equals("END")) {
tempStringT = in.readLine();
currentSet.add(tempStringT);
}
} catch (IOException e) {
e.printStackTrace();
}
initial.add(currentSet);
numOfdataSet--;
} while (numOfdataSet != 0);
} catch (IOException e) {
}
;
print();
}
// ***************************************************
void getArrays(ArrayList<String> a) {
// read the file and put the words into a temporary array
String[] temp = new String[a.size()];
for (int i = 0; i < a.size(); i++) {
temp[i] = a.get(i);
// System.out.println("temp "+i+" is "+temp[i]);
}
// extract the vocabulary counter from the temp array
int vocaCounter;
int shift;
if (!temp[0].equals("")) {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
} else {
shift = 2;
vocaCounter = Integer.parseInt(temp[1]);
}
// System.out.println("there are "+vocaCounter);
// store the vocabulary into the array named as init
init = new String[vocaCounter];
for (int i = shift; i < vocaCounter + shift; i++) {
init[i - shift] = temp[i];
// System.out.println(i - shift + " voca is " + init[i - shift]);
}
// store the test words into the array named as test
test = new String[temp.length - vocaCounter - shift - 1];
for (int j = 0; j < temp.length - vocaCounter - shift - 1; j++) {
test[j] = temp[j + vocaCounter + shift];
// System.out.println("test "+j+" is "+test[j]);
}
sorted = init;
}
/**
* sort the two strings
*/
void arraySorter() {
x = x.toLowerCase();
initSort(x);
sort(0, x.length());
get();
// java.util.Arrays.sort(FirstArray);
y = y.toLowerCase();
initSort(y);
sort(0, y.length());
get();
}
String getEle(String in) {
initSort(in);
sort(0, in.length());
return new String(get());
}
void print() {
Iterator<ArrayList> iterator = initial.iterator();
while (iterator.hasNext()) {
getArrays((ArrayList<String>) iterator.next());
// ****************
/**
* sort the test array and store it as the testSort array
*/
String[] testSort = new String[test.length];
for (int i = 0; i < test.length; i++) {
testSort[i] = test[i];
}
for (int i = 0; i < test.length; i++) {
testSort[i] = getEle(testSort[i]);
}
// for(int i=0;i<test.length;i++)
// {
// System.out.println("test is "+test[i]+" and test sorted is "+testSort[i]);
// }
/**
* sort the vocabulary array and store the sorted array as vocaSort
*/
String[] vocaSort = new String[init.length];
for (int i = 0; i < init.length; i++) {
vocaSort[i] = init[i];
}
for (int i = 0; i < init.length; i++) {
vocaSort[i] = getEle(vocaSort[i]);
}
// start the testing process
for (int i = 0; i < test.length; i++) {
int counter = 1;
System.out.println("Anagrams for: " + test[i]);
for (int j = 0; j < sorted.length; j++) {
// anagramTester(test[i], init[j]);
boolean result = testSort[i].equals(vocaSort[j]);// //AnagramTester();
if (result == true && counter < 10) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 100) {
System.out.println(" " + counter + ") " + init[j]);
counter++;
} else if (result == true && counter < 1000) {
System.out.println("" + counter + ") " + init[j]);
counter++;
}
}
if (counter == 1)
System.out.println("No anagrams for: " + test[i]);
}
System.out.println();
}
}
/**
* main function
*
* #param args
*/
public static void main(String[] args) {
Main myWork = new Main(); // create a dinamic instance
myWork.begin();
}
}
below is the input.txt file
1
4
atol
lato
rola
tara
kola
tola
END
2
24
uhgj
uhjg
ughj
ugjh
ujhg
ujgh
hujg
hugj
hgju
hguj
hjgu
hjug
guhj
gujh
ghuj
ghju
gjuh
gjhu
jugh
juhg
jhgu
jhug
jghu
jguh
jguh
END
it was a output format issue and problem solved