So I have been writing a chat client and I decided to make a search function so you could find a particular word in the chat history and it selects it. However, what happens is that each line below the initial line the selection is that many indexes right of the word it should select. Is there a new line character or index locations I am missing?
How do I get around the indexes changing on each line?
Or perhaps there is an issue in my code:
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {
toSearchText = searchText.getText();
if (!toSearchText.equals("")) {
for (int i = index; i < searchBlock.length(); i++) {
if (searchBlock.charAt(i) == toSearchText.charAt(0)) {
System.out.println("found first char- Starting check loop." + i + j + "::" + count);
for (j = i; j < i + toSearchText.length(); j++) {
System.out.println("J" + j + " II " + innerIndex);
if (searchBlock.charAt(j) == toSearchText.charAt(innerIndex)) {
innerIndex++;
count++;
System.out.println("found char:" + innerIndex + " - " + searchBlock.charAt(j));
} else {
System.out.println("Not the word");
break;
}
}
}
System.out.println(i);
System.out.println(j);
if (count == toSearchText.length()) {
if (searchBlock.substring(i, j).equals(toSearchText)) {
System.out.println(searchBlock.substring(i, j) + " and " + toSearchText);
System.out.println("focusing");
ClientWindow.mainText.requestFocusInWindow();
ClientWindow.mainText.select(i, j);
count = 0;
innerIndex = 0;
index = i + toSearchText.length();
if (index > searchBlock.length()) {
index = 0;
}
break;
}
} else {
System.out.println("focus refused");
}
}
System.out.println("Search Finished");
}
}
Ok, So to get around the issue of there being an extra index on each line, I wrote a method to count the lines and then minused that value from the indexes.
private int checkLine(int position){
int counter = 0;
Scanner text = new Scanner(searchBlock.substring(0,position));
while(text.hasNextLine()){
counter++;
text.nextLine();
}
return counter - 1;
}
Related
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;
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.
I am doing recursion for a given phone number and print all the possible string representation of the number. The problem is in loop for (int j=0;j<ops;j++) { the size of the "perm" ArrayList keep increasing in every iteration. I want to get fixed pattern and add new number e.g perm = 11 and call recursion with tperm=110,111,112.
import java.util.*;
public class phoneNum {
public static void getSt ( List<Integer>list , List<Integer> perm ) {
Integer len = list.size();
Integer len1 = perm.size();
Integer ops = 0;
if (len == len1) {
for(int k=0;k<len;k++) {
System.out.print(" " + list.get(k));
}
for(int k=0;k<len;k++) {
System.out.print(" " + perm.get(k));
}
System.out.print("====");
System.out.print(getPattrn(list,perm));
System.out.println("\n");
} else {
for (int i=0; i<len1+1; i++) {
if(list.get(i) == 7 || list.get(i) == 9) {
ops = 4;
} else {
ops = 3;
}
for (int j=0;j<ops;j++) {
List<Integer> tperm = new ArrayList<Integer>(perm);
tperm.add(i,j);
System.out.println("Size=" + tperm.size() + " ---" + perm.size());
getSt(list,tperm);
}
}
}
}
You can add tperm.remove(i) at the end of inner for loop.
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