Adding all inputs into an array - java

Intended Function: User should ender 1,2 or 3. 1 should allow the user to add a number to the array, 2 should allow the user to access the number at that point in the array, 3 should exit the program.
Problem: When the user is asked for a number and chooses 'yes' to add another, only the last number entered is added to the array. All numbers inputed should be added. Why is only the last one added?
import java.util.Scanner;
public class PhoneBookV2 {
public static void main(String[] args){
String[] numbers = {};
String[] moreNumbers = new String[numbers.length + 1];
numbers = moreNumbers;
print(numbers);
task(numbers, moreNumbers);
}
public static void task(String[] numbers, String[] moreNumbers){
Scanner scan = new Scanner(System.in);
System.out.println("Please Pick A Task: \n 1:Add A Number to Speed Dial \n 2:Speed Dial A Number \n 3:Exit");
String choice = scan.nextLine();
switch(choice){
case "1":
AddNumber(numbers , moreNumbers);
break;
case "2":
CallNumber(numbers);
break;
case "3":
System.out.println("Goodbye!");
System.exit(0);
break;
}
}
private static String[] AddNumber(String[] numbers,String[] moreNumbers) {
Scanner scanner = new Scanner(System.in);
boolean cont = false;
do{
System.out.print("Please Enter The Number You Wish To Save Under Speed Dial: ");
moreNumbers[moreNumbers.length - 1] = scanner.nextLine();
System.out.print("Would you like to add another? Yes or No: ");
String answer = scanner.nextLine().toLowerCase();
if(answer.equals("yes")) continue;
else if(answer.equals("no")) {
print(numbers);
cont = true;
}
}while(!cont);
System.arraycopy(numbers, 0, moreNumbers, 0, numbers.length);
return moreNumbers;
}
public static void printPhoneBook(String[][] keys){
for(String[] row : keys){
for(String s : row){
System.out.print(s);
}
System.out.println();
}
}
public static void print(String[] numbers){
for(int i = 0; i< numbers.length; i++){
System.out.println((i+1) + ") " + numbers[i]);
}
}
}

That's because an array in Java is fixed size. Let's look at your code:
String[] numbers = {};
String[] moreNumbers = new String[numbers.length + 1];
You are creating a String array numbers of length 0 and another String array moreNumbers with the length of numbers added to 1 (e.g, length 1).
Then, you pass these arrays to the task method, where you add a number to the moreNumbers array.
moreNumbers[moreNumbers.length - 1] = scanner.nextLine();
Here, you're setting a value (scanner.nextLine()) to the index 0 of moreNumbers (since moreNumbers has length 1). When you fetch another value, it's set to the same index 0 since moreNumbers did not change its size.
You can use the add method of ArrayList, which can resize:
import java.util.ArrayList;
// ...
private static ArrayList<String> AddNumber() {
// Create a new ArrayList to store the numbers
final ArrayList<String> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean cont = false;
do {
System.out.print("Please Enter The Number You Wish To Save Under Speed Dial: ");
// Add the next number to the ArrayList
numbers.add(scanner.nextLine());
System.out.print("Would you like to add another? Yes or No: ");
String answer = scanner.nextLine().toLowerCase();
if (answer.equals("yes")) continue;
if (answer.equals("no")) {
print(numbers);
cont = true;
}
} while (!cont);
return numbers;
}

Related

How to modify my program so that the user does not need to specify the input length?

I have made a program that asks:
The length of the array:
and the elements of the Array:
And then the program will multiply the elements.
My question is, how would I prompt the user to just enter the elements of the array without asking for the length and then stop when I type -1? Would I need to use an array list? Here is my code so far.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length of the array: "); //Prompt User for length
int number = Integer.parseInt(input.next());
System.out.print("The elements of your array: "); //Prompt User for elements
int[] myArray = new int[number];
for(int i = 0; i < number; i++){
myArray[i] = Integer.parseInt(input.next());
}
System.out.printf("The multiplication is %d.", multiplication(myArray, myArray.length - 1) ); //End Statement
}
static int multiplication(int[] array, int startIndex) {
if (startIndex == 0)
return(array[startIndex]);
else
return (array[startIndex] * multiplication(array, startIndex - 1));
}
}
Any help would be appreciated.
First the code, then the explanation (appears after the code, below).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MultiplyRecurse {
private static int multiplication(int[] array, int startIndex) {
if (startIndex == 0)
return(array[startIndex]);
else
return (array[startIndex] * multiplication(array, startIndex - 1));
}
/**
* #param args
*/
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner stdin = new Scanner(System.in);
String quit = "Q";
List<Integer> list = new ArrayList<>();
String line = null;
while (!quit.equalsIgnoreCase(line)) {
try {
System.out.print("Enter a number (or 'Q' to quit): ");
line = stdin.nextLine();
if (!line.equalsIgnoreCase(quit)) {
list.add(Integer.valueOf(line));
}
}
catch (NumberFormatException xNumberFormat) {
System.out.println("Not a number. Please try again.");
}
}
int[] myArray = list.stream().mapToInt(i->i).toArray();
System.out.printf("The multiplication is %d.%n",
multiplication(myArray, myArray.length - 1));
}
}
In java int is a primitive. If you look at the code for class ArrayList you will see that it contains a member named elementData which is an array of Object. Hence you can't create an ArrayList object that contains an array of int, so you need to use Integer instead.
Note that if the user enters a number larger than MAX_VALUE, the code Integer.valueOf(line) will throw NumberFormatException.
Your multiplication() method requires a int[] argument, so you need to convert your ArrayList<Integer> to a int[]. The line of code that achieves this is taken from this stackoverflow question:
How to convert List to int[] in Java?
EDIT
Due to OP's comment
List<Integer> numbers = new ArrayList<>();
System.out.print("Enter numbers: ");
while (input.hasNextInt()) {
int number = input.nextInt();
if (number == -1) {
break;
}
numbers.add(Integer.valueOf(number));
}
int[] myArray = numbers.stream().mapToInt(i->i).toArray();
System.out.printf("The multiplication is %d.%n",
multiplication(myArray, myArray.length - 1));
Sample run:
Enter numbers: 8 4 -1 <ENTER>
The multiplication is 32.
After typing -1, hit <ENTER> (on the keyboard).
Yes we can use ArrayList and Array too.Here is an example with ArrayList.
List<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.print("The elements of your array: ");
boolean flag = true;
while (flag) {
int val = input.nextInt();
if (val > 0) {
list.add(val);
} else {
flag = false;
System.out.println(list);
}
}

Asking user to enter specific number of strings then adding each string to array?

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
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.");
}
}
}
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.

Java While loop condition isn't being exicuted

I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[0] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (input.equals("zzz")){
System.out.println("bleh");
}
counter++;
} while (!input.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
Replace
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
}
counter++;
with
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
and
while (!input.equals("zzz") && counter <= 14)
with
while (!arr[counter].equals("zzz") && counter <= 14)
Explanation: zzz is a string which you have to compare with the input string stored in arr[counter].
Also, in order to avoid NullPointerException, you should perform sort operation on the copy of the array without any null element. Given below is the complete program:
import java.util.Arrays;
import java.util.Scanner;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
do {
System.out.print("Enter item or type 'zzz' to quit: ");
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
} while (!"zzz".equals(arr[counter]) && counter <= 14);
arr = Arrays.copyOf(arr, counter);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
A sample run:
Enter item or type 'zzz' to quit: a
Enter item or type 'zzz' to quit: b
Enter item or type 'zzz' to quit: c
Enter item or type 'zzz' to quit: zzz
bleh
Array is [a, b, c]
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[counter] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")){System.out.println("bleh");}
counter++;
}while (!arr[counter].equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
You meant to compare the input String, not the Scanner object. I also removed your magic number "0" index that you had , since you already set your counter to 0.
The reason your code isn't working is that input is the scanner object, and the equals method on the scanner object doesn't refer to the data being read by it. A way of doing this so that it works would be:
import java.util.*;
public class Help {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
String inputString = null;
System.out.println("Enter item or type 'zzz' to quit");
do{
inputString = input.nextLine();
arr[counter] = inputString;
if (inputString.equals("zzz")){System.out.println("bleh");}
counter++;
}while (!inputString.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
input is a Scanner. It will never equal a String.
Try this
Scanner sc = new Scanner(System.in);
String input; // this is now a proper string to compare
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
input = sc.nextLine();
int counter = 0;
while (counter < arr.length) {
if (input.equals("zzz")) return; // check most recently entered input
arr[counter++] = input; // if not returned, store in the list and increase counter
input = sc.nextLine(); // prompt next line
}
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

How to restrict amount of characters a user can enter?

For my program below, I want it so that the user must enter a word 2 or more characters long, but I do not know how to make that restriction.
This is a palindrome program, and it is used to test whether the word is a palindrome or not. It lets me enter a word of any length but I want to restrict to 2 or more, and if they enter only a one character word, a message should display "Wrong word".
import java.util.*;
class PalindromeTesterSamJiang1 {
public static void main(String [] arg) {
int x=0;
Scanner in=new Scanner(System.in);
System.out.printf("Menu: Please select an option \n"
+ "1)Palindrome Tester\n"
+ "0)Exit program \n");
x=in.nextInt();
switch (x){
case 1:
lol test=new lol();
test.palindromeTester("");
test.displayInfo();
break;
default:
System.out.println("Goodbye");
break;
}
}
}
class lol {
String original, reverse = "";
public String palindromeTester(String reference) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word to Test: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
return original;
}
public void displayInfo() {
if (original.equals(reverse))
System.out.println("RESULT: A PALINDROME");
else
System.out.println("RESULT: NOT A PALINDROME");
String[] arguments = new String[] {"123"};
PalindromeTesterSamJiang1.main(arguments);
}
}
You can read the input in a loop,
print an error if the input is too short,
break out when you get a valid input, for example:
while (true) {
System.out.println("Enter a word to Test: ");
original = in.nextLine();
if (original.length() > 2) {
break;
}
System.out.println("Too short. Word must be at least 2 characters");
}
System.out.println("Enter a word to Test: ");
original = in.nextLine();
String[] array = original.split(" ");
if(array.length < 2)
System.out.print("Enter atleast 2 sentence");

Categories

Resources