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");
}
Related
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().
Question: Repeated Sequence Check
The program should enter a string (possibly containing blanks), and determine whether the characters are in
lexicographic order.
For example:
“12AABab” is in order since each character is less than or equal to the one following it (‘1’ < ‘2’, ‘2’ <
‘A’, ‘B’ < ‘a’, etc.) according to the Unicode character sequence.
“abCDef” is out of order, because ‘b’ > ‘C’ (lower-case letters come after upper-case letters in the
Unicode sequence).
If the string is in order, the program should display “The input is in order”; otherwise, it should display
“The input is out of order”
The program should repeat this process until the user enters the string “quit”, regardless of case. It should
not check the sequence of “quit”.
Finally, the program should display “Goodbye”.
Notes:
This program will require nested loops. The inner loop will check the sequence of the input, while
the outer loop will repeat the input and check process.
Be sure to reinitialize all variables at the start of the outer loop.
A string of length 0 or 1 is considered to be in order by definition.
what I could do best is: (I tried with 2 other different methods I could send it too if you like)
package homelab03;
import java.util.Scanner;
public class Quest3deneme3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String whole,remain,d,e;
char h1,h2;
int lenght,b,c,sayac;
//int[] a;
String[] a;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
whole=whole.replaceAll("\\s+","");
lenght=(int)whole.length();
//System.out.println(+lenght);
remain=whole;
sayac=0;
c=0;
b=0;
a= new String[lenght];
//boolean cem = d.compareTo(e);
while(b<lenght)
{
a[b]=remain.substring(b,b+1);
remain=remain.substring(b+1);
System.out.println(a[b]);
d=a[b];
e=a[c];
while(a[b]<a[c] )
{
sayac=sayac+1;
h1=h2;
}
}
if(sayac==lenght)
{
System.out.println("oley");
}
else
{
System.out.println("nooo");
}
}
//a[b]=remain.substring(b,b+1);
//remain=whole.substring(b+1);
//System.out.println(a[b]);
}
note we haven't learned a[b] <= this thing yet but I find it online if the solution won't require that that would be better.
note 2: we haven't learned regex either I think that might be dissalowed (I found some answers with that online but I think I won't get credit for that)
You could check this code. Maybe it will inspire you :)
import java.util.Scanner;
public class howToDoRepeatedSequanceCheck {
public void repeatedTests() {
String whole;
int inputLength,i;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
while(!whole.equals("quit")) {
whole=whole.replaceAll("\\s+","");
inputLength = whole.length();
boolean isInOrder = true;
i = 0;
while(isInOrder && i<inputLength-1 ) {
if(whole.charAt(i)<whole.charAt(i+1)) {
// System.out.println("ok " + whole.charAt(i)+ " < " +whole.charAt(i+1));
}else {
// System.out.println("error");
isInOrder = false;
}
i++;
}
if(isInOrder == true) {
System.out.println("The input is in order");
}else {
System.out.println("The input is out of order");
}
System.out.println();
System.out.println("Enter an input string:");
whole = keyboard.nextLine();
}
System.out.println("Goodbye");
}
}
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
I tried this code but this is not working for all strings.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++)
{
if(str.charAt(i) == subStr.charAt(0))
{
for(int j=0 ; j<subStr.length();j++)
{
if( subStr.charAt(j) ==str.charAt(i+j))
count++;
else
{
count=0;
break;
}
}
}
}
if(count == subStr.length())
System.out.println("Sub String Matched !!");
else
System.out.println("String does not match !!");
}
}
What's wrong with this code ?
How to search a sub string in string
You don't need to loop over whole String. You can use string.indexOf(subString) to find the index of the substring in the string and it will return the index of the first occurrence of the substring. If you only want to ckeck whether String contains substring or not you can use string.contains(subString).
Try to decipher to the logic behind the code, so in plain english your code does the following:
LOGIC:
1)Enter a String via the Scanner and store it as str, do the same for the substring and store it as subStr.
2)Cycle through the each character of str via the for loop.
If the first character of the subStr is equal to any character with in str, then cycle through the characters of subStr. If the characters beyond this index are equal then increment the count variable each time the letters in each String are equal at the following indexes.
Else print String does not match.
3) If the number of similar characters in both Strings (denoted by the count variable) is equal to the length of the subString, then the subString is matched. Else no match.
ANSWER
So what went wrong?
I hope you notice on 2), The first bullet point you are only checking whether or not the first character of str is equal to the first character of subStr, if they are not equal you are then concluding that their is no match, which is false.
Consider the example:
str = "baloon"
subStr = "loon"
Your output would be: "String not matched"
This is because according to your code if 'b' != 'l' then theirs no match, which is false. That in essence is why your code does not work.
You could've just done the following:
if(str.contains(subStr)){
System.out.println("Sub-string matched");
}
Your code will only work if the substring is the end of the original string. This is because your code does not check that the entire substring was matched until it exits the first for loop. I moved the if (count == subStr.length() ) statement inside your first for loop and added a break if it finds the substring.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++) {
if(str.charAt(i) == subStr.charAt(0)) {
for(int j=0 ; j<subStr.length();j++) {
if( subStr.charAt(j) ==str.charAt(i+j)) {
count++;
} else {
count=0;
break;
}
}
if(count == subStr.length()) {
System.out.println("Sub String Matched !!");
//int index = i;
break;
}
}
}
if(count == 0){
System.out.println("String does not match !!");
}
}
}
Note: If you then want the index at which the substring (first) occurred, you can set int index = i; before breaking the loop as shown in the commented line above.
Another note: don't tend to omit the {}s in if and else statements. While, technically, you don't need them for single statements, it can cause bugs if you need to edit code later...
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.