Passing over values from one method to another on - java

The purpose of my code is to determine if a string entered by a user is a palindrome (meaning that the spelling of the word backwards and normally is the same). I am supposed to do this using 2 methods, the first one (reverse) which reverses the word. In this method, the string of the reversed word is returned, but I need to use it on the other method (isPalindrome) to compare if both the original text and the reversed word are spelled the same. How do I use the string being returned in the reverse method on the method isPalindrome?
import java.util.Scanner;
public class Palindromes
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type in your text:");
String palindrome = input.nextLine();
reverse(palindrome);
if(isPalindrome(palindrome))
{
System.out.println("Your word is a palindrome!");
}
else
{
System.out.println("Your word isn't a palindrome!");
}
}
public static boolean isPalindrome(String text)
{
boolean value = false;
if(reverse.equals(text))
{
value = true;
}
return value;
}
public static String reverse(String text)
{
String reverse = "";
for(int i = text.length()-1; i>=0; i--)
{
reverse = reverse + text.substring(i, i+1);
}
return reverse;
}
}

In your isPalindrome() method, you just need to call:
return text.equals(reverse(text));
No need for the intermediate boolean value.
And to take it one step further, no need for the reverse logic either, since you can just use StringBuilder.reverse().

Related

Reverse and compare String

I have started to learn java and I've run into some trouble. Just wondering why my compare string function is not working and always returning true;
The purpose of the program is to take an input of a string, reverse the string and see if the string is the same as the original input (palindrome).
import java.util.Scanner;
public class palinedromeString {
private static Scanner keyboard;
public static void main(String[] args) {
System.out.println("Please enter a Palindrome");
keyboard = new Scanner(System.in);
String input = keyboard.next();
String original = input;
System.out.println("You entered: " + original);
System.out.println("Your String reversed is:" + " " + stringReverse(input));
System.out.println(checkString(input, original));
}
public static String stringReverse(String a) {
String result = "";
for(int i = a.length()-1; i>=0; i--){
result = result + a.charAt(i);
}
return result;
}
public static boolean checkString(String a, String b){
if(b.equals(a)){
return true;
}
else{
return false;
}
}
}
stringReverse returns the reversed String (it doesn't operate in place). Update input and your code should work as expected. Something like,
input = stringReverse(input);
System.out.println("Your String reversed is:" + " " + input);
Also, checkString is equivalent to
return b.equals(a);
Because you are passing input and original to the checkString() method. those two hold the same values. It's obvious you get true always.
checkString(stringReverse(input), original);
You have to use the above instead.
You have different options.
Assign the
stringReverse(input)
to a variable like
input=stringReverse(input);
before checking
Imesha Sudasingha's answer.
The thing is you are reversing the string into a different variable and it doesnot get reflected in the String you pass unless you explicitly assign it.
Here in checkString(input, original) method, both the parameter has same value, Hence it always returns true.
You have to pass original and reversed string like this:
String reversedStr = stringReverse(input);
checkString(reversedStr , original);

how to add an additional method to get word count and first word of a string

I'm still fairly new to Java and understanding the basics of everything, we just started talking about methods.
I'm having a hard time implementing this new method.. without using arrays or vectors or anything in the sort..
Any help would be greatly appreciated!
public class ClosedLab07{
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
String str = getInputString(keyboard);
int count = getWordCount(str);
System.out.println("Your string has " + (count+1) + " words in it.");
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(Scanner inScanner) {
String str = "";
while (str.equals("")){
System.out.print("Enter a string: ");
str = inScanner.nextLine();
if (str.equals("")){
System.out.println("ERROR - string must not be empty.");
System.out.println();
}
}
return str;
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
int i = 0;
int wordCount = 0;
while (i < input.length()){
char pos = input.charAt(i);
if (pos == ' '){
wordCount++;
}
i++;
}
return wordCount;
// Fill in the body
}
private static String getFirstWord(String input)
// THIS IS THE METHOD I'M WORKING ON
}
Add this line to your new method
return input.split("\\s")[0]; // split returns an array of all the words. you need just the first word

String matching program

I am trying to make a java program to reverse the given string and each time iterate, compare with the reversed string then to print pass if matched else fail.
My program is:
package sss;
import java.util.Scanner;
public class ssi {
/**
* #param args
*/
public static void main(String[] args) {
String original,reverse="";
Scanner sc=new Scanner(System.in);
int ascii11,ascii12,ascii13,ascii14;
System.out.println("enter the string to be reversed");
original=sc.next();
int length=original.length();
for(int i=length-1;i>=0;i--)
{
reverse=reverse+original.charAt(i);
}
System.out.println(reverse);
//System.out.println(original);
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}
}
// TODO Auto-generated method stub
sc.close();
}
}
here each time when the for loop iterates i am getting pass or fail for each pair of numbers but i want the o/p as to print only pass or fail ONCE.
can any one help me out please...
Example Code:
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
String original;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string to be reversed: ");
original = sc.next();
int halfLength = original.length()/2;
int lastIndex = original.length() - 1;
int i;
for(i = 0; i < halfLength; i++) {
if(original.charAt(i) != original.charAt(lastIndex - i)) {
System.out.println("Fail!");
break;
}
}
// Managed to match all characters
if(i == halfLength) {
System.out.println("Pass!");
}
sc.close();
}
}
Input/Output:
Enter the string to be reversed: banana
Fail!
Enter the string to be reversed: RADAR
Pass!
Enter the string to be reversed: asdwwdsa
Pass!
So the idea is to:
Compare the first half of the string with the second half of the string
Compare the first character with the last character
Compare the 2nd character with the 2nd last character, and so on.
If any character does not match, print Fail!
If the loop finishes, it implies that the string is a palindrome (original == reversed), print Pass!
You need to flag each comparison of the original and reversed characters with either a pass or a fail boolean value. Obviously if any of them are flagged with a fail, you can then terminate the algorithm and print fail. If the for loop continues with a pass right to the end, then print pass once outside of the for loop.
Your print statement is inside the loop , so its printing "pass" or "fail" for each loop. You should use a flag to check whether all the ascii characters are same. and then check the status of flag outside the loop.
OR
Use StringBuffer it has a built-in method to reverse string.
StringBuffer input = new StringBuffer("Your String to reverse");
String reverse = input.reverse().toString();
if(input.equals(reverse))
System.out.println("pass");
else
System.out.println("fail");
Move your if condition out of for loop.
for(int j=0;j<original.length()-1;j++)
{
ascii11=original.charAt(j);
ascii12=original.charAt(j+1);
ascii13=reverse.charAt(j);
ascii14=reverse.charAt(j+1);
}
if(Math.abs(ascii11-ascii12) == Math.abs(ascii13-ascii14))
{
System.out.println("pass");
}
else
{
System.out.println("fail");
}

Issue with Palindrome class using Stacks

I am trying to write a Palindrome class using Stacks to determine if a word entered by user is a palindrome. There seems to be an issue in my Palindrome class. Can someone please help me identify it? My program works but no matter what word I type, it returns that the word is not a palindrome.
import java.util.Stack;
public class Palindrome
{
public Palindrome()
{
Stack stack = new Stack();
String input = "";
boolean isPalindrome = false;
for(int i = 0; i < input.length(); i++)
{
stack.push(i);
}
String opposite = " ";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
if(input.equals(opposite))
isPalindrome = true;
else
isPalindrome = false;
}//end main
}//end class Palindrome
Here is my PalindromeCheck class:
import java.util.Scanner;
public class PalinDromeCheck
{
public static void main(String[] args)
{
Palindrome pal = new Palindrome();
Scanner type = new Scanner(System.in); //create scanner for user to type a word
String word = null; //initial word to check
String stop = null; //stops processing of word
do
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(pal.equals(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
System.out.println("Would you like to try another word? Type Y for 'Yes' or N for 'No'");
stop = type.nextLine(); //stops processing
}
while(stop.equalsIgnoreCase("y")); //continues to process and ignores upper or lowercase Y
}
}
You have several bugs.
First, you need to give the input to the Palindrome class.
Second, when you reverse the input using stack, you push the index on the stack, not the character.
Third, it's not a good practice to do everything une constructor. Palindrome class doesn't need to know the input as member or for initialization purpose
If you don't need to have several implementation of Palindrome, you shall use a static method.
Try this :
public class Palindrome
{
public static boolean isPalindrome(String input)
{
char[] inputArray = input.toCharArray();
bool isOk = true;
for(int i = 0; i < inputArray.length/2 && isOk; i++){
isOk &= inputArray[i] == inputArray[inputArray.length - i - 1];
}
return isOk;
} // end method
} //end class Palindrome
Then, your main function could be :
public static void main(String[] args)
{
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word)) {
System.out.println("is a palindrome");
} else {
System.out.println("is not a palindrome\n");
}
} // End of main
Is this your full Palindrome-Class? If yes, it has no input to handle!
public class Palindrome
{
public static boolean isPalindrome(String input)
{
Stack stack = new Stack();
for(int i = 0; i < input.length(); i++)
{
stack.push(input.charAt(i));
}
String opposite = "";
while(!stack.isEmpty())
{
opposite = opposite + stack.pop();
}
return input.equals(opposite);
}//end main
}//end class Palindrome
this creates a static method you can use in your code like:
System.out.println("Enter a word to determine if it is a palindrome: ");
word = type.nextLine(); //user types word
if(Palindrome.isPalindrome(word))
System.out.println("is a palindrome");
else
System.out.println("is not a palindrome\n");
Your input is empty because you set input to "" in the constructor. You would be better off using a constructor argument to contain the input and then keep track of that using a member variable.
The code you typed is probably better suited to be in a method (equals perhaps? You will have to override this). You might want to consider pushing the character from the input string onto the stack rather then 0, 1, 2, 3... n (where n = input.length() - 1).
Your current .equals(word) does not do what you think it does because you have not provided an overload.

I need to convert a void out put into a string so that i can compare the two strings

My program is supposed to generate a pattern of letters based on the input of the user. I have to use recursion to set each output to be different. I've already done this. Next i have to compare the two outputs in another method and use recursion to find the length of the longest common sub sequence between the two. The problem is i dont know how to compare them. Since they are void results i dont know how to convert them to strings.
import java.util.Scanner;
public class patternOfLetters {
private static String letter;
public static void printLetterPattern(char letter){
char [] pattern = new char[1];
int patternLength= pattern.length;
String result="";
char start=letter;
if(start=='A'){
System.out.print('A');
result+='A';
}else if(start=='B'){
printLetterPattern('A');
System.out.print('B');
printLetterPattern('A');
}
else if(start=='C'){
printLetterPattern('B');
System.out.print('C');
printLetterPattern('B');
}
else if(start=='D'){
printLetterPattern('C');
System.out.print('D');
printLetterPattern('C');
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Scanner otherIn = new Scanner(System.in);
System.out.println("Enter a character to start the pattern: ");
String input = in.nextLine();
String upper = input.toUpperCase();
char letter=upper.charAt(0);
System.out.println("");
System.out.println("Your first pattern of letters is:");
printLetterPattern(letter);
System.out.println("");
System.out.println("");
System.out.println("Enter another character to generate your second pattern: ");
String input2 = in.nextLine();
String upper2 = input2.toUpperCase();
char letter2=upper2.charAt(0);
System.out.println("");
System.out.println("Your second pattern of letters is:");
printLetterPattern(letter2);
in.close();
otherIn.close();
}
}//fin.
You cant, return type "void" means there is no result returned, so there is nothing you could convert.
Your methods just print their output to the console, you will need to rewrite them so they actually return a result.
One way could be like this (pseudocode):
public String produceLetterPattern(String pattern, char letter) {
...
if(start=='A') {
pattern+="A";
return pattern;
} else if (start=='B') {
pattern = produceLetterPattern(pattern, 'A');
pattern +="B";
pattern = produceLetterPattern(pattern, 'A');
return pattern;
} ...
}
That's the general idea, you should be able to work it out from there. Important part is that you need a result returned, in the above example a String, returned via
return pattern;

Categories