Error in program [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
//This program determines if the input string is a palindrome
import java.util.*;//importing all the methods from java.util class
import static java.lang.System.out;
public class Pallindrome {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input= new Scanner(System.in);
String pallindrome;
out.println("Enter a string: ");
pallindrome= input.nextLine();
ArrayList<String> pall= new ArrayList<String>();
buildAL(pall, pallindrome);
display(pall);
if(isPalendrome(pall))
out.println(pallindrome + " is a pallindrome");
else
out.println(pallindrome + " is not a pallindrome");
}
static void display(ArrayList<String> arr1){ //this method is for displaying the array list
for(int i=0; i<arr1.size();i++)
out.print(arr1.get(i));
out.println();
}
static void buildAL(ArrayList<String> arr2, String word){ //this is for building the array with the entered word
for(int i=0;i<arr2.size();i++)
arr2.add(word.charAt(i)+ "");
}
static Boolean isPalendrome(ArrayList<String> arr3){ //it will test if the word is pallindrome
ArrayList<String> rarr3= new ArrayList<String>();
rarr3.addAll(arr3);
Collections.reverse(rarr3);
for(int i=0;i<rarr3.size();i++)
if(!(rarr3.get(i).equals(arr3.get(i))))
return false;
return true;
}
}
When I run this code it shows the same output. please point out the error.

It's unclear what the problem is but your for loop doesnt over the letters in word as the termination condition is based on the empty List size passed to the buildAL method. Replace
for (int i = 0; i < arr2.size(); i++)
with
for (int i = 0; i < word.length(); i++) {

Below
static void buildAL(ArrayList<String> arr2, String word){
for(int i=0;i<arr2.size();i++)
arr2.add(word.charAt(i)+ "");
}
arr2.size() is 0 as you don't have any element in the list. Either add the word to the list or do word.length() in for loop.
Also, if I have to do the same thing I would do something like -
After reading the string from the scanner, Simply do
StringBuilder sb = new StringBuilder("your String");
if ("yourString".equals(sb.reverse().toString())) {
//or you can use equalsIgnoreCase also if that fits your requirement
//its a palindrome
} //Otherwise, not.

Related

Pallindrome String is replaced by * character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Input a string which contains some palindrome substrings. Find out the position of palindrome substrings if exist and replace it by *. (For example if input string is “bob has a radar plane” then it should convert in “** has a ***** plane”.
My code is given below.
import java.util.Scanner;
public class Pallindrome_String {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String sen;
System.out.println("Enter the String: ");
sen = in.nextLine();
pallindrome(sen);
in.close();
}
public static void pallindrome(String s) {
int len = s.length();
for (int i = 0; i < len; i++) {
String res = "";
if (s.charAt(i) == ' ') {
res = s.substring(0, i);
String rev = "";
for (int j = res.length() - 1; j >= 0; j--) {
rev = rev + res.charAt(i);
}
if (rev.equals(res)) {
rev = "*";
System.out.print(rev + " ");
} else {
System.out.print(res + " ");
}
}
}
}
}
There is a simpler, more efficient way of finding palindromes in Java. I'll explain the steps to implementing it.
first, after getting your input 'sen', you can use the split method of the String class to seperate each word.
sen = in.nextLine();
String[] splitted = s.split(" "); // seperates the string when there is a whitespace and stores the resulting words in an array
After you've got the words in an array, you can check each word and see if its a palindrome. To do so, you can read the word front to back and back to front and compare the result.
If u find a palindrome, store its index (position in the 'splitted' array). After you've gone through all the words in the 'splitted' array, you can then print out the appropriate number of *'s based on the length of the word.
The split() will loose double spaces and punctuation in source string and make a lot of useless objects in memory. This is more correct solution. IMHO
public static void main(String[] args) {
String s = "Bob! Do you have a radar plane?";
StringBuilder sb = new StringBuilder(s);
Matcher m = Pattern.compile("[a-zA-Z]+").matcher(s);
while (m.find()) {
String word = m.group();
if (word.length() == 0)
continue;
String reversed = new StringBuffer(word).reverse().toString();
if (word.equalsIgnoreCase(reversed)) {
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < word.length(); i++)
replacement.append('*');
sb.replace(m.start(), m.end(), replacement.toString());
}
}
System.out.println(sb);
}

Getting array out of ArrayOutOfBound exception. I was writing code to get first letters of all words in a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
//. I was writing code to get first letters of all words in a string.
public class Firstword {
static void func(String str)
{
String k ="";
String str1=" "+str;
char[] ch= str1.toCharArray();
for(int i=0;i<ch.length-2;i++)
{
if(i != ch.length-1)
while(i<ch.length && ch[i]!=' ')
i++;
k=k+ch[i+1];
}
System.out.print(k);
System.out.print(ch.length);
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
}
Your error is here:
k=k+ch[i+1];
You are getting out of bounds.
Because of this:
while(i<ch.length && ch[i]!=' ')
i++;
Something like this will work -
static void func(String str)
{
String [] words = str.split(" ");
for(int i = 0; i < words.length ;i++){
System.out.println(words[i].charAt(0));
}
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
Output -
H
B
j

What would the java code be for sorting the characters in each word of a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I don't want a string with the words sorted alphabetically. I need the letters of each word arranged alphabetically, but the order of words to remain the same.
Eg: Input string: welcome to java, Output string: ceelmow ot aajv
Try this:
String str = "welcome to java";
String strs[] = str.split(" ");
char[] ch;
StringBuilder strBuilder = new StringBuilder(str.length());
for (int i=0; i<strs.length; i++) {
ch = strs[i].toCharArray();
Arrays.sort(ch);
strBuilder.append(ch);
if (i != strs.length - 1) {
strBuilder.append(" ");
}
}
System.out.println(strBuilder.toString());
This could be solved using 5 steps
1) Split the String to words using foo.split(" ")
2) Get all the characters in the String using char[] bar=foo.toCharArray()
3) Sort the array using Arrays.sort(bar)
4) Turn the characters in a String using new String(bar)
5) Put all the characters back to a sentence
Don't forget to mind that capitals will come before not-capitals
Let me know if it works (or not)
Happy coding :) -Charlie
import java.util.Arrays;
public class StackOverflowExample {
public static void main(String[] args) {
String s = "welcome to java";
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i != 0) {
sb.append(" ");
}
char[] wordCharArray = words[i].toCharArray();
Arrays.sort(wordCharArray);
sb.append(wordCharArray);
}
System.out.println(sb.toString());
}
}

How to reverse words in string in java without using split and stringtokenizer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to reverse words in string of java without using split method and StringTokenizer.
For example, How are you must be printed in you are How.
I tried but I failed to do it.
Any help will be appreciated.
Try below code snippet
import java.util.ArrayList;
public class ReverseString
{
public static void main(String args[])
{
String myName = "Here we go";
ArrayList al = new ArrayList();
al = recursiveReverseMethod(myName,al);
al.trimToSize();
StringBuilder sb = new StringBuilder();
for(int i = al.size()-1; i>=0;i--)
{
sb.append(al.get(i)+" ");
}
System.out.println(sb);
}
public static ArrayList recursiveReverseMethod(String myName,ArrayList al)
{
int index = myName.indexOf(" ");
al.add(myName.substring(0, index));
myName = myName.substring(index+1);
if(myName.indexOf(" ")==-1)
{
al.add(myName.substring(0));
return al;
}
return recursiveReverseMethod(myName,al);
}
}
Here is another flavor based on the old time logic of String reversal in 'C'., from this thread.,
class testers {
public static void main(String[] args) {
String testStr="LongString";
testers u= new testers();
u.reverseStr(testStr);
}
public void reverseStr(String testStr){
char[] d= testStr.toCharArray();
int i;
int length=d.length;
int last_pos;
last_pos=d.length-1;
for (i=0;i<length/2;i++){
char tmp=d[i];
d[i]=d[last_pos-i];
d[last_pos-i]=tmp;
}
System.out.println(d);
}
}
I would do this:
public static String reverseWordsWithoutSplit(String sentence){
if (sentence == null || sentence.isEmpty()) return sentence;
int nextSpaceIndex = 0;
int wordStartIndex = 0;
int length = sentence.length();
StringBuilder reversedSentence = new StringBuilder();
while (nextSpaceIndex > -1){
nextSpaceIndex = sentence.indexOf(' ', wordStartIndex);
if (nextSpaceIndex > -1) reversedSentence.insert(0, sentence.substring(wordStartIndex, nextSpaceIndex)).insert(0, ' ');
else reversedSentence.insert(0, sentence.subSequence(wordStartIndex, length));
wordStartIndex = nextSpaceIndex + 1;
}
return reversedSentence.toString();
}

ArrayList Confusion and assistance! [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
basically id like a few hints or tips on how to solve this question.. maybe a few things which i could read up on about arraylists and loop which would make it simple for me to understand!..
the question is :
Processing an ArrayList of Characters:
cList is an ArrayList of objects of type Character that has been declared and intialised. Write a loop that will count the Characters that are not spaces and print the number out to the terminal window.
and second question would be:
Looping through a String
Assuming that a variable has been declared like this:
String s;
and that a value has already been assigned to s, write a loop statement that will print the characters of s in reverse order (so if s = "HELLO", your loop should print "OLLEH").
for the first question i tried to do:
public ArrayList()
public static void main(String[] args) {
int countBlank;
char ch;
public ArrayList (int cList)
{
int cList = ;
while(cList ){
System.out.println(cList);
}
}
and second question :
i have no idea, but a read up would be great!
thank you!
You could start by reading up on ArrayList Javadoc and documentation on mindprod.
In your example you haven't declared cList as arraylist nor filled it with Character objects. Instead of a while you might look into for. To get the characters in a String, String.toCharArray() might be of use.
For your first question, you want to loop through the list and count the number of times a character isn't a space.
int counter = 0;
for (Character c : characters) {
if (c == null {
continue; // Note: You can have null values in an java.util.ArrayList
}
if (!Character.isSpaceChar(c)) {
counter++;
}
}
System.out.println(counter);
For your second question:
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
An arraylist is probably too fat for that:
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class CI {
private static final String text = "Hello";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it
.previous()) {
System.out.print(ch);
}
}
}
Answer to Question 1:
import java.util.*;
public class ProcessListOfChars{
public static int printCharsInListIgnoreSpaces(List<Character> cList){
int count =0;
for(Character character:cList){
// System.out.println("Value :"+character);
if(character!=null &&!character.toString().trim().equals("")){
++count;
}
}
return count;
}
public static void main(String... args){
List<Character> cList = new ArrayList<Character>();
cList.add('c'); //Autoboxed char to Charater Wrapper Class
cList.add(' '); //Space character
cList.add('r');
cList.add('b');
cList.add(' ');
int count = printCharsInListIgnoreSpaces(cList);
System.out.println("Count of Characers :"+count);
}
}

Categories

Resources