Need help ending a program with a do while loop - java

I am creating a wordle project, where the word is set to "tyler". The user's guess is saved as a string, as is the wordle word, "tyler". Both the strings are saved as characters in an array, then the program checks whether each character in the arrays match.
My code is here:
// Nelson's work
import java.util.Scanner;
class FinalProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Nelson's work
int counter = 0;
do {
String word = "tyler";
System.out.println("Press enter to begin");
// Saves userInput as a string
String userInput = input.nextLine();
while (userInput.length() != 5) {
System.out.println("Enter a 5 letter word: ");
userInput = input.nextLine();
counter++;
}
// End of Nelson's work
// Tyler's work
// Creates an array of length equal to string length
char[] ch = new char[userInput.length()];
// For loop to put characters into array
for (int i = 0; i < userInput.length(); i++) {
ch[i] = userInput.charAt(i);
}
// 'For each' loop to print each element of the array
for (char c : ch) {
System.out.println(c);
}
// Creates an array of the size of the wordle word
char[] wordle = new char[word.length()];
System.out.println(" ");
// Characters of string wordle word which is 'tyler' are in an array
for (int i = 0; i < word.length(); i++) {
wordle[i] = word.charAt(i);
// System.out.println(wordle[i]);
if (wordle[i] == ch[i]) {
System.out.println("Letter " + ch[i] + " is correct");
} else {
System.out.println("Letter " + ch[i] + " is not correct");
}
}
System.out.println(" ");
} while (counter <= 5);
System.out.println("You lost!");
// End of Tyler's work
}
}
I am trying to make a do while loop that reprompts the user for a word, giving the user 5 tries, and the program would end if A) the user has had all 5 tries, or B) the user gets the word right. Please help with the loop, or if there is additional code I should try.
I tried to put the variables inside the dowhile loop, but one of the variables is from a scanner (it is user input), but I need that inside the do while loop so it reprompts the user while the counter is less than or equal to 5.

Related

how do I add a try catch block inside a for loop to catch an ArrayIndexOutOfBounds exception?

I am new to using try catch blocks and I need some direction. I have a program that counts letters entered in a phrase from user input. The letters 'A' through 'Z' are converted to a number between 0 & 25 by subtracting the corresponding value of the Unicode character set index value of the letter that's being processed from the value of 'Z', which is 90. How would I add a try catch block inside the first for loop that translates the character to the index so that if the phrase contains any characters that are not a letter it would catch it in the ArrayIndexOutOfBoundsException. I then would have a message that prints out the non letter character in a statement to the user. I know what I want to do but, I'm having a little trouble understanding the syntax that I would need to do this. I tried to add if(counts[i] <= 64 || >= 91), but that doesn't seem to work. Do I need to convert it to a string? I know my code needs to be something like:
try {
code...
}
catch (StringIndexOutOfBoundsException exception)
{
System.out.println("Not a letter: " + counts);
}
Here is my code without the try/catch block:
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
//get word from user
System.out.print("\n Enter a single word (letters only): ");
String word = scan.nextLine();
scan.close();
//convert to all upper case
word = word.toUpperCase();
//count frequency of each letter in string
for (int i=0; i < word.length(); i++)
counts[word.charAt(i)-'A']++;
//print frequencies
System.out.println();
for (int i=0; i < counts.length; i++)
if (counts [i] != 0)
System.out.println((char)(i +'A') + ": " + counts[i]);
}
}
Instead of catching the exception, just check in your loop:
for (int i=0; i < word.length(); i++) {
char currentChar = word.charAt(i);
if (currentChar >= 'A' && currentChar <= 'Z') {
counts[currentChar -'A']++;
}
}
As was mentioned in the comments, your code shouldn't rely on catching out of bounds exceptions.
All you need to do is to put counts[word.charAt(i) - 'A']++ inside a try-catch block as shown below:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
// Get word from user
System.out.print("Enter a single word (letters only): ");
String word = scan.nextLine();
scan.close();// Do not close it.
// Convert to all upper case
word = word.toUpperCase();
// Count frequency of each letter in string
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
try {
counts[ch - 'A']++;// Check this for exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("'" + ch + "' is non-alphabetic character.");
}
}
// Print frequencies
System.out.println();
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((char) (i + 'A') + ": " + counts[i]);
}
}
}
}
A sample run:
Enter a single word (letters only): hello2world
'2' is non-alphabetic character.
D: 1
E: 1
H: 1
L: 3
O: 2
R: 1
W: 1
Some recommendations:
Do not close Scanner(System.in) as it also closes System.in and there is no way to open it again.
Do use {} for a block for loop or if/else/else if even if it just has a single statement.

How to resolve the following program with a for loop into producing an appropriate output?

The following Java program is supposed to manipulate a string input by the user in such a way that the user will decide which character needs to be replaced with another and just the last character from the string should be replaced. Example if the user enters the string "OYOVESTER" and decides to replace "O" with "L", the program should output the following result: "OYLVESTER" (notice that only the last "O" was replaced with "L")
NOTE: YOU CANNOT USE BREAK COMMAND TO STOP THE LOOP. IT IS PROHIBITED.
import java.util.Scanner;
public class StringFun {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String inString = keyboard.nextLine();
String outString = "";
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int count = 0; // variable that tracks number of letter occurrences
for(int index = inString.length() - 1;index >= 0;index--) {
if(inString.charAt(index) == oldCharF && count < 1){
outString = newCharF + outString;
outString = outString + inString.substring(0,index);
count++;
}
if (count < 1) {
outString = outString + inString.charAt(index);
}
}
System.out.print("The new sentence is: "+outString);
}
}
I keep getting the following output which is incorrect:
Enter the string to be manipulated
OYOVESTER
Enter the character to replace
O
Enter the new character
L
The new sentence is: LRETSEVOY
There are many simpler ways to achieve your requirement but I hope you have to demonstrate this with loops (without breaks)
Then you can use some thing like this :
boolean skip = false;
for (int index = inString.length() - 1; index >= 0; index--) {
if (!skip && inString.charAt(index) == oldCharF) {
outString = newCharF + outString;
skip = true;
}
else {
outString = inString.charAt(index) + outString;
}
}
PS : Using String concatenation inside loops is not recommended since
every String concatenation copies the whole String, usually it is preferable to
replace it with explicit calls to StringBuilder.append() or StringBuffer.append()
No break command seems like a weird condition. You could just a boolean value, and other methods, to break the loop when you need. Why not do something like this?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
String word = keyboard.nextLine();
//Replace Last
System.out.println("Enter the character to replace");
char oldCharF = keyboard.next().charAt(0);
System.out.println("Enter the new character");
char newCharF = keyboard.next().charAt(0);
int index = word.lastIndexOf(oldCharF);
if(index > 1){
word = word.substring(0,index) + newCharF + word.substring(index+1);
}
System.out.println("The new sentence is: " + word);
}

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers

Counting matching characters on a string

I have been asked to created a program that asks the user for two inputs, both of which have to be stored as strings. The first input can be one or multiple words, and the second input has to be one sole character. After the user enters both inputs the program should count how many times, if any, the sole charter appears in the first string. Once the iteration through the first string is done the program should then output the number of instances of the second string. Example:
"There is 1 occurrence(s) of 'e' in test."
The program must use the a while loop and string values. This is the solution I have as of right now following the parameters established by the professor
public static void main(String[] args) {
String inputEntry; // User's word(s)
String inputCharacter; // User's sole character
String charCapture; // Used to create subtrings of char
int i = 0; // Counter for while loop
int charCount = 0; // Counter for veryfiying how many times char is in string
int charCountDisplay = 0; // Displays instances of char in string
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
inputCharacter = scan.nextLine();
if (inputCharacter.length() > 1 || inputCharacter.length() < 1) // if user is not in compliance
{
System.out.print("Please enter one character. Try again.");
return;
}
else if (inputCharacter.length() == 1) // if user is in compliance
{
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
System.out.print("There is " + charCountDisplay +
" occurrence(s) of " + inputCharacter + " in the test.");
}
}
This iteration has a bug. Instead of counting all the instances of the inputCharacter variable it only counts up to one, regardless of how many instances appear on the string. I know the problem is in this part of the code:
while( i < inputEntry.length()) // iterates through word(s)
{
charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
if (charCapture.equals(inputCharacter))
{
++charCountDisplay;
}
++charCount;
++i;
}
I just can't quiet pin down what I'm doing wrong. It seems to me that the charCountDisplay variable reverts to zero after each iteration. Isn't that supposed to be avoided by declaring the variable at the very beginning?... I'm one confused fellow.
This is wrong
charCapture = inputEntry.substring(charCount);
does not return one char
try using inputEntry.charAt(charCount)
Another hint is to define your variables close to where you use them rather than at the top of your method like:
String inputEntry;
inputEntry = scan.nextLine();
Even better would be to do inline
String inputEntry = scan.nextLine();
It will make your code a lot more concise and readable.
A more concise way to do your code is:
Scanner scan = new Scanner(System.in);
System.out.print("Enter some words here: "); // Captures word(s)
String inputEntry = scan.nextLine();
System.out.print("Enter a character here: "); // Captures char
String inputCharacter = scan.nextLine();
// validate
// then
int len = inputEntry.length();
inputEntry = inputEntry.replace(inputCharacter, "");
int newlen = inputEntry.length();
System.out.format("There is %d occurrence(s) of %s in the test.%n",
len - newlen, inputCharacter);
output
Enter some words here: scarywombat writes code
Enter a character here: o
There is 2 occurrence(s) of o in the test.
Here is a complete MVCE:
package com.example.countcharacters;
/**
* EXAMPLE OUTPUT:
* Enter some words here:
* How now brown cow
* Enter a character here:
* abc
* Please enter one character. Try again.
* Enter a character here:
* o
* There are 4 occurrence(s) of o in the text How now brown cow.
*/
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Captures word(s)
String inputEntry;
System.out.println("Enter some words here: ");
inputEntry = scan.nextLine();
// Captures char
char inputCharacter;
while (true) {
System.out.println("Enter a character here: ");
String line = scan.nextLine();
if (line.length() == 1) {
inputCharacter = line.charAt(0);
break;
} else {
// if user is not in compliance
System.out.println("Please enter one character. Try again.");
}
}
// iterates through word(s)
int charCountDisplay = 0;
int i = 0;
while(i < inputEntry.length()) {
char c = inputEntry.charAt(i++);
if (c == inputCharacter) {
++charCountDisplay;
}
}
// Print results
System.out.print("There are " + charCountDisplay +
" occurrence(s) of " + inputCharacter +
" in the text " + inputEntry + ".");
}
}
NOTES:
You can use "char" and "String.charAt()" to simplify your code.
In general, it's preferable to declare variables close to where you use them (rather than at the top).
You can put your test for "one character only" in its own loop.
'Hope that helps!
inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() will give you the number of occurrences of a character in the string.
String inputEntry = "text";
char inputCharacter = 'x';
System.out.print("There is " + inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() + " occurrence(s) of " + inputCharacter + " in the text " + inputEntry + ".");

Random String Generator keeps adding to previous iterations

I am writing a program that takes a user's input for a string that must be of length 6, and creates a random version of that string. Then, it prints out 5-10 iterations of a randomised string. For example:
The input of 8 and abcdef would create 8 lines of random variations of abcdef. The program below does that, but it's adding strings together, as so:
abbdfe
abbdfeacbfed
and so on. Does anyone know how to change it so it would print abbdfe acbfed and so on.
I know there are some functional issues with my code but it works as a start.
package matrixMaker;
import java.util.Scanner;
import java.util.Random;
public class matrixMaker
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number between 5 and 10, inclusively: ");
int userInput = in.nextInt();
in.nextLine();
System.out.print("Please enter a string of length 6 characters: ");
String textToChange = in.nextLine();
String randomText = "";
int length = 6;
// Print error if text is not 6 characters long.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
}
// If input is 6 characters, print out randomText X amount of times, depending on the user's specification of user.
if(textToChange.length() == 6)
{
for (int i = 1; i <= userInput; i++)
{
// Initialise array to create random order of chars.
Random rand = new Random();
char[] text = new char[length];
for(int a = 0; a < length; a++)
{
text[a] = textToChange.charAt(rand.nextInt(textToChange.length()));
}
// Take the chars from array and concatenate them into a string of the same size as the text variable.
for(int a = 0; a < text.length; a++)
{
randomText += text[a];
}
System.out.printf(randomText + "\n");
}
}
in.close();
}
}
You seem to be initializing the variable randomText at the top of the method, but keep adding to the same variable inside the loop, so it will keep adding to itself.
String randomText = "";
randomText += text[a];
Either initialize the randomText String inside the loop, or after your last line inside the loop, assign it back to an empty string again.
Btw, you seem to have another error here:
// Print error if text is not 6 characters long.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
}
This loop will go for infinite, you need to add a way to allow the user to change the input after the error is displayed.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
in.nextLine();
textToChange = in.nextLine();
}
--Edit added to OP comment:
To print the character of the odd generated text on the odd row number; one way to do it is to consider pushing your generated randomText to an empty ArrayList which you initialize outside the loop..then you can loop over your ArrayList separately. You can think of ways to refactor this and put in an outside method in the way you like. like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a number between 5 and 10, inclusively: ");
int userInput = in.nextInt();
in.nextLine();
System.out.print("Please enter a string of length 6 characters: ");
String textToChange = in.nextLine();
int length = 6;
// Print error if text is not 6 characters long.
while (textToChange.length() != 6) {
System.out.println("Error! Enter a string of length 6.");
in.nextLine();
textToChange = in.nextLine();
}
//new array list for results of random text generated
ArrayList<String> randomTextArray = new ArrayList<>();
// If input is 6 characters, print out randomText X amount of times, depending on the user's specification of user.
if (textToChange.length() == 6) {
for (int i = 1; i <= userInput; i++) {
String randomText = "";
// Initialise array to create random order of chars.
Random rand = new Random();
char[] text = new char[length];
for (int a = 0; a < length; a++) {
text[a] = textToChange.charAt(rand.nextInt(textToChange.length()));
}
// Take the chars from array and concatenate them into a string of the same size as the text variable.
for (int a = 0; a < text.length; a++) {
randomText += text[a];
}
randomTextArray.add(randomText);
System.out.printf(randomText + "\n");
}
System.out.printf("Odd Characters \n");
String oddCharsOfRandomText = "";
for (int i=0; i < randomTextArray.size(); i++) {
if (!(i%2 == 0)) { //resolve true only if we are in an odd line
for (int x=0; x <= randomTextArray.get(i).length(); x++ ){
if (!(x%2 == 0)) { //resolve true only if we are in an odd character
oddCharsOfRandomText += randomTextArray.get(i).charAt(x);
}
}
}
}
System.out.printf(oddCharsOfRandomText + "\n");
}
in.close();
}

Categories

Resources