Validating User input strings - java

I want to write a loop that prompts the user to input their first middle and last name, I then want to validate that input by searching for the white spaces in between each name.
Example: First Middle Last
What I'm looking for is some thing like the following.
Pseudo Code: if name contains 2 white spaces and their are less than 3 white space in name the operation has been successful other wise tell the user to re-input their first middle and last name.
How can I go about doing this?
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isName = false;
String name = "";
int x = name.length();
Scanner input = new Scanner(System.in);
while(!isName) // Probably better to remove the while loop entirely
{
System.out.print("Please input your 'First Middle Last' name: ");
name = input.nextLine();
name.trim(); // To remove any leading or trailing white spaces
for(int i = 0; i < x; i++)
{
if(name.lastIndexOf(' ', i) == 2 && name.lastIndexOf(' ', i) < 3)
{
isName = true;
break;
}
else
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
name = name.trim();
System.out.print("\nInvalid input");
}
}
}
}
The above produces an infinite loop and logically I understand why.

You could split your String on one or more white space characters and check that you get three elements. Something like,
boolean isName = false;
String name = "";
Scanner input = new Scanner(System.in);
while (!isName) {
System.out.print("Please input your 'First Middle Last' name: ");
name = input.nextLine();
isName = (name.trim().split("\\s+").length == 3);
if (!isName) {
System.out.print("\nEnter your name as 'First Middle Last': ");
}
}

Here is the problem (infinite loop):
for(int i = 0; i < x; i++)
x is initialized to 0 because name.length() is 0 initially. Since the condition i<x is never satisfied, it never enters the for loop and the while loops goes on for ever.
Right before the for loop, you need to do x = name.length(). Also, as others have suggested you need to enclose the statements inside {} for the else part.

As per this link you can count white spaces with:
int numOfSpaces = s.length() - s.replaceAll(" ", "").length();
With this you can tell if you have at least 2 spaces. The link also goes over different methods of counting how many white spaces exist in a given String.
Cheers!

Related

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

How to find the length of the last word in java?

I want to find the length of the last word to initially find the length of the second word in the phrase. here's my plan, If I find the length of the last phrase then in the for loop if I subtract x, it should give me the length of the second word always. This has to be done using for loop and a scanner, where the user inputs any phrase.
Basically, I need to know how to find the length of the last phrase. Thats what I need to know only.
here's my code:
else if (option == 2){
int counter = 0 ;
for (int x = 0; x < phrase.length() - x; x++){
//in the "int x = 0" i need to put the length of the last word
// in a phrase
char n = phrase.charAt(x);
if (n == x);
counter++;
}
System.out.print("Second word has "+counter+" letters");
}
With only the for-loop, length of last word in the phrase:
else if (option == 2){
int lastSpaceChar = 0;
for (int x = 0; x < phrase.length(); x++){
char n = phrase.charAt(x);
if (n == ' ') { //Indicate space
lastSpaceChar = x;
}
}
//When loop is finished, it will have the index of the last space
//So if you take total length - last space, you'll get the last word
int lengthOfLastWord = phrase.length() - spaceChar;
System.out.print("Last word has " + lengthOfLastWord + " letters");
}
If you want the second word, you need to do the same, except find 1st and 2nd space, because characters between first 2 spaces form the 2nd word.
else if (option == 2){
int firstSpace = -1;
int secondSpace = -1;
for (int x = 0; x < phrase.length(); x++){
char n = phrase.charAt(x);
if (n == ' ' && firstSpace == -1) { //Space found the first time
firstSpace = x;
} else if (n == ' ') {
//FirstSpace has already been found
//So this should be second
secondSpace = x;
break; //No need to look anymore, we have both spaces
}
}
//When loop is finished, you will have first 2 spaces
//Characters between first 2 spaces is 2nd word
int lengthOfSecondWord = firstSpace - secondSpace;
System.out.print("Second word has " + lengthOfSecondWord + " letters");
}
I'm assuming you're just learning, so this will do.
Of course, you should probably do error handling and look out for edge cases in actual practice.
The length of the last word in a sentence can be obtained like this:
public int getLengthOfLastWord(String sentence) {
if (sentence == null || sentence.length() == 0) {
return 0;
}
// Split the sentence into words on space(s).
String[] words = sentence.split("\\s+");
return words[words.length - 1].length();
}
To be accurate, you'll want to do more than just check for spaces between words, because if you are only looking for spaces then it is going to treat punctuation like commas and periods as part of the lengths of words. So your best bet is something like isAlphabetic().
If your plan is to loop through characters in the string (i.e. you don't want to use string functions), one very simple way (that wouldn't require you to change your code much) is to count forward through the array. The first time you find one where:
phrase.charAt(x).isAlphabetic()
is true, you know you've reached the beginning of the first "word" in the phrase.
Then you keep looking forward and when
!phrase.charAt(x).isAlphabetic()
Then you know you've reached the space between the first word and the second word. But there might be punctuation so you keep scanning forward until you're back to isAlphabetic() being true again, at which point you've reached the beginning of the second word. You now start counting characters until you find isAlphabetic() going false again (you've reached a space or punctuation). At which point you know you've reached the end of the second word, and now you can check your character count for how long it was.
This method doesn't count numbers, punctuation, spaces, and special characters as part of a phrase. So you might need to special-case it for things like an apostrophe in a contraction like "don't", but hopefully this gives you a general idea.
There are other approaches, but this is the closest to how you have your code right now. Obviously you can use String functions and get a shorter piece of code, etc, but you asked specifically for a version that conformed to your loop method.
int word_wanted = 2; // Want length of the second word. Or set to -1 if you want the last word.
int counter = 0; // How long is the current word
int on_word = 0; // What word number are we on
boolean in_word = false; // Are we currently in a word
for (int x = 0; x < phrase.length() - x; x++){
if (phrase.charAt(x).isAlphabetic()) {
if (!in_word) {
on_word++;
counter = 0;
in_word = true;
}
counter++;
} else {
if (in_word) {
in_word = false;
if (on_word == word_wanted) break; // Stop if we found the length of the word requested.
}
}
}
// counter now contains the length of the requested word. It can be returned
// as a return value from your method, or used for other purposes.
It is not clear from your question whether you want to find the length of the last word or the length of the second word from the start or the length of the second last word in a phrase. So, I've written solutions to all of these requirements. I've put enough comment in the code so that you can understand it easily.
Length of the last word:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int i;
// Start the loop from the end in the backward direction
for (i = phrase.length() - 1; i >= 0; i--) {
if (phrase.charAt(i) == ' ') {
System.out.println("Length of the last word: " + (phrase.length() - i - 1));
break;
}
}
// If the loop terminated without finding any space, it means there is only one
// word in the phrase
if (i == -1) {
System.out.println("Length of the last word: " + phrase.length());
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the last word: 5
Another sample run:
Enter option: 2
Enter phrase: Good morning
Length of the last word: 7
Another sample run:
Enter option: 2
Enter phrase: Good
Length of the last word: 4
Length of the second word from the beginning:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index = 0, counter = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == ' ') {
if (counter == 0) {
index = i;
}
counter++;
}
// Print the length when space has been found second time, and break the loop
if (counter == 2) {
System.out.println("Length of the second word: " + (i - index - 1));
break;
}
}
// If there are only two words in the phrase, space will be found only once. In
// that case the length of the second word will be phrase.length() - index - 1
if (counter == 1) {
System.out.println("Length of the second word: " + (phrase.length() - index - 1));
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Hello world
Length of the second word: 5
Another sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the second word: 7
Length of the second last word:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 2) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
int index = 0, counter = 0;
// Start the loop from the end in the backward direction
for (int i = phrase.length() - 1; i >= 0; i--) {
if (phrase.charAt(i) == ' ') {
if (counter == 0) {
index = i;
}
counter++;
}
// Print the length when space has been found second time, and break the loop
if (counter == 2) {
System.out.println("Length of second last word: " + (index - i - 1));
break;
}
}
// If there are only two words in the phrase, space will be found only once. In
// that case the length of the second last word (which is the first word out of
// the two words) will be index (as the loop is running in the backward
// direction)
if (counter == 1) {
System.out.println("Length of second last word: " + index);
}
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of second last word: 7
Another sample run:
Enter option: 2
Enter phrase: Hello world
Length of second last word: 5

charAt(0) Not returning first number but second

Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment_4_Piglatin {
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
String vowels = "aeiou";
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
if (vowels.contains(String.valueOf(word.charAt(index)))) {
System.out.print(index);
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
}
}
}
System.out.println(firstVowel);
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:
String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
if(vowels.contains(String.valueOf(word.charAt(i)))){
System.out.println(word.charAt(i));
break;
}
}
Please note that you need to do toLowerCase on the actual word in order for contains to work.
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.
Think of this example: hello
The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.
However, if you only have one vowel, your program will "work".
What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.
The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:
System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));
This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:
firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}
Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.
So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
ArrayList<Character> vowels = new ArrayList<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
char indchar = word.charAt(index);
if (vowels.contains(word.charAt(index))) {
System.out.println(index);
firstVowel = Character.toString(word.charAt(index));
System.out.println(firstVowel);
index = word.length();
}
}
}
}
}
This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.

Basic Hangman game in Java (mostly concerns string manipulation)

I am taking an intro class to Java and we have a project that deals with a hangman game. I have most of the code worked out but there is a bug that I can't seem to resolve.
First, the program prompts the user for a letter and one space where they think the letter goes, then the program displays a word in a series of hyphens and, if the user makes a correct guess, the letter in the corresponding hyphen is replaced with said letter.
For testing purposes, the word has been defaulted to narrow.
So if I were to guess the letter r and for space, I were to guess index 2, the program would give me:
Guess a letter: r
Guess a space: 2
Guess: --r---
The problem I am having is that when I guess the index 3 for space and try to guess the next r, the program just gives me the same output as before.
We are not allowed to use arrays or string builder because we have not talked about them yet.
Here are my variables:
// default word for testing
String blank = "narrow";
// variables to manipulate the string
String start = "";
String end = "";
String word = "";
// variables for input and output
// input is used for the user's letter guess
String input;
// space is used for the user's index guess
String space = "";
// guess is used at the end to display the word to the user and set equal to word after
// it has been manipulated
String guess = "";
Here is the code where the string is being manipulated.
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input)) {
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I think it has to do with the if statement, but I have tried some other things and they have not worked. Any help would be appreciated.
Thank you.
The problem with your code is that everytime the blank.indexOf(input) returns 2 everytime (indexOf returns the first occurance of 'r' which is 2)
You can change the condition to check if the character at the space that the user guessed is the contains the letter that the user guessed.
You can do this as follows:
Maintain the pattern to be printed. Make a variable for this.
update the pattern everytime the user guesses correctly.
Note: In the below code guess is the variable I am talking about which is initially set to "------" for the word "narrow"
// check if the space has the letter you guessed
if (blank.charAt(space) == input.charAt(0)) {
// if it has just update the pattern string to also contain the new letter
guess = guess.substring(0, space) + input + guess.substring (space + 1)
You can just print or return (if it is a method) the pattern string.
I think blank.indexOf(input) returns only the first occurrence index of that input character. So you need to use this indexOf(int ch, int fromIndex).
In your case, store index of last occurrence of the input char in some int variable, then use that as fromIndex.
int lastOccurrence = 0;
for (int i = 0; i < blank.length(); i++) {
if (i == blank.indexOf(input, lastOccurrence)) {
lastOccurrence = i;
start = guess.substring(0, i);
end = guess.substring(i + 1);
word = start.concat(input).concat(end);
}
}
I would write it like this:
//set up variables
Scanner keyboard = new Scanner(System.in);
String word = "narrow";
String display = "";
for (int i = 0; i < word.length(); i++) {
display = display + "-";
}
//loop until the word is guessed
while (display.contains("-")) {
//show the user flow, take input
System.out.println("Guess: " + display);
System.out.print("Guess a letter: ");
String letter = keyboard.nextLine();
System.out.print("Guess a space: ");
String spaceStr = keyboard.nextLine();
int space = Integer.parseInt(spaceStr);
//check if the guess is right
if (letter.equals(word.charAt(space) + "")) {
//modify the string shown to the user
String temp = display.substring(space + 1);
display = display.substring(0, space);
display = display + letter + temp;
}
}
The key is to have one variable that is shown to the user and one which holds the real word. When they make a correct guess, you can modify the string which is shown to the user.
indexOf(String str) returns the index within this string of the FIRST OCCURENCE of the specified substring. More of this here
Best way I would suggest to do, is to change the output ONLY if the user got it right. Hence, for every guess I would do:
if(blank.charAt(space) == input.charAt(0))
{
start = guess.substring(0, space);
end = guess.substring(space + 1);
word = start.concat(input).concat(end);
}

java characters in a string

so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));

Categories

Resources