For loop isn't printing correct "." - java

What I am trying to do is have it take a java file that look like this
public class test1 {
public static void main ( string[] args ) {
System.out.println( "This is Test 1." );
}
}
And it is suppose to output a text file with the proper spacing and indents.
So far I can get the correct indenting for the first the lines. But I am having trouble with my second for loop that prints the spaces for the ending brackets. The ending brackets are prints outward like the first 3 lines instead of inward. Sorry if my variables are confusing.
Here is my code so far
public class JavaJustifier {
public static void main( String[] args )
throws FileNotFoundException {
for( int i = 1; i < 6; i++ ) {
justifyJava( "Test" + i + ".java",
"Justified" + i + ".txt",
4 );
}
}
public static void justifyJava( String inputFileName,
String outputFileName,
int tabSize )
throws FileNotFoundException {
int counter = 0;
int counter2 = 0;
int blah = 0;
File f = new File(inputFileName);
File p = new File(outputFileName);
if (p.exists())
p.delete();
Scanner input = new Scanner (f);
PrintStream name = new PrintStream(new File(outputFileName));
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
if (line.contains("{") == true) {
name.print("{\r\n");
counter++;
for (int i = 1; i <= counter; i++) {
for (int j = 0; j <= tabSize; j++) {
name.print(" ");
}
}
System.out.println(counter);
} else if (line.contains("}") == true) {
name.print("\r\n");
counter--;
for (int x = 1; x <= counter; x++) {
for (int y = 1; y <= tabSize; y++) {
name.print(" ");
}
}
name.print("}");
System.out.println(counter);
} else {
name.print(line);
}
}
}
What it gives me is
public class Test1
{
public static void main( String[] args )
{
System.out.println( "This is Test 1." );
}
}
What I desire is this
public class Test1
{
public static void main( String[] args )
{
System.out.println( "This is Test 1." );
}
}

Okay, I've refactored a few things (and it was necessary) but it works exactly as you expect it to (AFAIK!).
Here's the code:
public class JavaJustifier {
static int counter = 0;
static int tabSize = 4;
public static void main(String[] args) throws FileNotFoundException {
justifyJava("Test1.java", "Justified1.txt");
}
private static void processLine(PrintStream name, String line) {
if (line.contains("{")) {
String preText = line.substring(0, line.indexOf("{"));
String postText = line.substring(line.indexOf("{") + 1)
.replaceAll("\\n", "").replaceAll("\\r\\n", "");
printSpaces(name);
name.println(preText);
printSpaces(name);
name.println("{");
counter++;
processLine(name, postText);
} else if (line.contains("}")) {
String preText = line.substring(0, line.indexOf("}"));
String postText = line.substring(line.indexOf("}") + 1)
.replaceAll("\\n", "").replaceAll("\\r\\n", "");
name.println(preText);
counter--;
printSpaces(name);
name.println("}");
processLine(name, postText);
} else {
if (!line.equals("\r\n") && line.length() != 0) {
printSpaces(name);
name.print(line);
}
}
}
private static void printSpaces(PrintStream p) {
for (int i = 1; i <= counter; i++) {
for (int j = 0; j <= tabSize; j++) {
p.print(" ");
}
}
}
public static void justifyJava(String inputFileName, String outputFileName)
throws FileNotFoundException {
File f = new File(inputFileName);
File p = new File(outputFileName);
if (p.exists())
p.delete();
Scanner input = new Scanner(f);
PrintStream name = new PrintStream(new File(outputFileName));
while (input.hasNextLine()) {
String line = input.nextLine().trim();
processLine(name, line);
}
}
}

Related

Putting subsequences in HashMap

I am trying to get my program to print out "(ABC,1) (BCD,1) (CDB,1) (DBC,1)" if I have a .txt file that shows ABCDBCD but the error code states The local variable hentSub may not have been initialized Java(536870963) on my subsequence getSub. Any tips? The reason it states (ABC,1) is because the 1 is a person, and a subseq of their DNA
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("C:\\Users\\Public\\File1.txt"));
String currentLine, subString;
int subSize = 3;
HashMap<String, subsequence> subSeqHashNy = new HashMap<String, subsequence> ();
subsequence getSub;
int count = 0;
while (scanner.hasNextLine()) {
currentLine = scanner.nextLine();
currentLine = currentLine.trim();
if (currentLine.length() < subSize) {
break;
}
for (int i = 0; i + subSize <= currentLine.length(); i++) {
subString = currentLinje.substring(i, i + subSize);
System.out.print(subString + " ");
for(subsequence sub1: subSeqHashNy.values()) {
if (hetSub == null) {
subSeqHashNy.put(sub1.key(), sub1);
}
else {
int num = getSub.getNum();
sub1.leggTil(num);
subSeqHashNy.put(sub1.key(), sub1);
}
}
}
System.out.print("\n");
}
scanner.close();
}

Palindromes and Arrays, an effort in frustration

I am currently attempting to make a Palindrome Checker using a series of Clean and dirty arrays and while I've gotten it to compile but I'm having issues getting the code to detect the actual palindromes
Below is the code in question, any and all help would be most appreciated.
import java.io.*;
import java.util.Scanner;
public class palindrome
{
public static void main (String[] args) throws IOException
{
File inputFile = new File ("Palindromes.txt");
Scanner inputScan = new Scanner (inputFile);
String [] dirty = new String [20];
int i = 0;
while (inputScan.hasNext())
{
dirty[i] = inputScan.nextLine();
System.out.println(dirty[i]);
i++;
}
inputScan.close();
String [] clean = new String [i];
String reverse ="";
for (int x = 0; x < clean.length; x++)
{
clean[x] = "";
for (int z = length; z < dirty[x].length(); z--)
{
char test = dirty[x].charAt(z);
if (Character.isLetterOrDigit(test))
{
test = Character.toLowerCase(test);
clean [x] += test;
if (clean[x].equals(clean[z]))
{
System.out.println(clean[z] +" is a palindrome");
} else
{
System.out.println(clean[z] +" is NOT a palindrome");
}
}
}
}
for (int j = 0; j < clean.length; j++)
{
System.out.println(clean[j]);
}
}
Are you trying to do something like this?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Palindrome {
public static boolean isPalindrome(String s) {
s = s.toLowerCase().replaceAll("[\\s\\p{Punct}]", "");
int len = s.length(), mid = len / 2;
for (int x = 0; x < mid; x++)
if (s.charAt(x) != s.charAt(len - x - 1))
return false;
return true;
}
public static void main(String[] args) throws IOException {
File inputFile = new File("Palindromes.txt");
try (Scanner scanner = new Scanner(inputFile)) {
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (isPalindrome(s)) {
System.out.println(s + " is a palindrome");
} else {
System.out.println(s + " is NOT a palindrome");
}
}
}
}
}

find all palindromes in string

I need to find all the palindromes in a string. It takes user input
example: "abbaalla"
it loops through creating a substring that changes as the loop progresses.
example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..
once it reaches the max length of the word it iterates the start of the substring and repeats
example: check palindrome "b" "bb" "bba" and so on..
I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"
the final output should be a string that includes all palindromes. in this case;
output: "abba alla"
Also this program currently results in: String index out of range: -1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
public static Set<CharSequence> printAllPalindromes(String input) {
if (input.length() <= 2) {
return Collections.emptySet();
}
Set<CharSequence> out = new HashSet<CharSequence>();
int length = input.length();
for (int i = 1; i <= length; i++) {
for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
if (input.charAt(j) == input.charAt(k)) {
out.add(input.subSequence(j, k + 1));
} else {
break;
}
}
}
return out;
}
Simple Brute force way-->
public class AllPalindromes {
public static boolean checkPalindrome(String str) {
for(int i=0;i<=str.length()/2;i++)
if(str.charAt(i)!=str.charAt(str.length()-1-i))
return false;
return true;
}
public static void printAllPalindrome(String str) {
for(int i=0;i<=str.length();i++)
for(int j=i;j<str.length();j++)
if(checkPalindrome(str.substring(i,j+1)))
System.out.println(str.substring(i,j+1));
}
public static void main(String[] args) {
printAllPalindrome("abbaalla");
}
}
Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)
Note that #jw23's solution does not display the palindromes which are of even length — only the odd length ones.
public class HelloWorld{
public static void printPalindromes(String s) {
if (s == null || s.length() < 3)
return;
System.out.println("Odd Length Palindromes:");
// Odd Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
System.out.println("\nEven Length Palindromes:");
// Even Length Palindromes
for (int i=1; i<s.length()-1; i++) {
for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
if (s.charAt(j) == s.charAt(k)) {
if (k-j+1 >= 3)
System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
}
else
break;
}
}
}
public static void main(String[] args){
String s = "abcbaaabbaa";
printPalindromes(s);
}
}
public class Palindrome
{
static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String array[]=s1.split("");
System.out.println("Palindromes are :");
for(int i=0;i<=array.length;i++)
{
for(int j=0;j<i;j++)
{
String B=s1.substring(j,i);
verify(B);
}
}
System.out.println("\n"+count);
sc.close();
}
public static void verify(String s1)
{
StringBuilder sb=new StringBuilder(s1);
String s2=sb.reverse().toString();
if(s1.equals(s2))
{
System.out.print(s1+" ");
count++;
}
}
}
My own logic for palindrome program for all substrings
public class Test1 {
public static void main(String[] args) {
String s = "bob";
ArrayList<Character> chr = new ArrayList<Character>();
ArrayList<String> subs= new ArrayList<String>();
for (int i=0;i<s.length();i++)
{
chr.add(s.charAt(i));
}
System.out.println(chr.toString());
StringBuilder subString = new StringBuilder();
for(int i=0; i < s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
for(int k=i;k<=j;k++)
{
subString.append(chr.get(k));
}
System.out.println(subString.toString());
subs.add(subString.toString());
subString.setLength(0);
}
}
System.out.println(subs);
for(String st : subs)
{
String st2 = new StringBuffer(st).reverse().toString();
if(st.equals(st2))
{
System.out.println(st+" is a palindrome");
}
else
{
System.out.println(st+" not a palindrome");
}
}
}
}
Print All Palindromes in the string
import java.util.*;
class AllPalindroms
{
public static void main(String args[])
{
String input = "abbaalla";
if (input.length() <= 1)
{
System.out.println("Not Palindrome Found.");
}
else
{
int length = input.length();
Set<String> set = new HashSet<String>();
for (int i = 0; i <length; i++)
{
//if(i==0)
for (int j=i+1;j<length+1;j++)
{
String s = input.substring(i, j);
StringBuffer sb = new StringBuffer(s);
sb.reverse();
if(s.equals(sb.toString()) && s.length()>1)
{
set.add(s);
}
}
}
System.out.println(set);
}
}
}
My code to count all palindromes in a string:
import java.util.Scanner;
public class CountPalindromeSapient {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the given string: ");
String inputStr = sc.nextLine();
countPalindrome(inputStr);
System.out.println("\nTotal count of Palindromes are: "+count);
sc.close();
}
private static int countPalindrome(String inputStr) {
int count = 0;
int len = inputStr.length();
int startIndex =0;
String subString = "";
System.out.println( "Possible substrings are: ");
for (int i = 0; i < len; i++) {
for (int j = startIndex; j <= len; j++) {
subString = inputStr.substring(startIndex, j);
System.out.println(subString);
count = checkPalindrome(subString);
}
startIndex++;
}
return count;
}
private static int checkPalindrome(String subString) {
// TODO Auto-generated method stub
int subLen = subString.length();
boolean isPalindrome = false;
for(int k=0; k<subLen; k++,subLen-- ) { // Important
if (subString.charAt(k) != subString.charAt(subLen -1)) {
isPalindrome = false;
break;
}else {
isPalindrome = true;
}
}
if(isPalindrome == true) {
count ++;
}
return count;
}
}
class StringTest {
public static void main(String[] args) {
StringTest test = new StringTest();
boolean bool = test.checkPalindrom("abbaalla");
if(!bool)
System.out.println("String is not palindrom");
}
private boolean checkPalindrom(String k){
int[] count= new int[k.length()];
boolean[] arr = new boolean[k.length()];
for(int t=0;t<k.length();t++){
int j=0;
char ch = k.charAt(t);
for(int x=t+1;x<k.length();x++){
if(j<count.length){
if(ch == k.charAt(x))
count[j] = x + 1;
else
count[j] = 0;
j++;
}
}
arr[t] = workOnArr(count,t,k);
}
for(int z=0;z<arr.length;z++){
if(arr[z])
return true;
}
return false;
}
private boolean workOnArr(int[] s,int z,String w){
int j = s.length - 1;
while(j -- > 0){
if(s[j] != 0){
if(isPalindrom(w.substring(z, s[j]))){
if(w.substring(z, s[j]).length() > 1){
System.out.println(w.substring(z, s[j]).length());
System.out.println(w.substring(z, s[j]));
}
return true;
}
}
}
return false;
}
private boolean isPalindrom(String s){
int j= s.length() -1;
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i) != s.charAt(j))
return false;
j--;
}
return true;
}
}
output:-
given palindrom are:-
abba, bb, aa, alla, ll
Question: All the palindromes from a word.
public class Test4 {
public static void main(String[] args) {
String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
allpalindromicsubstrings(a);
}// main
private static void allpalindromicsubstrings(String a) {
Set<String> set = new HashSet<String>();
for (int i = 0; i < a.length(); i++) {
// odd length palindrome
expand(a, i, i, set);
// even length palindrome
expand(a, i, i + 1, set);
} // for
set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
}// ee
private static void expand(String a, int start, int last, Set<String> set) {
// run till a[start...last] is a palindrome
while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {
set.add(a.substring(start, last + 1));
// expand in both directions
start--;
last++;
}
}// ee
}
The output palindromes in the word =>
niin
ADA
eye
MADAM
iniini
GiniiniG
ii
MeyeM
ini
Print all the palindromes in a string:
public class test1 {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
System.out.println(list);
List<String> plist = new ArrayList<>();
for(int i = 0 ; i <list.size();i++) {
String curr =list.get(i);
if(ispalin(curr)) {plist.add(curr);}
}//for
System.out.println("palindrome list => " +plist);
}//main
private static boolean ispalin(String curr) {
if(curr == null || curr.length() == 0) {return false;}
return new StringBuffer(curr).reverse().toString().equals(curr);
}
}
The output is: palindrome list => [MADAM, GiniiniG]
Another Method in Java 8:
public class B {
public static void main(String[] args) {
String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
// list to stream
// for Multi Threaded environment
Stream<String> stream = list.parallelStream();
// also,Stream<String> stream = list.stream(); for single Threaded environment
long palindrome = stream.filter(B::isPalindrome)// find all palindromes
.peek(System.out::println) // write each match
.count();// terminal - return a count
System.out.println("Count of palindromes: " + palindrome);
// System.out.println("List => " + list);
}
private static boolean isPalindrome(String aa) {
return new StringBuffer(aa).reverse().toString().equals(aa);
}
}
Output:
GiniiniG
MADAM
Count of palindromes: 2
Java program to enter a string and frame a word by joining all the first character of each word.
Display a new word.
import java.util.*;
public class Anshu {
public static void main(String args[]) {
Scanner in = new Scanner(System.in)
System.out.println("Enter a string");
String s = in .nextLine();
char ch = s.charAt(0);
System.out.print(ch);
s = s.toUpperCase;
int l = s.length();
for (int i = 0; i < l; i++)
char a = s.charAt(i);
if (Character.isWhiteSpace())
System.out.print(s.charAt(i + 1) + "");
}
}

How to Find the Longest Palindrome (java)

Hi I've been doing this java program, i should input a string and output the longest palindrome that can be found ..
but my program only output the first letter of the longest palindrome .. i badly need your help .. thanks!
SHOULD BE:
INPUT : abcdcbbcdeedcba
OUTPUT : bcdeedcb
There are two palindrome strings : bcdcb and bcdeedcb
BUT WHEN I INPUT : abcdcbbcdeedcba
output : b
import javax.swing.JOptionPane;
public class Palindrome5
{ public static void main(String args[])
{ String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
for(int x=0; x<size; x++)
{ for(int y=x+1; y<size-x; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
Out = GetLongest(subword);
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
public static String GetLongest(String sWord)
{
int sLength = sWord.length();
String Lpalindrome = "";
int storage = 0;
if(storage<sLength)
{
storage = sLength;
Lpalindrome = sWord;
}
return(Lpalindrome);
}
}
modified program..this program will give the correct output
package pract1;
import javax.swing.JOptionPane;
public class Palindrome5
{
public static void main(String args[])
{
String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
String subword = "";
String revword = "";
String Out = "";
int size = word.length();
boolean c;
String Lpalindrome = "";
int storage=0;
String out="";
for(int x=0; x<size; x++)
{ for(int y=x+1; y<=size; y++)
{ subword = word.substring(x,y);
c = comparisonOfreverseword(subword);
if(c==true)
{
int sLength = subword.length();
if(storage<sLength)
{
storage = sLength;
Lpalindrome = subword;
out=Lpalindrome;
}
}
}
}
JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}
public static boolean comparisonOfreverseword(String a)
{ String rev = "";
int tempo = a.length();
boolean z=false;
for(int i = tempo-1; i>=0; i--)
{
char let = a.charAt(i);
rev = rev + let;
}
if(a.equalsIgnoreCase(rev))
{
z=true;
}
return(z);
}
}
You have two bugs:
1.
for(int y=x+1; y<size-x; y++)
should be
for(int y=x+1; y<size; y++)
since you still want to go all the way to the end of the string. With the previous loop, since x increases throughout the loop, your substring sizes decrease throughout the loop (by removing x characters from their end).
2.
You aren't storing the longest string you've found so far or its length. The code
int storage = 0;
if(storage<sLength) {
storage = sLength;
...
is saying 'if the new string is longer than zero characters, then I will assume it is the longest string found so far and return it as LPalindrome'. That's no help, since we may have previously found a longer palindrome.
If it were me, I would make a static variable (e.g. longestSoFar) to hold the longest palindrome found so far (initially empty). With each new palindrome, check if the new one is longer than longestSoFar. If it is longer, assign it to longestSoFar. Then at the end, display longestSoFar.
In general, if you're having trouble 'remembering' something in the program (e.g. previously seen values) you have to consider storing something statically, since local variables are forgotten once their methods finish.
public class LongestPalindrome {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}
public static void printLongestPalindrome(String S)
{
int maxBack=-1;
int maxFront = -1;
int maxLength=0;
for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
{
int back = potentialCenter-1;
int front = potentialCenter + 1;
int longestPalindrome = 0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome+1;
maxBack = back + 1;
maxFront = front;
}
back = potentialCenter;
front = potentialCenter + 1;
longestPalindrome=0;
while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
{
back--;
front++;
longestPalindrome++;
}
if (longestPalindrome > maxLength)
{
maxLength = longestPalindrome;
maxBack = back + 1;
maxFront = front;
}
}
if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
else{
System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
}
}
}
I have my own way to get longest palindrome in a random word. check this out
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.
public class LongestPalindrome {
public static void main(String[] args) {
HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
}
private static HashMap<String, Integer> findLongestPalindrome(String str) {
int i = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
while (i < str.length()) {
String alpha = String.valueOf(str.charAt(i));
if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
if (isPalindrome(pali)) {
map.put(pali, pali.length());
i = str.lastIndexOf(str.charAt(i));
}
}
i++;
}
return map;
}
public static boolean isPalindrome(String input) {
for (int i = 0; i <= input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}
}
This approach is simple.
Output:
String:abcdeedcba Value:10
String:4444 Value:4
String:6776 Value:4
String:ghihg Value:5
This is my own way to get longest palindrome. this will return the length and the palindrome word
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));
}
static String longestPalSubstr(String str) {
char [] input = str.toCharArray();
Set<CharSequence> out = new HashSet<CharSequence>();
int n1 = str.length()-1;
for(int a=0;a<=n1;a++)
{
for(int m=n1;m>a;m--)
{
if(input[a]==input[m])
{
String nw = "",nw2="";
for (int y=a;y<=m;y++)
{
nw=nw+input[y];
}
for (int t=m;t>=a;t--)
{
nw2=nw2+input[t];
}
if(nw2.equals(nw))
{
out.add(nw);
break;
}
}
}
}
int a = out.size();
int maxpos=0;
int max=0;
Object [] s = out.toArray();
for(int q=0;q<a;q++)
{
if(max<s[q].toString().length())
{
max=s[q].toString().length();
maxpos=q;
}
}
String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max;
return output;
}
this method will return the max length palindrome and the length of it. its a way that i tried and got the answer. and this method will run whether its a odd length or even length.

Java Array Index Out of Bounds Exception [duplicate]

This question already has an answer here:
Closed 10 years ago.
I run through the entire code. I am able to enter a simple .txt file to search for a word. After it asks for a word, it returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -48
at SearchEngine.main(SearchEngine.java:150)
Line 150 is for (int j = 0; j
Any help debugging?
This is basic search engine program that should be able to search a .txt file for any word.
Assignment link: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
System.out.println("Enter a word to be searched (type quit to exit program)");
Scanner keyboard = new Scanner(System.in);
String searchWord = keyboard.next();
while (!searchWord.equals("quit")) {
int counter = 0;
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
if(invertedIndex[wordPos][j] != 0) {
int number = invertedIndex[wordPos][j];
String printOut = concordanceArray[number];
System.out.print(number);
System.out.print(" :");
System.out.println(printOut);
}
}
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
From what I can see your getNumOfDistinctWords(String[] x) is wrong. This is returning a value of one less than it should be. Here is a modified version of the code:
import java.util.*;
import java.io.*;
public class SearchEngine {
//Counts the number of words in the file
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String[] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i < x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException {
HashSet<String> distinctWords = new HashSet<String>();
for(int i=0; i<x.length; i++){
distinctWords.add(x[i]);
}
String[] distinctWordsArray = new String[distinctWords.size()];
int i = 0;
for(String word : distinctWords){
distinctWordsArray[i] = word;
i++;
}
return distinctWordsArray;
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//Output the number of words in the file
System.out.println("Number of words is: " + NUM_WORDS);
String[] allWordsArray = new String[NUM_WORDS];
readInWords(input, allWordsArray);
Arrays.sort(allWordsArray);
String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray);
//Output the number of distinct words
System.out.println("Number of distinct words is: " + distinctWordsArray.length);
System.out.println("Finished creating distinctWordsArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String[] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[distinctWordsArray.length][10];
int [] wordCountArray = new int[distinctWordsArray.length];
int lineNum = 0;
while (lineNum < concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
//Find the position the word appears on the line, if word not found returns a number less than 0
int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next());
if(wordPos > -1){
wordCountArray[wordPos] += 1;
}
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
I should also point out the fact that Arrays.binarySearch(distinctWordsArray, scan.next()); will return a number less than 0 if the word is not found on that line. This is why you are getting the Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 as wordCountArray is being referenced at index -1 which of course doesn't exist!
The code after this also looks buggy but I'll let you fix that!!
Without knowing exactly where line 126 is, finding this specific bug is just too much hassle. But I've got some advice for the rest of the code:
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
Normally, variables in all-caps are constants that are assigned at compile time. It's a tradition that comes from C days, when it was wonderful to know which "variables" were actually replaced by the preprocessor. But the convention has proven to be useful in other languages, and most programmers would expect NUM_DISTINCT_WORDS to be assigned a specific value at compile time.
This code is simply unreadable:
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
A more idiomatic way to show these nested loops is:
for (int i = 0; i < invertedIndex.length; i++) {
for (int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
}
}
}
Because I use the standard Lindent script to do re-indenting, I get tabs. You don't have to use tabs, but they are convenient to add and delete with a single keystroke, and they are deep enough to be obviously visible even with smallish type faces. You'll find your code far easier to work with if you follow the standard indenting idioms.
The following piece of code is extremely unfortunate:
catch(FileNotFoundException exception) {
System.out.println("File Not Found");
}
It would be better to catch a higher-level exception and include the exception message. You can more easily handle dozens of errors if you catch an exception higher in the hierarchy, and the error messages will be far more informative.
Your main() method performs a lot of detailed work. I think your code would be easier to test, easier to debug, and easier to read, if you break it apart into more methods. Try to get the main() to read practically like a high-level description of your code.
With the line with the bug on it now easily visible, I can spot the problem:
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
You've looked up the wordPos in the vocabArray, but modified content in the wordCountArray. Are you sure they are the same size and have the same meanings?

Categories

Resources