The problem is when I enter a decimal input. For example 10001.10.
It says NumberFormatException. But when I input just a number without decimal like "1001110" its works fine.
import java.util.*;
import java.util.Arrays;
public class Binary {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String[] Condition = { "0", "1", "." };
//Accept First Input
String numInp1="";
System.out.print("Enter First Binary Number: ");
numInp1 = in.nextLine();
//Accept Second Input
String numInp2="";
System.out.print("Enter Second Binary Number: ");
numInp2 = in.nextLine();
//numInp1
String _Array1 []=new String[numInp1.length()];
//numInp2
String _Array2 []=new String[numInp2.length()];
//Catch error in numInp1/_Array1
boolean flag1 = false;
for(int i = 0; i < _Array1.length; i++)
{
_Array1[i] = String.valueOf(numInp1.charAt(i));
int cnt = 0;
for (int j = 0; j < Condition.length; j++)
{
if (!_Array1[i].equals(Condition[j]))
{
cnt++;
}
else
{
break;
}
if (cnt == 3)
{
flag1 = true;
}
}
}
//Catch error in numInp2//_Array2
boolean flag2 = false;
for(int i = 0; i < _Array2.length; i++)
{
_Array2[i] = String.valueOf(numInp2.charAt(i));
int cnt = 0;
for (int j = 0; j < Condition.length; j++)
{
if (!_Array2[i].equals(Condition[j]))
{
cnt++;
}
else
{
break;
}
if (cnt == 3)
{
flag2 = true;
}
}
}
//Getting which of the Array has Higher Input
if(flag2 == false && flag1 == false)
{
int HigherLength = 0;
if(_Array1.length >= _Array2.length)
{
HigherLength = _Array1.length + _Array2.length;
}
else
{
HigherLength = _Array2.length + _Array1.length;
}
//Declaring the size of higher length as the size of Equals[] Array
int Equals[] = new int[HigherLength];
int _Array1Int[] = new int[_Array1.length];
int _Array2Int[] = new int[_Array2.length];
for(int i = 0;i<_Array1.length;i++)
{
if(_Array1[i].equals("."))
{
_Array1[i] = "6";
}
_Array1Int[i] = Integer.parseInt(_Array1[i]);
}
for(int i = 0;i<_Array2.length;i++)
{
if(_Array2[i].equals("."))
{
_Array2[i] = "6";
}
_Array2Int[i] = Integer.parseInt(_Array2[i]);
}
//_________________________
int numInp1int = Integer.parseInt(numInp1);
int numInp2int = Integer.parseInt(numInp2);
int i,m,n,sum,carry=0;
for(i=Equals.length-1;i>=0;i--)
{
m=numInp1int%10;
n=numInp2int%10;
numInp1int=numInp1int/10;
numInp2int=numInp2int/10;
sum=m+n+carry;
if(sum==1)
{
Equals[i]=1;
carry=0;
}
else if(sum==2)
{
Equals[i]=0;
carry=1;
}
else if(sum==3)
{
Equals[i]=1;
carry=1;
}
else
{
Equals[i]=m+n+carry;
}
}
String Equals1[] = new String[Equals.length];
for(i=0;i<Equals.length;i++)
{
try{
Equals1[i] = String.valueOf(Equals[i]);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
if (Equals1[i].equals("6"))
{
Equals1[i] = ".";
}
System.out.print(Equals1[i]);
}
}
}
}
Do below changes in your code
Remove below 2 lines-
int numInp1int = Integer.parseInt(numInp1);
int numInp2int = Integer.parseInt(numInp2);
Replace with below code -
StringBuilder strNum1 = new StringBuilder();
for (int num : _Array1Int)
{
strNum1.append(num);
}
int numInp1int = Integer.parseInt(strNum1.toString());
StringBuilder strNum2 = new StringBuilder();
for (int num : _Array2Int)
{
strNum2.append(num);
}
int numInp2int = Integer.parseInt(strNum2.toString());
Updating _Array1 and _Array2 does not change numInp1int and numInp2int which you are trying to parse as Integer.
You should learn to interpret error messages in the stack trace. Here you can clearly see where the problem is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10001.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at q35640801.Binary.main(Binary.java:120)
It's in the call parseInt() of class Integer. It cannot parse decimal numbers like 10001.10
Related
I am trying to separate a text in k-shingles, sadly I cannot use scanner. If the last shingle is too short, I want to fill up with "_". I came this far:
public class Projektarbeit {
public static void main(String[] args) {
testKShingling(7, "ddssggeezzfff");
}
public static void testKShingling(int k, String source) {
//first eliminate whitespace and then fill up with withespaces to match target.length%shingle.length() == 0
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<String>();
int i;
int l = txt.length();
String shingle = "";
if (k == 1) {
for(i = 0; i < l; i++){
shingle = txt.substring(i, i + k);
shingles.add(shingle);
};
}
else {
for(i = 0; i < l; i += k - 1){
try {
shingle = txt.substring(i, i + k);
shingles.add(shingle);
}
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
};
};
}
System.out.println(shingles);
}
}
Output: [ddssgge, eezzfff, f______]
It works almost, but in the with the given parameters in the example the last shingle is not necessary (it should be [ddssgge, eezzfff]
Any idea how to do this more beautiful?
To make the code posted work you only need to add break and the end of the catch block:
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
break;
};
Having said that I wouldn't use an Exception to control the program. Exception are just that: should be used for run time errors.
Avoid StringIndexOutOfBoundsException by controlling the loop parameters:
public static void main(String[] args) {
testKShingling(3, "ddssggeezzfff");
}
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<>();
int stringLength = txt.length();
if (substringLength == 1) {
for(int index = 0; index < stringLength; index++){
String shingle = txt.substring(index, index + substringLength);
shingles.add(shingle);
};
}
else {
for(int index = 0; index < stringLength -1 ; index += substringLength - 1){
int endIndex = Math.min(index + substringLength, stringLength);
String shingle = txt.substring(index, endIndex);
if(shingle.length() < substringLength){
shingle = extend(shingle, substringLength);
}
shingles.add(shingle);
};
}
System.out.println(shingles);
}
private static String extend(String shingle, int toLength) {
String s = shingle;
for(int index = 0; index < toLength - shingle.length(); index ++){
s = s.concat("_");
}
return s;
}
An alternative implementation of testKShingling:
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
ArrayList<String> shingles = new ArrayList<>();
if (substringLength == 1) {
for(char c : txt.toCharArray()){
shingles.add(Character.toString(c));
};
}
else {
while(txt.length() > substringLength) {
String shingle = txt.substring(0, substringLength);
shingles.add(shingle);
txt = txt.substring(substringLength - 1); //remove first substringLength - 1 chars
}
if(txt.length() < substringLength){ //check the length of what's left
txt = extend(txt, substringLength);
}
shingles.add(txt); //add what's left
}
System.out.println(shingles);
}
I'm a grade 11 student and have been given the task to complete this question for homework:
Problem J3/S1: From 1987 to 2013
You might be surprised to know that 2013 is the first year since 1987
with distinct digits.
The years 2014, 2015, 2016, 2017, 2018, 2019
each have distinct digits.
2012 does not have distinct digits,
since the digit 2 is repeated.
Given a year, what is the next year with distinct digits?
Input
The input consists of one integer Y (0 ≤ Y ≤ 10000),
representing the starting year.
Output
The output will be the single integer D,
which is the next year after Y with distinct digits.
Sample Input 1
1987
Sample Output 1
2013
Sample Input 2
999
Sample Output 2
1023
I usually answer these types of questions rather quickly but I am stumped when it comes to this one. I have spent several hours and cannot figure it out. I found out How to identify if a number is distinct or not, but I can't figure out how to add on years and check again, I keep getting errors. I would really appreciate someone's help.
Please keep in mind that I am in grade 11 and this is my first year of working with Java, so please do not use advanced coding, and methods because I won't understand. If you can, please answer it in a class and not the main method.
here is what I tried:
import java.util.*;
import java.io.*;
public class Leavemealone
{
public static void main(String[] args) throws IOException
{
BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));
int ctr = 0;
String inputStr = "";
int input = 0;
int inputCheck = 0;
System.out.println("Enter somthin: ");
input = Integer.parseInt (objReader.readLine ());
while(ctr == 0)
{
inputStr += input;
Scanner sc = new Scanner(inputStr);
int n = sc.nextInt(); // get year
String s = String.valueOf(n);
int[] num = new int[4];
for (int i = 0; i < s.length(); i++)
{
int x = Integer.parseInt(s.substring(i, i + 1)); // integer at this part in the string
num[i] += x;
}
String apple = (num[0] + "" + num[1] + "" + num[2] + "" + num[3]);
if (num[0] != num[1] &&
num[1] != num[2] &&
num[2] != num[3] &&
num[0] != num[2] &&
num[0] != num[3] &&
num[1] != num[3])
{
ctr++;
//distinct
}
else
{
input++;
//not distinct
}
}
}
}
Thanks in advance!
this is the other code I found online, I just don't know how to put it in a class
import java.util.Scanner;
import java.io.*;
public class Thegoodone
{
public static void main(String[] args) throws IOException
{
BufferedReader objReader = new BufferedReader(new InputStreamReader (System.in));
int ctr = 0;
String input = "";
int inputCheck = 0;
while (ctr == 0)
{
System.out.println("Enter somthin: ");
inputCheck = Integer.parseInt (objReader.readLine ());
if (inputCheck > 0 && inputCheck < 10000)
{
input += inputCheck;
ctr += 1;
}
else
{
System.out.println("invalid input ");
}
}
Scanner sc = new Scanner(input);
int n = sc.nextInt(); // get year
n++; // start from the next year
while (!hasDistinctDidgets(n)) //if there is repeating digits
{
n++;// next year
}
System.out.println(n);// prints year
}
public static boolean hasDistinctDidgets(int n)
{
//System.out.println("a" + n);
String s = String.valueOf(n); // converts the year from int to String
int[] numbers = new int[10]; // index position represents number, element value represents occurrence of that number
for (int i = 0; i < s.length(); i++)
{
int x = Integer.parseInt(s.substring(i, i + 1)); // integer at this part in the string
numbers[x]++; //increase occurrence of this integer in the array
}
//check if any digit occurred more than once in the array
for (int i = 0; i < numbers.length; i ++)
{
if (numbers[i] > 1) //digit occurred more than once
{
return false; //not distinct
}
}
return true; // hasn't returned false yet, so the integer has distinct digits
}
}
so this is how I tried to put it in a class:
import java.util.Scanner;
import java.io.*;
public class Danny3
{
public static void main(String[] args) throws IOException
{
BufferedReader objReader = new BufferedReader(new InputStreamReader (System.in));
int ctr = 0;
String input = "";
int inputCheck = 0;
while (ctr == 0)
{
System.out.println("Enter somthin: ");
inputCheck = Integer.parseInt (objReader.readLine ());
if (inputCheck > 0 && inputCheck < 10000)
{
input += inputCheck;
ctr += 1;
}
else
{
System.out.println("invalid input ");
}
}
Scanner sc = new Scanner(input);
// System.out.println(output);
int n = sc.nextInt(); // get year
n++; // start from the next year
DistinctCheck processing = new DistinctCheck(n);
int output = processing.getSum();
System.out.println(output);
}
}
class DistinctCheck
{
//private int year = 0;
private boolean hasDistinctDidgets;
private int b = 0;
DistinctCheck(int temp)
{
hasDistinctDidgets(temp);
}
private void yearAdd(int b)
{
while(!hasDistinctDidgets(b)) //if there is repeating digits
{
b++;// next year
}
}
private boolean hasDistinctDidgets(int year)
{
String s = String.valueOf(year); // converts the year from int to String
int[] numbers = new int[10]; // index position represents number, element value represents occurrence of that number
for (int i = 0; i < s.length(); i++)
{
int x = Integer.parseInt(s.substring(i, i + 1)); // integer at this part in the string
numbers[x]++; //increase occurrence of this integer in the array
}
//check if any digit occurred more than once in the array
for (int i = 0; i < numbers.length; i ++)
{
if (numbers[i] > 1) //digit occurred more than once
{
return false; //not distinct
}
}
return true; // hasn't returned false yet, so the integer has distinct digits
}
int getSum()
{
return b;// prints year
}
}
I would start with a method to determine if a given int consists of distinct digits. You could use a Set<Character> and add each character from the String to the Set. You will get false on a duplicate. Like,
static boolean distinctDigits(int i) {
String s = String.valueOf(i);
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
if (!set.add(c)) {
return false;
}
}
return true;
}
Then your main just needs to invoke that. Like,
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int v = s.nextInt();
while (v < 10000) {
v++;
if (distinctDigits(v)) {
break;
}
}
System.out.println(v);
}
i figured it out:
import java.util.*;
public class Apple
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int num = input.nextInt();
Distinct findDistinct = new Distinct(num); // objecct
String output = findDistinct.getDistinctYear();
System.out.println(output);
}
} // end of main
class Distinct
{
private int ctr = 0;
private String yearStr = "";
private String distinctYear = "";
private int year = 0;
Distinct(int n)
{
year = n;
makeDistinct();
}
private void makeDistinct()
{
while(ctr == 0)
{
year += 1; // year will keep increasing until it is distinct
yearStr = Integer.toString(year);
if(isDistinct(yearStr) == true) // if the number is distinct
{
distinctYear = yearStr;
ctr++;
}
}
}
private boolean isDistinct(String yearStr)
{
String eachNum[] = yearStr.split(""); // breaks up each number (char) of yearStr
for(int i = 0; i < eachNum.length; i++)
{
for(int j = 0; j < i; j++)
{
if (eachNum[i].equals(eachNum[j])) // not distinct
{
return false;
}
}
}
return true; // is distinct
}
String getDistinctYear()
{
return distinctYear;
}
}
I'm trying to solve a palindrome problem that the input consists of Strings , if the concatenation of two strings represent a palindrome word(A palindrome is a word which can be read the same way in either direction. For example, the following
words are palindromes: civic, radar, rotor, and madam)
then save it into array to print it latter otherwise print "0"
but I'm having a problem in filling the null index with zeros , here I get Exception
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
"Exception in thread "main" java.lang.NullPointerException"
here is my full code
import java.util.Scanner;
public class Palindrome {
public static String reverse(String R2) {
String Reverse = "";
String word_two = R2;
int ln = word_two.length();
for (int i = ln - 1; i >= 0; i--) {
Reverse = Reverse + word_two.charAt(i);
}
return Reverse;
}
public static void main(String[] args) {
Scanner inpoot = new Scanner(System.in);
int stop = 0;
String pal1;
int Case = inpoot.nextInt();
String result[] = new String[Case];
String Final;
int NumberofWords;
for (int i = 0; i < Case; i++) {
NumberofWords = inpoot.nextInt();
String words[] = new String[NumberofWords];
for (int array = 0; array < words.length; array++) {
words[array] = inpoot.next();
}
for (int word1 = 0; word1 < NumberofWords; word1++) {
if (stop > Case) {
break;
}
for (int word2 = 0; word2 < NumberofWords; word2++) {
if (word1 == word2) {
continue;
}
Final = "" + words[word1].charAt(0);
if (words[word2].endsWith(Final)) {
pal1 = words[word1].concat(words[word2]);
} else {
continue;
}
if (pal1.equals(reverse(pal1))) {
result[i] = pal1;
stop++;
break;
} else {
pal1 = "";
}
}
}
}
// HERE IS THE PROBLEM
for (int re = 0; re < result.length; re++) {
if (result[re].equals(null)) {
result[re] = "0";
}
}
for (int x = 0; x < result.length; x++) {
System.out.println("" + result[x]);
}
}
}
A test such as anObject.equals(null) makes no sense. Indeed, if anObject is null, it will throw a NullPointerException (NPE), and if it is not, it will always return false.
To test if a reference is null, just use anObject == null.
If you want to check whether result[re] is null, you cannot use equals. Use the identity comparison:
if (result[re] == null) {
result[re] = "0";
}
This is my task, Given an input of an expression consisting of a string of letters and operators (plus sign, minus sign, and letters. IE: ‘b-d+e-f’) and a file with a set of variable/value pairs separated by commas (i.e: a=1,b=7,c=3,d=14) write a program that would output the result of the inputted expression.
For example, if the expression input was ("a + b+c -d") and the file input was ( a=1,b=7,c=3,d=14) the output would be -3.
Hi I am trying to do a simple java code which outputs a number if i add 4 letters. When I do different combinations like d-c+a+b it gives me a inccorect number like 118.0. Can someone tell me where in my code my calculations are wrong..
Thank you
the ValVarPairs.txt contains these numbers-> a=100,b=5,c=10,d=13
This is what i coded.
package com.ecsgrid;
import java.io.*;
public class testC {
public static void main(String[] args) {
int i = 0,j = 0;
double result, values[] = new double[4];
char k, operators[] = new char[3];
for (i = 0; i <= 2; i++)
operators[i] = '+'; // default is to add the values
File myfile;
StreamTokenizer tok;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String InputText;
i = 0;
try {
myfile = new File("C:\\VarValPairs.txt");
tok = new StreamTokenizer(new FileReader(myfile));
tok.eolIsSignificant(false);
while ((tok.nextToken() != StreamTokenizer.TT_EOF) && (i <= 3)){
if ((tok.ttype == StreamTokenizer.TT_NUMBER))
values[i++] = tok.nval;
}
}
catch(FileNotFoundException e) { System.err.println(e); return; }
catch(IOException f) { System.out.println(f); return; }
System.out.println("Enter letters and operators:");
try {
InputText = in.readLine();
}
catch(IOException f) { System.out.println(f); return; }
for (i = 0; i < InputText.length(); i++)
{
k = InputText.charAt(i);
if ((k == '+') || (k == '-'))
{
if (j <= 2) operators[j++] = k;
}
}
result = values[0];
for (i = 0; i <= 2; i++){
if (operators[i] == '+')
result = result + values[i+1];
else
result = result - values[i+1];
}
System.out.println(result);
}
}
I'm not sure where your calculations are wrong, but you could do something like this:
EDITED CODE:
import java.io.*;
import java.util.*;
public class test{
public static int a;
public static int b;
public static int c;
public static int d;
public static int fin = 0;
public static String temp;
public static void main(String[] args){
try{
Scanner input = new Scanner(new File("yourfile.txt"));
temp = "";
while(input.hasNext()){ //stores the letters
temp = temp + input.next();
}
input.close();
}
catch(Exception e){
}
/*
THIS IS IF THE FILE yourfile.txt IS IN THIS FORMAT EXACTLY:
a=1
b=2
c=3
d=4
*/
for(int i = 0; i < temp.length(); i++){ //intitializes the values
String message = "" + temp.charAt(i);
if(message.equals("a") || message.equals("b") || message.equals("c") || message.equals("d")){
String val = "" + temp.charAt(i+2);
setValue(message,val);
}
}
Scanner enter = new Scanner(System.in);
System.out.print("ENTER EXPRESSION: ");
String ex = enter.nextLine();
for(int b = 0; b < ex.length(); b++){
String m = ""+ ex.charAt(b);
if(b == 0){
if(m.equals("a") || m.equals("b") || m.equals("c") || m.equals("d")){
fin = fin + getValue(m);
}
}
else{
if(m.equals("a") || m.equals("b") || m.equals("c") || m.equals("d")){
String check = "" + ex.charAt(b-1);
if(check.equals("+")){
fin = fin + getValue(m);
}
if(check.equals("-")){
fin = fin - getValue(m);
}
}
}
}
System.out.println(fin);
}
public static void setValue(String variable, String value){
if(variable.equals("a")){
a = Integer.parseInt(value);
}
if(variable.equals("b")){
b = Integer.parseInt(value);
}
if(variable.equals("c")){
c = Integer.parseInt(value);
}
if(variable.equals("d")){
d = Integer.parseInt(value);
}
}
public static int ret = 0;
public static int getValue(String var){
if(var.equals("a")){
ret = a;
}
if(var.equals("b")){
ret = b;
}
if(var.equals("c")){
ret = c;
}
if(var.equals("d")){
ret = d;
}
return ret;
}
}
There are some problems in your code where you use "==" instead of .equals()
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.