Palindrome checker - What am i doing wrong? - java

I am to create a program that checks for palindromes in a sentence and display the palindromes that have been found. My following code keeps giving me a "String is out of bounds" error. What am i doing wrong?
My Program:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
//Split string
spacePos = input.indexOf(" ");
String word = input.substring(0, spacePos);
//Get palindromes
System.out.println("Your Palindromes are:");
for (int counter = 0; counter < input.length(); counter++) {
//Reverse first word
wordlength = word.length();
for (int i = wordlength - 1; i >= 0; i--) {
Rinput = Rinput + word.charAt(i);
//Add word to An array of Palindromes
if (Rinput.equalsIgnoreCase(word)) {
Palin = word;
System.out.println("Palin:" + Palin);
break;
}
//Move on to the next word in the string
input = input.substring(input.indexOf(" ") + 1) + " ";
word = input.substring(0, input.indexOf(" "));
}
}
}
}

If you know functions you can use a recursive function to build the palindrome version of a string (it's a common example of how recursion works).
Here's an example:
import javax.swing.JOptionPane;
public class Palindromechkr {
public static void main(String[] args) {
//Declare Variables
String Palin, input, Rinput = "";
int wordlength, spacePos;
//Ask for sentance
input = JOptionPane.showInputDialog("enter a sentance");
String[] words = input.split(" +"); // see regular expressions to understand the "+"
for(int i = 0; i < words.length; i++) { // cycle through all the words in the array
Rinput = makePalindrome(words[i]); // build the palindrome version of the current word using the recursive function
if(Rinput.equalsIgnoreCase(words[i])) {
Palin = words[i];
System.out.println("Palin: " + Palin);
}
}
}
// this is the recursive function that build the palindrome version of its parameter "word"
public static String makePalindrome(String word) {
if(word.length() <= 1) return word; // recursion base case
char first = word.charAt(0); // get the first character
char last = word.charAt(word.length()-1); // get the last character
String middle = word.substring(1, word.length()-1); // take the "internal" part of the word
// i.e. the word without the first and last characters
String palindrome = last + makePalindrome(middle) + first; // recursive call building the palindrome
return palindrome; // return the palindrome word
}
}

You should have done is
public static void main(String[] args) {
String Palin, input, Rinput = "";
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
for (int counter = str.length()-1; counter >= 0; counter--) {
Rinput = Rinput + str.charAt(counter);
}
if (Rinput.equalsIgnoreCase(str)) {
Palin = str;
System.out.println("Palin:" + Palin);
}
Rinput="";
}
}
I don't know if you are aware but StringBuilder has a reverse method to it. Which can be used like this :
public static void main(String[] args) {
String input;
input = new Scanner(System.in).nextLine();
//Split string
for(String str : input.split(" ")){
if (new StringBuilder(str).reverse().toString().equalsIgnoreCase(str)) {
System.out.println("Palin:" + str);
}
}
}

Related

I have a problem with methods on Java could I have some advice?

I was given the task of splitting my program which outputted the longest word in a sentence into a number of methods within the same class. I keep on trying out different ways but none seem to work. Could someone help me out?
This is the program:
import java.util.Scanner;
public class Test{
public static str getUserInput(Scanner sc) {
System.out.print("Enter a string or sentence: ");
// Return the string inputted by the user
return sc.nextLine();
return str;
}
public static void getlongestWord(str) {
Scanner str2 = new Scanner(str);
//Initialise longestWord with the first word in str
String longestWord = str2.next();
//Initiaise maxlen with length of first word in str
int maxlen = longestWord.length();
while(str2.hasNext()) //This loop will keep running till words are present
{
String word = str2.next(); //Storing next word in variable
int len = word.length(); //Storing word's length
if(len>maxlen) //If this length is more than maxlen, longestWord and maxlen are changed
{
longestWord = word;
maxlen = len;
}
}
return longestWord;
return maxlen;
}
int longestWord;
int maxlen;
public static void getOutput (int longestWord) {
System.out.println("The longest word is '" + longestWord );
}
public static void getOuput2 (int maxlen){
System.out.println ("of length "+maxlen+" characters.");
}
}
I left some comments in your code:
import java.util.Scanner;
public class Test {
public static str getUserInput(Scanner sc) { // The return type should be of type String and not str.
System.out.print("Enter a string or sentence: ");
return sc.nextLine();
return str; // you can't have a return statement immediately after another return statement :)
}
public static void getlongestWord(str) { // The method parameter is not of a valid type (it is not String)
Scanner str2 = new Scanner(str);
String longestWord = str2.next();
int maxlen = longestWord.length();
while(str2.hasNext())
{
String word = str2.next();
int len = word.length();
if(len>maxlen)
{
longestWord = word;
maxlen = len;
}
}
return longestWord;
return maxlen; // you can't have a return statement immediately after another return statement :)
}
int longestWord; // Instance variables should be declared at the top of the class
int maxlen;
public static void getOutput(int longestWord) { // Methods named {getSomething()} should return that something. This method returns void.
System.out.println("The longest word is '" + longestWord);
}
public static void getOuput2(int maxlen) { // Focus on proper naming.
System.out.println("of length " + maxlen + " characters.");
}
}
I also wrote my own version of what you are trying to do:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.print("Enter a string or sentence: ");
Scanner sc = new Scanner(System.in);
processInput(sc);
}
public static void processInput(Scanner sc) {
String sentence = sc.nextLine();
String longestWord = findLongestWord(sentence);
printInfo(longestWord);
}
public static String findLongestWord(String sentence) {
String longest = "";
for (String currentWord : sentence.split(" ")) {
if (longest.length() < currentWord.length())
longest = currentWord;
}
return longest;
}
public static void printInfo(String longestWord) {
System.out.println("The longest word is '" + longestWord);
System.out.println("of length " + longestWord.length() + " characters.");
}
}
My solution is in no way a perfect solution so you could go ahead and understand the changes I made, and then implement your own changes.
Remember: every class and method should be responsible for one thing only.
A simple way to do it is to split the string on whitespace and then iterate the resulting array to find the longest word. To find the longest word, you can start with the assumption that the first word is the longest and store it in a variable (e.g. String longestWord) and whenever a word longer than this is encountered, replace the stored word with that word.
public class Main {
public static void main(String[] args) {
// Test string
String str = "Stack Overflow is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers.";
System.out.println("The longest word in the sentence: " + getLongestWord(str));
}
static String getLongestWord(String str) {
// Split the string on whitespace
String[] arr = str.split("\\s+");
// Start with the assumption that the first word is longest
String longestWord = arr[0];
int maxLen = longestWord.length();
for (String s : arr) {
if (s.length() > maxLen) {
maxLen = s.length();
longestWord = s;
}
}
return longestWord;
}
}
Output:
The longest word in the sentence: programming

Using for-loops to replace a certain character

The purpose of my code is to ask the user for a string, but the user has to use the number "2" to replace the word "to". Then, in my method useProperGrammar, the program should replace the number "2" for the word "to". The method returns the corrected sentence along with the number of errors fixed, which indicates the purpose of the variable counter. However, when I execute my code, the corrected code nor the number of grammar mistakes is displayed, what is the problem with my method? I know I can use the static method ".replace()", but I wanted to know if there were any other ways to solve this problem.
import java.util.Scanner;
public class Grammar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence (replace \"to\" for the number \"2\")");
String begin = input.nextLine();
System.out.println(useProperGrammar(begin));
}
public static String useProperGrammar(String sentence)
{
int counter = 0;
for(int i = 0; i<sentence.length(); i++)
{
String character = sentence.substring(i, i+1);
if(character.equals("2"));
{
String front = sentence.substring(0, i);
String back = sentence.substring(i+1);
sentence = front + " to " + back;
counter++;
}
}
return sentence + "\nFixed " + counter + "grammatical errors:";
}
}
you need to remove the ; after if(character.equals("2"))
import java.util.Scanner;
public class Grammar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence (replace \"to\" for the number \"2\")");
String begin = input.nextLine();
System.out.println(useProperGrammar(begin));
}
public static String useProperGrammar(String sentence)
{
int counter = 0;
for(int i = 0; i<sentence.length(); i++)
{
String character = sentence.substring(i, i+1);
if(character.equals("2"))
{
String front = sentence.substring(0, i);
String back = sentence.substring(i+1);
sentence = front + " to " + back;
counter++;
}
}
return sentence + "\nFixed " + counter + "grammatical errors:";
}
}

Java Splitting Strings and Applying A Method

I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.
I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
Check the inline comments:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
//Split your input phrase
String[] wordsArray = word.split(" ");
//For each word in the phrase call your scramble function
// and print the output plus a space
for (String s : wordsArray){
System.out.print(scramble(s) + " ");
}
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned
see String split
example
String in = "hello world";
String[] splitIn = in.split(" ");
The same way you can test for other things such as "," "." ";" ":" etc

How to determine if words in an input string start with random assigned letters in Java?

I present three random letters to the user, lets say ' J U D ' and my user has to give a word for each letter starting with the assigned random letter, for example:
"Just Use Data".
I have been unsuccessful searching for how to validate that the user's input starts with the assigned random letter.
My code
public static void generateLetters(){
Random randomLetter = new Random();
int i;
char[] letter = {'A', 'B', 'C', 'D', 'E', 'F'};
// It's A-Z, but for typing sake... you get the point
char[] letters = new char[26];
for(i = 0; i <= 3; i++){
letters[i] = letter[randomLetter.nextInt(26)];
System.out.printf(letters[i] + " ");
}
}
The above block will generate letters randomly and works fine. Below, I'll enter basically what I have for the user input.
public static String[] getWord(String[] word){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return word;
}
Simple thus far and this is my main function:
public statc void main(String[] args){
generateLetters();
getWord();
}
I need to take the string returned from getWord() and verify that each word input does begin with the randomly assigned letters. I've been unsuccessful in doing this. All of the syntax I find during my online research just gets me confused.
generateLetters() should return the generated letters.
getWord() doesn't actually do anything with the user input. Make it return a String that contains the user input.
You can use a separate method to validate the input.
Here's a fixed version of your code.
public static void main(String[] args) {
char[] letters = generateLetters();
System.out.println(letters);
String input = getWord();
System.out.println("Input is " + (isValid(letters, input) ? "valid" : "invalid"));
}
public static boolean isValid(char[] letters, String input) {
String[] words = input.split(" ");
for (int n = 0; n < words.length; n++)
if (!words[n].startsWith("" + letters[n]))
return false;
return true;
}
// Here're the fixed versions of your other two methods:
public static String getWord(){
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static char[] generateLetters(){
Random randomLetter = new Random();
char[] letter = new char[26];
char c = 'A';
for (int i = 0; i < 26; i++)
letter[i] = c++;
char[] letters = new char[26];
for(int i = 0; i < 3; i++)
letters[i] = letter[randomLetter.nextInt(26)];
return letters;
}
You can try this one.
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
wordInput.close();
return inputWord;
}
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
StringTokenizer st = new StringTokenizer(input, " ");
int counter = 0;
boolean isValid = true;
while (st.hasMoreTokens()) {
String word = st.nextToken();
if (!word.startsWith(String.valueOf(letters[counter]))) {
isValid = false;
break;
}
counter++;
}
if (isValid) {
System.out.println("valid");
} else {
System.out.println("Invalid");
}
}
This code will only work for the input you have provided, i am assuming thats what you need i.e. if the random letters are ' J U D ' only the input "Just Use Data". will qualify as correct input and not Use Just Data. I have also not checked the boundaries of input.
import java.util.Random;
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
char[] letters = generateLetters();
String input = getWord();
String[] words = input.split(" ");
if (words.length == letters.length) {
if (check(letters, words)) {
System.out.println("Yeah");
} else {
System.out.println("Oops");
}
} else {
System.out.println("INVALID");
}
}
public static Boolean check(char[] letters, String[] words) {
for (int i = 0; i < letters.length; i++) {
if (words[i].charAt(0) != letters[i]) {
return false;
}
}
return true;
}
public static String getWord() {
System.out.println("Enter a word for your letters: ");
Scanner wordInput = new Scanner(System.in);
String inputWord = wordInput.nextLine().toUpperCase();
return inputWord;
}
public static char[] generateLetters() {
Random randomLetter = new Random();
char[] letters = new char[3];//Make it varaible length
for (int i = 0; i < letters.length; i++) {
letters[i] = (char) ((int) randomLetter.nextInt(26) + 'A');
System.out.printf(letters[i] + " ");
}
return letters;
}
}
Method 2 Regex
public static Boolean check(char[] letters, String word) {
return word.matches(letters[0]+"(\\S)*( )"+letters[1]+"(\\S)*( )"+letters[2]+"(\\S)*");
}

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Categories