-1

New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?

public class Palindromes {

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();

        System.out.print("Enter the strings: ");
        StringBuilder paliString = new StringBuilder(numOfStrings);
        for(int n=0; n < paliString; n++){
            paliString[n] = scan.nextLine();
            scan.nextLine();

            String[] stringPali = new String[numOfStrings];

            StringBuilder str = paliString;
            if(isPali(userString)){
                paliString = append.userString;
            }
            System.out.println("The palindromes are: " + userString ";");
        }

    static boolean isPali(String userString) {
        int l = 0;
        int h = userString.length() - 1;

        // Lowercase string
        userString = userString.toLowerCase();

        // Compares character until they are equal
        while (l <= h) {

            char getAtl = userString.charAt(l);
            char getAth = userString.charAt(h);

            // If there is another symbol in left
            // of sentence
            if (!(getAtl >= 'a' && getAtl <= 'z'))
                l++;

            // If there is another symbol in right
            // of sentence
            else if (!(getAth >= 'a' && getAth <= 'z'))
                h--;

            // If characters are equal
            else if (getAtl == getAth) {
                l++;
                h--;
            }

            // If characters are not equal then
            // sentence is not palindrome
            else
                return false;
        }

        // Returns true if sentence is palindrome
        return true;
    }
}

SAMPLE RESULT:

Enter the number of strings: 8

Enter the strings:

Race Car

Mountain Dew

BATMAN

Taco Cat

Stressed Desserts

Is Mayonnaise an instrument

swap paws

A Toyotas a Toyota

The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
kak23
  • 1
  • 4
  • 1
    You have not told us, what actual error you are facing, however I see quite a few. a) After doing `scan.nextInt();` do a `scan.nextLine();` b) use the `numOfStrings` variable in your loop `for int x = 0; x < numOfStrings; x++) ....` c) change `StringBuilder paliString` to use a `String[]` d) Just call the `isPali` method in your loop, there is no need to store anything (this actually removed the need for `c)` – Scary Wombat Mar 05 '20 at 00:22

2 Answers2

2

As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.

This one does the trick.

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();
        scan.nextLine(); // you need this to catch the enter after the integer you entered

        System.out.print("Enter the strings: ");
        StringBuilder paliString = new StringBuilder();
        for (int n = 0; n < numOfStrings; n++) {
            String userString = scan.nextLine();
            if (isPali(userString)) {
                if (paliString.length() > 0) {
                    paliString.append("; ");
                }
                paliString.append(userString);
            }
        }
        System.out.println("The palindromes are: " + paliString);
    }

Key changes:

  • I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
  • You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
  • I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
  • Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.

Edit

Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different) I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.

Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();
        scan.nextLine(); // you need this to catch the enter after the integer you entered

        System.out.print("Enter the strings: ");
        List<String> paliStrings = new ArrayList<>();
        for (int n = 0; n < numOfStrings; n++) {
            String userString = scan.nextLine();
            if (isPali(userString)) {
                paliStrings.add(userString);
            }
        }
        System.out.println("The palindromes are: " + String.join("; ", paliStrings));
    }

And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();
        scan.nextLine(); // you need this to catch the enter after the integer you entered

        System.out.print("Enter the strings: ");
        List<String> paliStrings = new ArrayList<>();
        for (int n = 0; n < numOfStrings; n++) {
            String userString = readNextLine(scan);
            if (isPali(userString)) {
                paliStrings.add(userString);
            }
        }
        System.out.println("The palindromes are: " + String.join("; ", paliStrings));
    }

    static String readNextLine(Scanner scanner) {
        while (true) {
            String userString = scanner.nextLine();
            if (userString.matches("[A-Za-z0-9 ]+")) {
                return userString;
            } else {
                System.out.println("Error: invalid input.");
            }
        }
    }
0

I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array.

I have done the above part of your question. I hope, this will give you direction to move forward.

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        boolean valid = true;
        int numOfStrings = 0;
        do {
            valid = true;
            System.out.print("Enter the number of strings: ");
            try {
                numOfStrings = Integer.parseInt(scan.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Error: invalid input.");
                valid = false;
            }
        } while (!valid);
        String[] stringPali = new String[numOfStrings];
        String input;
        for (int i = 0; i < numOfStrings; i++) {
            do {
                valid = true;
                System.out.print("Enter a string consisting of only letters and digits: ");
                input = scan.nextLine();
                if (!input.matches("[A-Za-z0-9 ]+")) {
                    System.out.println("Error: invalid input.");
                    valid = false;
                }
            } while (!valid);
            stringPali[i] = input;
        }
    }
}

A sample run:

Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !@£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello @
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123

Feel free to comment in case of any doubt/issue.

Wish you all the best!

[Update]

Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        boolean valid = true;
        int numOfStrings = 0;
        do {
            valid = true;
            System.out.print("Enter the number of strings: ");
            try {
                numOfStrings = Integer.parseInt(scan.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Error: invalid input.");
                valid = false;
            }
        } while (!valid);

        String[] stringPali = new String[numOfStrings];
        String input;
        System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
        for (int i = 0; i < numOfStrings; i++) {
            do {
                valid = true;
                input = scan.nextLine();
                if (!input.matches("[A-Za-z0-9 ]+")) {
                    System.out.println("Error: invalid input.");
                    valid = false;
                }
            } while (!valid);
            stringPali[i] = input;
        }
    }
}

A sample run:

Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits: 
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash

Feel free to comment in case of any doubt.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Hi Arvind, is there any way the user could enter whatever number of strings (given by user as you did) without it asking every time they enter one string "Enter a string consisting..". Just asking once "Enter the strings: " and having the user type out the strings one by one (knowing to move to the next string when the user presses Enter)? – kak23 Mar 05 '20 at 00:41
  • @kak23 - I hope the solution worked for you. Do not forget to accept the answer so that future visitors can also use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash May 22 '20 at 11:04