Prevent the user entering numbers in java Scanner? - java

I am having some trouble preventing the user from entering numbers with the scanner class. This is what I have:
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word;
String inverse = "";
System.out.println("Write a sentence or word: ");
while (!input.hasNext("[A-Za-z]+")) {
System.out.println("Not valid! Try again: ");
input.nextLine();
}
word = input.nextLine();
word = word.replaceAll("\\s+","");
word = word.toLowerCase();
int length = word.length();
length = length - 1;
for (int i = length; i >= 0; i--) {
inverse = inverse + word.charAt(i);
}
if (word.equals(inverse)) {
System.out.println("Is a palindrome.");
} else {
System.out.println("Is not a palindrome.");
}
}
}
Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. Here is an example of output:
Write a sentence or word:
--> 11
Not valid! Try again:
--> 1 test
Not valid! Try again:
--> test 1
Is not a palindrome.
As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string. However I cannot have any arguments if I do that. Help much appreciated!

Change your regex from: [A-Za-z]+ to ^[A-Za-z]+$ in order to prevent numbers anywhere in the input-string

Related

How do I print a letter based on the index of the string?

I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.

Reverse sentence duplicate removal

I need to remove "the enter a sentence to be reversed" bit at the top and the bottom, because it shouldn't be there. Below is my code and the console message that needs to be fixed.
import java.util.Scanner;
public class ques1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sentence;
do {
String newsent = "";
System.out.println("\nEnter a sentence to be reversed: ");
sentence = scanner.nextLine();
for (int i = sentence.length() - 1; i >= 0; i--) {
newsent = newsent + sentence.charAt(i);
}
System.out.print(newsent);
} while (!sentence.equals("exit"));
}
}
Enter a sentence to be reversed: (want to remove this)
Enter a sentence to be reversed:
Hi how are you?
?uoy era woh iH
Enter a sentence to be reversed:
I am doing great, thanks.
.sknaht ,taerg gniod ma I
Enter a sentence to be reversed:
Exit
tix
Enter a sentence to be reversed: (Want to remove this)
Your input is wrong and it doesn't match with the string check "exit". The loop will continue till you feed the input as "exit".

replaceAll and loops?

My Computer Science class assignment requires that I write a program which determines if a word or phrase is a palindrome (is the same forward and backwards, ie "noon"). As part of this, I have to write a method which removes all punctuation and spaces, so they are not counted in determining if it is a palindrome. It also runs on a loop, allowing the user to input as many phrases they want until they indicate they're done. My problem is that when the word/phrase entered contains a space, somehow it terminates the loop and doesn't allow more input. The program works just fine, as long as the input has no spaces. Here's my code:
In class RecursivePalindrome:
public String removePunctuation(String s){
s = s.replaceAll("\\.","");
s = s.replaceAll("!","");
s = s.replaceAll(",","");
s = s.replaceAll(" ","");
s = s.replaceAll("'","");
s = s.replaceAll("-","");
s = s.replaceAll("\\?","");
return s;
}
public boolean isPalindrome(String s) {
s = removePunctuation(s);
String firstChar = s.substring(0,1);
String lastChar = s.substring(s.length()-1);
if (s.length() == 1){
return true;
}
if (s.length() == 2 && firstChar.equalsIgnoreCase(lastChar)){
return true;
}
if (!firstChar.equalsIgnoreCase(lastChar)){
return false;
}
return isPalindrome(s.substring(1, s.length() - 1));
}
In class RecursivePalindromeTester:
public static void main(String[]args){
//Create objects
Scanner in = new Scanner(System.in);
RecursivePalindrome palindrome = new RecursivePalindrome();
//Output
for (String again = "Y"; again.equalsIgnoreCase("Y"); again = in.next())
{
//Prompt for input
System.out.println();
System.out.print("Enter a word or phrase: ");
String phrase = in.next();
//Output
if (palindrome.isPalindrome(phrase)){
System.out.println("This is a palindrome.");
}
else
System.out.println("This is not a palindrome.");
System.out.print("Another word or phrase? (Y/N): ");
}
}
The output should be:
"Enter word or phrase: <input>mom- mom!
This is a palindrome
Another word or phrase? (Y/N): <input>Y
Enter a word or phrase: <input>Dog?
This is not a palindrome
Another word or phrase? (Y/N): <input>N"
Terminate
But instead I get:
"Enter word or phrase: <input>mom- mom!
This is a palindrome
Another word or phrase? (Y/N):"
Terminate
I really have no idea why a space would cause the loop to terminate, especially since it doesn't do this with any other punctuation.
Totally agreed with #Ilya Bursov comment,
You should use in.nextLine() instead of in.next() , there are big difference between both methods
next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line
Try like this ,
class RecursivePalindromeTester {
public static void main(String[] args) {
//Create objects
Scanner in = new Scanner(System.in);
RecursivePalindrome palindrome = new RecursivePalindrome();
//Output
for (String again = "Y"; again.equalsIgnoreCase("Y"); again = in.nextLine()) {
//Prompt for input
System.out.println();
System.out.print("Enter a word or phrase: ");
String phrase = in.nextLine();
//Output
if (palindrome.isPalindrome(phrase)) {
System.out.println("This is a palindrome.");
}
else
System.out.println("This is not a palindrome.");
System.out.print("Another word or phrase? (Y/N): ");
}
}
}

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

Palindrome checker - spacing

I have a program where I am typing a Java program to check if the String entered is a palindrome. I have 2 problems going on that I can not for the life of me seem to figure out.
I have typed out the code so that it will tell me if it is a palindrome when all lowercase letters and no spaces involved. Any time I enter a palindrome with a space anywhere in it, it will tell me it is not a palindrome. Think I am just missing one little piece of code to make it work.
import java.util.Scanner;
public class HW3 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String word;
String backwards = "";
System.out.println("Enter a word or phrase and I'll tell you if it's a palindrome");
word = keyboard.nextLine();
int length = word.length();
for (int i = length - 1; i >= 0; i--) {
backwards = backwards + word.charAt(i);
}
if (word.equalsIgnoreCase(backwards)) {
System.out.println(word + " is a palindrome!");
}
else {
System.out.println("That is not a palindrome!");
System.exit(0);
}
System.out.println("Done!");
}
}
You seem to want to remove spaces from your strong. To do so, use the replace() method:
word.replace(" ", "");
Try removing all spaces before performing the palindrome check.
word = word.replaceAll("\\s","");
Your program works as expected. (At least how I expect it to work; "taco cat" does not equal "tac ocat" so it should not be regarded as a palintrome.)
If you want to disregard from spaces, you could do
word = word.replaceAll("\\s", "");
right after reading the input string.

Categories