Struggling with my sentinel program - java

This is my first submission, I have completed one quarter of Java programming.
I have an assignment to create a Palindrome Checker. Fairly straight forward, I had that portion of the code figured out in the first hour. However, in typical fashion (for me) I want my code to do a bit more. This is where I run into issues.
I want this code to do the following:
Take user input
Correctly identify if the input is a palindrome regardless of case or punctuation
Run in a loop so that multiple tests can be performed
So far it works, I just don't know if I went about it the right way. Would anyone be willing to take a look and let me know how inefficient this is, or if it has any obvious rookie mistakes? Thanks so much.
Code:
/**
* Created by Travis on 1/10/2015.
*/
import java.io.IOException;
import java.util.*;
import javax.swing.*;
import java.text.*;
import java.lang.StringBuilder;
public class Palindrome
{
public static void main(String[] args) throws IOException //main class
{
String str = "", answer = "", test1 = "yes", test2 = "no"; //strings
int len = 10; //initial value for len so it doesn't trip the success if
Scanner KB = new Scanner(System.in); //user input
System.out.println("Greetings, Welcome to the Palindrome Checker.\n" + //initial greeting
"Would you like to check a Palindrome? (Yes or no)");
answer = KB.nextLine(); //input is for the sentinel program.
if (!(answer.equalsIgnoreCase(test1) || answer.equalsIgnoreCase(test2))) //error message in case user inputs incorrect string.
{
System.out.println("Error! You can only choose 'yes' or 'no'. Please try again:");
answer = KB.nextLine(); //allows for new answer
}
System.out.println(answer + " y"); //debugging so i can see answer
while (answer.equalsIgnoreCase(test1)) //compares to test1 which is: yes. as long as answer equals yes, the program should loop
{
System.out.println("Please provide a word or phrase:");
str = KB.nextLine(); //prompt for palindrome
String str2 = str.toLowerCase().replaceAll("\\s+", "").replaceAll("\\W+", ""); //converts input to a string that is a single group of chars with no space or punctuation
System.out.println(str2); //debug
StringBuilder str1 = new StringBuilder(str2); //takes the string and makes a stringbuilder so i can delete chars to test
len = str1.length(); //sets for length. This lets me account for any length of phrase
System.out.println(len); //debug
System.out.println(str1); //debug
for (int i = 0; len >= 2; i++) //for loop to progressively test front and back letters and proceed if they are the same
{
char ch1 = str1.charAt(0); //takes the letter at [0] and converts to char
char ch2 = str1.charAt(len - 1); //takes the last letter and converts to char
System.out.println("The first letter in your phrase is: " + ch1); // lists the letter at [0]
System.out.println("The last letter in your phrase is: " + ch2); //lists the letter at the end
if (!(ch1 == ch2)) //if the front and back letter do not match, fails and prompts for new phrase
{
System.out.println("Sorry, this phrase is not a palindrome. \n" +
"Would you like to try again?");
answer = KB.nextLine();
break;
}
else if (ch1 == ch2) //if front and back do match, removes front and back letters and updates stringbuilder
{
System.out.println("Removing letters on each end of the phrase and performing " +
"new check:\n");
str1.deleteCharAt(len - 1); //deletes the last letter from str1
str1.deleteCharAt(0); //deletes first letter from str1
len = str1.length(); //updates len with the new length of str1
i++;
}
}
if (len <= 1) //if the for loop successfully reduces stringbuilder to 1 or less characters, prompts for success
{
System.out.println("Congratulations, your phrase: '" + str + "' is a palindrome! \n\n" +
"Would you like to try again?");
answer = KB.nextLine();
len = 10; //resets len
}
}
if (answer.equalsIgnoreCase(test2)) //ends sentinel loop.
{
System.out.println(answer + " N");
System.exit(0);
}
}
}

Related

Char count of each token in Tokenized String, Java

I'm trying to figure out if I can count the characters of each token and display that information such as:
day is tokenized and my output would be: "Day has 3 characters." and continue to do that for each token.
My last loop to print out the # of characters in each token never prints:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Example of Console:
Please type a sentence containing at least 4 words, with a maximum of 8 words:
Hello there this is a test
Thank you.
You entered:
Hello there this is a test
Each word in your sentence is: [Hello, there, this, is, a, test]
First off, I have added the necessary imports and built a class around this main method. This should compile.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SOQ_20200913_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> tokenizedInput = new ArrayList<>();
String sentenceRetrieved;
// getting the sentence from the user
System.out.println("Please type a sentence containing at least 4 words, with a maximum of 8 words: ");
sentenceRetrieved = sc.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(sentenceRetrieved);
// checking to ensure the string has 4-8 words
while (strTokenizer.hasMoreTokens()) {
if (strTokenizer.countTokens() > 8) {
System.out.println("Please re-enter a sentence with at least 4 words, and a maximum of 8");
break;
} else {
while (strTokenizer.hasMoreTokens()) {
tokenizedInput.add(strTokenizer.nextToken());
}
System.out.println("Thank you.");
break;
}
}
// printing out the sentence
System.out.println("You entered: ");
System.out.println(sentenceRetrieved);
// print out each word given
System.out.println("Each word in your sentence is: " + tokenizedInput);
// count the characters in each word
// doesn't seem to run
int totalLength = 0;
while (strTokenizer.hasMoreTokens()) {
String token;
token = sentenceRetrieved;
token = strTokenizer.nextToken();
totalLength += token.length();
System.out.println("Word: " + token + " Length:" + token.length());
}
}
}
Next, let's look at this working example. It seems like everything up until your final while loop (the one that counts character length) works just fine. But if you notice, the while loop before the final one will continue looping until it has no more tokens to fetch. So, after it has finished gathering all of the tokens and has no more tokens to gather, you try and create the final while loop, asking it to gather more tokens. It would not have reached the while loop until it ran out of tokens to gather!
Finally, in order to solve this, you can simply go through the list that you added to in the second to last while loop, and simply cycle through that for your final loop!
For example:
int totalLength = 0;
for (String each : tokenizedInput) {
totalLength += each.length();
System.out.println("Word: " + each + " Length:" + each.length());
}

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.

How to find the length of the second word in 3-word phrase without using loops or any built-in methods of java?

I want to know how you can find the length of the second word without using a for or a while loop and any built-in methods of java like substring, match, left or right...etc. This has to be done using the indexOf(); method and the char.
Sample input: The grey elephant ----> Sample output: Second letter has 4 words
I did this task using the for loop but our teacher restricted it, I want to know is that is there any way the for loop can be broken down, meaning keeping everything the same but removing the loop, and manually doing it. I don't want any other solutions, if you could just fix my code cuz the process is right and it works with the for loop. But I need it without it, I think if statements will do but idk where to put them.
Or if none work then I think it involves the overloaded version of the indexOf(); method. How would I use that?
Code:
else if (option == 2){
int first = -1;
int last = -1;
for (int x = 0; x < phrase.length() && x > phrase.indexOf(x); x++){
char n = phrase.charAt(x);
if (n == ' ' && first == -1){
first = x;
}
else if (n == ' '){
last = x;
}
}
int length = last - first - 1;
System.out.print("Second word has "+length+" letters");
}
Do it as follows:
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 index1 = phrase.indexOf(' ');
int index2 = phrase.indexOf(' ', index1 + 1);
System.out.println("Length of the second word is " + (index2 - index1 - 1));
}
}
}
A sample run:
Enter option: 2
Enter phrase: The grey elephant
Length of the second word is 4
Another sample run:
Enter option: 2
Enter phrase: Good morning world!
Length of the second word is 7
[Update]
Posting the following update based on OP's request to find the length of the first word and that 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 firstIndex = phrase.indexOf(' ');
System.out.println("Length of the first word is " + firstIndex);
System.out.println("Length of the last word is " + (phrase.length() - phrase.lastIndexOf(' ') - 1));
}
}
}
A sample run:
Enter option: 2
Enter phrase: Good morning world
Length of the first word is 4
Length of the last word is 5
Here it is how you can calculate the length of the 2nd word (assuming the separator character of the string is only one space.
String str = "The grey elephant";
int start = str.indexOf(' ');
int end = str.indexOf(' ', start+1);
int lengthSecondWord = end - start - 1;
System.out.println("2nd word length " + lengthSecondWord);

replace dashes with guessed letter in java

really beginner javascript user here, creating a hangman game. i am having the world of difficulty in trying to show a users correct guess.
from my understanding i have only masked the secret word with dashes so therefor am trying to make it become unmasked when a correct letter is guessed.
i imagine i need to use charAt somewhere, somehow but to be honest i just cant figure it out.
My code is still very basic and i havent done much else as there isnt much point writing out the rest of the game if you cant see the guess but here is the code i have so far... please remember this is still a very unfinished project.
package hangmangame;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
*
* #author Matt
*/
public class HangmanGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
char letter = 0; //declares and initailise letter
String marks = ""; //declares and initailise string for dashes
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
for (int i=1;i<=word.length(); i++) // for method for displaying the correct word as dashes
{
marks += "-"; //dashes to represent the correct word.
}
System.out.println("lets play hangman, your word is " + marks + "\n" + "enter a letter to guess the word");
Scanner input = new Scanner(System.in);
letter = input.next(".").charAt(0); //assign inputted letter to letter variable
if ((word).contains(""+letter)) //if statement to excute if guessed letter is in word
// i imagine this is where i put some sort of code to show that guessed letter?
System.out.println("You guessed a letter!" + marks); //display for correct letter
Here is some code to get you started. It's important to grab the entire line from the user instead of using next()... Unless you are an experienced coder and understand the way in which the next() iterates over the input I'd highly suggest using nextLine() as it's much easier to use.
char letter = 0; //declares and initailise letter
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
String [] marks = new String[word.length()];
for (int i=0;i<word.length(); i++) // for method for displaying the correct word as dashes
{
marks[i] = "-"; //dashes to represent the correct word.
}
HashSet<Character> lettersGuessed = new HashSet<>(); //keep track of letters guessed
Scanner input = new Scanner(System.in);
String userInput = "";
String currentWord = "";
while(true)
{
System.out.print("Word is - ");
currentWord = "";
for(int i = 0; i < marks.length; i++)
{
System.out.print(marks[i]);
}
System.out.print("\nGuess a letter - ");
userInput = input.nextLine(); //always grab lines
if(userInput.length() != 1)
{
System.out.println("Invalid guess - " + userInput);
}
else if(lettersGuessed.contains(userInput.charAt(0)))
{
System.out.println("You already guess that character - " + userInput);
}
else if(word.contains(userInput))
{
lettersGuessed.add(userInput.charAt(0));
currentWord = "";
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == userInput.charAt(0))
{
marks[i] = "" + userInput.charAt(0);
}
currentWord += marks[i];
}
}
if(currentWord.equals(word))
break;
}
System.out.println("You guessed it! The word was " + word + "!");
Output
Word is - ----
Guess a letter - l
Word is - --l-
Guess a letter - h
Word is - h-l-
Guess a letter - l
You already guess that character - l
Word is - h-l-
Guess a letter - u
Word is - hul-
Guess a letter - tg
Invalid guess - tg
Word is - hul-
Guess a letter - k
You guessed it! The word was hulk!
the String class contains an indexOf(String c) method which returns the index of the first occurrence of a substring. For example, if word was delicious then word.indexOf("i") would return 3, the first index of the substring "i".
But what about all other occurences of the substring "i"? Well, the indexOf method is handily overwritten to help with that. There is another version of it, indexOf(String ch, int fromIndex) that takes in a starting index. Continuing our earlier example, if you asked for word.indexOf("i", 4) this time you would get back 5, the first index of the substring "i" in the string "delicious" if we are discounting every index before the fourth one.
Think of it this way, indexOf is kind of the opposite of charAt. charAt takes in an index and gives you a character, indexOf takes in a character or string and gives you its first index.
I think this would all be a lot easier if you stored the word and the marks as character arrays like this:
char letter = 0; //declares and initailise letter
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
char[] chosenWord = new char[word.length()];
char[] marks = new char[word.length];
for (int i=0;i< word.length(); i++) // for method for displaying the correct word as dashes
{
chosenWord[i] = word.charAt(i);
marks[i] = '-';
}
System.out.println("lets play hangman, your word is " + new String(marks) + "\n" + "enter a letter to guess the word");
Scanner input = new Scanner(System.in);
letter = input.next(".").charAt(0); //assign inputted letter to letter variable
if ((word).contains(""+letter)){ //if statement to excute if guessed letter is in word
for(int i =0; i < chosenWord.length; i++){
if(chosenWord[i] == letter){
marks[i] = chosenWord[i]
}
}
// i imagine this is where i put some sort of code to show that guessed letter?
System.out.println("You guessed a letter!" + new String(marks));
}
I didn't syntax check this, but you should get the idea of what I'm working at.
This is what i made.
I think its much better to use arrays here.
public static void main(String[] args) {
String[] words = {"gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi", "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word[] = (words[(int) (Math.random() * words.length)]).split(""); //chooses random word from the word array and creates a array of letters
String[] marks = new String[word.length];
Arrays.fill(marks,"-"); // creates and fills an array with dashes
Scanner in = new Scanner(System.in);
String letter = "";
int counter = 0;
while(Arrays.toString(marks).contains("-")) {
counter++;
System.out.println("This is your word!: " + String.join("", marks));
System.out.print("Guess a letter ");
letter = String.valueOf(in.next(".").charAt(0));
for (int i = 0; i < word.length; i++) {
if(word[i].equals(letter)){
marks[i] = word[i];
}
}
}
System.out.println("Congratulations your word is " + String.join("",marks) + "You did it in " + counter + "trials");
}
}

Prevent the user entering numbers in java Scanner?

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

Categories