If statement Validation - java

trying to write a simple Java program that accepts a string and validates against two criteria.
If the word is shorter than 4 letter it asks the user to re enter a word till it is four letters..
Once that criteria is true it evaluates it against the letters. If the first letter of the four letter word is a D then it prints a silly message "The D was found" if not "No D found"
So far what i have working is validation for the four letters. It checks that it is four letters and if its not it keeps asking till it gets a four letter word.
After that when i enter the four letter word i cant get it to validate on the next if which checks if it is greater than 4 letters and then checks if it starts with a D or not.
import java.util.Scanner;
public class POD1
{
private static Scanner scan = new Scanner(System.in);
private static String word;
public static void main(String [] args)
{
System.out.println("Please enter a 4 Letter word");
word = scan.next();
if(word.length() <4)
{
System.out.println("Word is to short ");
System.out.println("Plese re-enter");
word = scan.next();
}
if(word.length() > 4)
{
if(word.charAt(1) == 'd')
{
System.out.println("Big d");
} else
if( word.charAt(1) !='d')
{
System.out.println("No big d");
}
}
}
}
UPDATE
The code now does go past 4 letter words but even if the word starts with a d it prints out no big d even though it starts with a d

You should be having the following to include 4 lettered words as well
if(word.length() >= 4)
You are scanning and taking the input until word.length() <4. So the loop breaks when the length is 4.
So, it doesn't enter the next if statement.
A better implementation would be to use the else clause
if(word.length() <4) {
System.out.println("Word is to short ");
System.out.println("Plese re-enter");
word = scan.next();
} else {
if(word.charAt(0) == 'D')
{
System.out.println("Big D");
} else
if( word.charAt(0) !='D')
{
System.out.println("No big D");
}
}
}
Also, you should be checking for 'D' and not 'd', if you are looking for "Big D".
Also, the index of the first character in a String is 0. So, you should be using word.charAt(0) == 'D', and not index 1 as you are using in your code right now. Index 1 will return the second character.

You check wether the word is shorter than 4 letters AND wether the word is longer than 4 letters.
There is absolutely nothing in your code that includes 4 letter words.
if(word.length() >= 4)
should be used.

Related

How would I put limits to the char's length?

Here is the question: Write a Java program that asks the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an appropriate, descriptive error message.
I have made a switch statement that successfully tells if you have a vowel or a consonant but I can't figure out how to give an error message if the length of what the user types in is more than one character.
import java.util.Scanner;
public class VowelKL{
public static void main(String[] args){
int i=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter a single letter from the alphabet: ");
char letter=input.next().charAt(0);
switch(letter)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : i++;
}
if(i==1)
System.out.println("You entered the letter " + letter + " and it is a Vowel!");
else
if((letter>='a' && letter<='z')||(letter>='A' && letter<='Z'))
System.out.println("You entered the letter " + letter + " and it is a Consonant!");
else
System.out.println("You did not enter a single character from the alphabet, please try again.");
}
}
You could use something like this
public int length() {
return i.length;
}
There are a few ways of doing this and the above is only an example but the .length() property will get you an int value of the length of the string. In the above case we are then returning the int as a value.
In your case you could make a new int variable and then assign it with the length.
int x = letter.length()
This will get the length of the string to an int value. You can then take that and write an if statement for when it is above or below the value of 1.
EDIT:
I quickly wrote this in java and it seems to work as intended. Hope that helps point you in the correct direction. Note that you would need to change your variable letter from a char to a String
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
System.out.println("Enter a single letter from the alphabet: ");
String letter= input.nextLine();
if (letter.length() == 1)
System.out.println("Only one letter was entered");
else
System.out.println("Either no letter or more than one letter was entered");
}
As you are already specifying in the user input command that user input is allowed only at index 0 i.e. charAt(0). So there is no other way to extract the index position of that character value. Unless you have to cast that particular character in the string type and then you can access String's
str.lastIndexOf(char) method to provide the restriction .
which is not the best practice to do.

Question regarding a while loop and how to re ask a y/n question

I am creating code that translated a word (obtained by the user) into Pig Latin. My code is working really good, except for one thing. I want the user to type in "y" or "n" to determine if the code will be run or not. I am using a while loop to determine what to execute. If a user types anything but the two listed above, I want it to ask again. At the moment I have a placeholder that calls the user silly and to restart the code. How can I accomplish this? Thanks a ton everyone!
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String playGame;
String word;
// Explains what the program does \\
System.out.println("Welcome to Coulter's Pig Latin Translator!");
System.out.println("If you choose to play, you will be asked to type a word which will be translated.");
System.out.println();
// Asks the user if they would like to play and checks 'y' or 'n' using a while statement \\
System.out.println("Would you like to play? [y/n]: ");
playGame = stdIn.next();
while(playGame.equals("y") || playGame.equals("n")) // While expression that will check if the user enters a 'y' or 'n'
{
if (playGame.equals("y")) // Executes if the user entered 'y'
{
System.out.println("Please enter the word that you would like to translate: ");
word = stdIn.next(); // Receives the word the user wishes to translate
System.out.println("_______________________________________________________");
System.out.println();
System.out.println("You entered the word: " + word); // Displays what the user entered
System.out.println();
System.out.println("Translation: " + solve(word)); // Displays the solved word
System.out.println();
System.out.println("Thanks for playing!"); //
return; // Ends the code
}
else if(playGame.contentEquals("n")) // Executes if the user entered 'n'
{
System.out.println("That's okay! Come back when you want to.");
return; // Ends the code
}
}
System.out.println("_______________________________________________________");
System.out.println("Don't be silly. Restart and type either 'y' or 'n'"); // Tells the user to restart if they entered anything but 'y' or 'n'
}
// Word translator code using a new static\\
public static String solve (String word)
{
String temp = word.toLowerCase();
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // Stores vowels in an array
char first = temp.charAt(0); // Defines first character for later use
for (int i = 0; i < vowels.length; i++) // Looks for first vowel to replace it
{
if (first == vowels[i])
{
return word + "way"; // Replaces checked vowel
}
}
word = word.substring(1); // Returns the string to the end of the word
word += first + "ay";
return word; // Returns the translated word to the program above
}
}
Well, you are asking for the input here:
playGame = stdIn.next();
That simply has to go into your loop then:
playOn = true;
while(playOn) {
playGame = stdIn.next();
if ( y ) { ... play
} else {
if ( n ) { ... dont play, set playOn = false
} else {
... ask again
}
}
The above is just meant as inspiration, and to point: what really matters here is that you get your if/else chain, and the corresponding "blocks" right. You need another if/else completely within the first "else" block!
Since the part of your code that you want to be repeated is only the initial question, that is all that should be in the loop:
boolean askAgain = true;
while(askAgain) {
// print your prompt;
playGame = stdIn.next();
if (playGame.equals("y") || playGame.equals("n")) {
askAgain = false;
}
}
// Now do your if/elseif for which letter was retrieved.
It's good practice to only loop over parts of your code that may actually be repeated.
You'll want to have your playGame = stdIn.next(); line and prompt to run at the start of the while loop instead of just before it. Then you can check if it is y, n or something else just after that.

How do you, using a set of random given letters, check if a word is created with only those given letters

In Java, I am supposed to make a word game where one is supposed to make letters with a given set of random letters. I have already wrote the code to find the letters (Variable is String Letters ), but I am having trouble checking if the word chosen by the player (String word), is actually created using the given letters? I have a txt file of all the English words in the English language, and this is what I am basing it off if it is a word. How do I do this? I am pretty sure it has something to do with checking the index, or using the built in command contains at.
I have already tried to search for this. However other questions used C-Language or Python. I have found 1 Java explanation, however I am new to coding and do not understand the code and variables they used.
This is an example of where I need help
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
Full method.
public static void getWord(String letters) {
int trys = 0;
int trysLeft = 5;
System.out.println("Input a word that you can make with those letters");
while (trys < 5) {
String word = getString(); //getString is a method where user can input a desired string
if (Words.contains(letters) == true) {
System.out.println("That is a word");
for (int i = 0; i < word.length(); i++) {
int index = letters.indexOf(word.charAt(i));
}
}
else if (Words.contains(word) == false) {
System.out.println("That is not a real word! Please enter a word that you can make with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
else if (Words.contains(letters) == false) {
System.out.println("You can not make a word with these letters.");
trys++;
trysLeft=trysLeft-trys;
System.out.println("You have " + trysLeft + " trys Left. Keep at it!");
}
}
}
You need to check the cointains for each letter. If you send a charSeq, example { 'a' , 'b', 'd' }, java will try to find if your string contains completely "abd"
One way to do it is to sort the letters in your letter list and your word and see if your word is contains in the available letters, like this:
public static void main(String args[]) {
String letters = sort("haat");
System.out.println("Is a word: " + letters.contains(sort("hat")));
}
public static String sort(String s)
{
char[] chars = s.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
There are many techniques that you could use to implement this class project.
Here is one:
Build a Map from the input letters. The key of the map should be a Character and the Value of the map should be the count of letters.
Build a Map from the word guess. Again, the key of the map should be a Character and the Value of the map should be the count of letters.
Compare the maps. If they are equal, then the word is constructed from exactly the letters in the input letters string.

(JAVA) The following code cannot debug: what errors were done and how to fix these errors?

I have a problem with the following code. The scenario is as such: the user inputs a string (can be a sentence). The code will, for each words, print the complete word + "ay" at the end if it starts with a vowel, and puts the first letter of the word at the end of the word (and then adds "ay" at the end). If it is not a letter that starts the word, then just print it. However, it is supposed to ask if the user wants to continue, by inputing "Yes" or "No", with the correct capitalization.
I try to debug it, and does not work as intended. You will see that everything within the while (scanWord.hasNext()) works (and everything before). However, after that loop, the rest gets ignored by the executer (will be commented as such). Can you help me get an answer, explain the mistake, and therefore make others and myself better java developers?
//import Scanner
import java.util.Scanner;
public class Prog508a {
public static void main(String [] args) {
//Declare variables
String word;
String response;
boolean answer = true;
//Declare Scanner objects
Scanner scanWord = new Scanner(System.in);
Scanner answerQuestion = new Scanner(System.in);
//while user still wants to continue
while (answer == true) {
//ask user for input
System.out.print("Enter a sentence: ");
//while the input still contains words
while (scanWord.hasNext()) {
//input from user is word
word = scanWord.next();
//if the character is letter at 0
if (Character.isLetter(word.charAt(0))) {
//and if the character is not a vowel at index 0
if (!(word.charAt(0) == 'a')
&& !(word.charAt(0) == 'e')
&& !(word.charAt(0) == 'i')
&& !(word.charAt(0) == 'o')
&& !(word.charAt(0) == 'u')) {
//the output is added the substring of word from the second letter and added first letter at the end
word = word.substring(1,word.length())+ word.charAt(0);
}
//word is added "ay"
word+= "ay";
}
//print the word result
System.out.print(word + " ");
}
//EVERYTHING UNDER HERE DOES NOT EXECUTE
System.out.println("\n");
System.out.print("Do you wish to convert another sentence (Yes or No): ");
response = answerQuestion.next();
while (!(response.compareTo("No") == 1) || !(response.compareTo("Yes") == 1)) {
//if the answer is no or yes (no capitalization)
if (response.compareTo("no") == 1 || response.compareTo("yes") == 1) {
while (response.compareTo("no") == 1 || response.compareTo("yes") == 1) {
System.out.println("Capitalization is important! Input correctly: ");
response = answerQuestion.next();
}
} else if (!(response.compareTo("No") == 1) || !(response.compareTo("No") == 1)) {
while (!(response.compareTo("No") == 1)
|| !(response.compareTo("Yes") == 1)
|| !(response.compareTo("no") == 1)
|| !(response.compareTo("yes") == 1)) {
System.out.println("You must input either yes or no! Input correctly: ");
response = answerQuestion.next();
}
}
}
if (response.compareTo("No") == 1)
answer = false;
if (response.compareTo("Yes") == 1)
answer = true;
}
//close the scanners
answerQuestion.close();
scanWord.close();
}
}
You need the correction at two places:
First, you need to change while (scanWord.hasNext()) { to if (scanWord.hasNext()) { as you would want the control to print the Yes/No question once the sentence is parsed.
Second, you need to correct the string comparison, you need to change response.compareTo("no") == 1 to response.equals("No"), or even better , with response.equalsIgnoreCase("No") for case insensitive comparison.
//EVERYTHING UNDER HERE DOES NOT EXECUTE
You have an infinite while loop.
//while the input still contains words
while (scanWord.hasNext()) {
So, you need to break out of that somehow. For example, don't use the while loop, input a whole sentence at once.
//ask user for input
System.out.print("Enter a sentence: ");
String sentence = scanWord.nextLine();
for (String word : sentence.split("\\s+")) {
// sentence is split on spaces
}
Just be careful using next() and nextLine() together.
The implementation of compareTo returns 0 when objects are equal, and 1 when one object is greater than the other.
Either use == 0 or just use if (response.equals("Yes")) { }.
Why is capitalization important, though? If you don't even care about case, use
if (response.equalsIgnoreCase("yes")) { }
Also, do not close the scanners within the loop. And you only need one.
If you close one scanner, it closes the backing stream, so you actually are closing both.

Input/comparing strings, Returning number, Java

Recently, I've been trying to build a program that does 4 things:
1) Enter a word from the keyboard.
2) Check the context of this word with the context of a string that contains the letters of the alphabet.
3) Compare the letters of the given word with the letters of the alphabet string and whenever there is match, it will return the position of that letter in the alphabet string +1. (ex. word='a' position=1 since 'a' is the first letter)
4) Get the total of all of these positions.(ex. word='abc' total=6)
Now let me show you what I've written in terms of code.
//Part 1 Entering word from keyboard
package IntroductionJava;
import java.util.Scanner;
public class Numerology
{
public static void main(String[] args)
{
int m=0,n=0,sum=0;
int j,k;
Scanner user_input=new Scanner(System.in);
String word;
System.out.print("Give a word: ");
word=user_input.next();
String word1 = "\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03bf\u03c0\u03c1\u03c3\u03c2\u03c4\u03c5\u03c6\u03c7\u03c8\u03c9";
//Part 2 check word
for(int i=0; i<word.length(); i++)
{
if(word.charAt(i)>=word1.charAt(0) && word.charAt(i)<=word1.charAt(word1.length()-1))
{
System.out.println("Your word '"+word+"' is valid.");
break;
}
else
{
System.out.println("Your word '"+word+"' is invalid.");
}
break;
//show System.out.print(word.charAt(i));
}
//Part 3 Compare letters
for(j=0; j<word.length(); j++)
{
for(k=0; k<word1.length(); k++)
{
if(word.charAt(j)==word1.charAt(k))//???
{
m=k+1;
}
}
}
}
Now, Part 1 and 2 are working fine.
My problem lies when I try to compare the letters of the word that I'm entering with the String of letters in unicode format(the letters in unicode format are from the Greek alphabet). I've tried many variations, I've also consulted some of the articles here but I couldn't find a solution.
To make things a bit more clear let's say that I'm entering the word: "hello". I want to check whether 'h' is inside the alphabet string, and if it is I want to get it's position as an integer which in our case it's the number '8' (position in the string +1) and so on.
And the last part of my program is to get all those numbers from the given word and get it's total ('hello'=8+5+12+12+20=57).
Thank you very much in advance.
How about this:
String alphabet = "abcdefgh";
String input = "abc";
int value = input.chars()
.map(alphabet::indexOf)
.map(i -> i + 1)
.sum()
System.out.println(value);

Categories