this my program
import java.util.*;
public class LeTter { //open class name
static Scanner keyboard = new Scanner(System.in); // Scanner
public static void main(String[] args) { //open main class
char letter; //decl
int y, x, z; //decl
boolean check = false;
System.out.println("Enter 8 letters: "); // print sentince
char[] des = new char[8]; //array
for (y = 0; y < des.length; y++) { // for without semicolon :), open for loop
des[y] = keyboard.next().charAt(0); //initialize
} // close for loop
System.out.println("Enter any letter to check about it: "); //will apper to the user
letter = keyboard.next().charAt(0); //initi
for (x = 0; x < des.length; x++) { //for loop opens
if (des[x] == letter) { //open if loop
System.out.println("we found it's " + des[x] + " and the index of it is " + x);
System.out.println("so we will show you this letters " + x + " times");
for (z = 0; z < x; z++)
System.out.println(des[x] + " ");
check = false;
} //close if loop
if (true)
System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
} // close for loop
} //close main
} //close class
put if the user didn't put the letter that not look like 8 letter was enter i want to print this statement "we don't found it"
how can I do it
example:
enter 8 letters
a s d f g h j k
enter any letter
t
we don't found it << how can I do this??
another example:
enter 8 letters
a s d f g h j k
enter any letter
a
we found it << i did this , i want the first one ""onlly""
I skip the input and begin from the loop of your code, change it to:
for (x = 0; x < des.length; x++)
{ // for loop opens
if (des[x] == letter)
{ // open if loop
check = true;
System.out.println("we found it's " + des[x] + " and the index of it is " + x);
break; // you want to show 1st one only, right?
} // close if loop
} // close for loop
if (!check)
System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
I've shortened your code, as you can just add the user's input into a char array, and remove the spaces.
I used break; to get out of the loop once the first char was found, you can remove this if you want to mind multiple instance of it.
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter 8 letters: ");
String letters = keyboard.nextLine().replaceAll(" ", "");
char cArray[] = letters.toCharArray();
System.out.println("Enter any letter to check about it: ");
char letter = keyboard.next().charAt(0);
boolean found = false;
for (int i = 0; i < cArray.length; i++) {
if (cArray[i] == letter) {
System.out.println("We found " + letter + " at position " + i);
found = true;
break; //used as you specify only to find the first one
}
}
if (!found) {
System.out.println("Are you sure about the letter you entered? We didn't find it");
}
}
Try it online!
Related
import java.util.Scanner;
public class VowelsAndConsonants {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int ConsonantCount = 0;
int VowelCount = 0;
int num = 0;
int x = 0;
while(true) {
System.out.print("Enter a string: ");
String userInput = input.next();
num = userInput.length();
for(x = 0; x < num ; x++) {
char c = userInput.charAt(x);
if (Character.isLetter(c)){
c = Character.toUpperCase(c);
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
VowelCount++;
else
ConsonantCount++;
}
}
System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
System.out.println("Do you want to enter another string? ");
String loopAgain = input.next();
if (loopAgain.equalsIgnoreCase("N")) {
break;
}
}
}
}
How do I reset the VowelCount and ConsonantCount after looping again? Currently, it's adding onto the counter without resetting to zero. Please help. My instructor wants me to break out of the loop if I say N or loop again if its any other character
I'm assuming you want to reset it after you print?
All you need to do is assign it like any other variable
System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
ConsonantCount = 0;
VowelCount = 0;
Another route you could take would be to declare your variables at the beginning of the while loop. This way, every time the while loop runs, it re-initializes the variables to zero, so you don't have to even reset it.
while (true) {
int ConsonantCount = 0;
int VowelCount = 0;
....
}
I am trying to create a Hangman and I have 2 problems.
1) The first problem is when the user finds the word, the loop does not stop.
2) I have a variable attempts which allows to know the number of attempts. Even if the user finds the letter, the number of attempts decrease.
The word to find is no
Here is a demonstration:
1) I enter the letter n
You have 5 attempts.
--
Enter your letter : n
2) I enter the letter o
The letter is good.
You have 4 attempts.
n-
Enter your letter : o
3) Normally the loop should stop.
The letter is good.
You have 3 attempts.
no
Enter your letter :
If you have an idea thank you in advance.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
attempts--;
}
}
}
You are just missing a checking loop or method. Check the solution below.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
boolean done = true;
for(boolean b : word_found)
done = done && b;
if(done) break;
else attempts--;
}
I will follow to your solution, not suggest a better one.
Ad 1. Add a check if the array word found contains only true after your first for cycle and if there are only true values in the array, print "you won" and set attempts to 0
Ad 2. Move attempts-- to the else case of your first for cycle OR add attempts++ in the true case of your first for cycle
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = { /* "yes", */ "no" };
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while (attempts > 0) {
System.out.println("You have " + attempts + " attempts.");
for (int i = 0; i < word_random.length(); i++) {
if (word_found[i]) {
System.out.print(word_random.charAt(i));
} else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
boolean match = false;
for (int i = 0; i < word_random.length(); i++) {
if (word_random.charAt(i) == letter) {
System.out.println("The letter is good. ");
word_found[i] = true;
match = true;
if (i == word_found.length - 1) {
System.out.println("THE END: attempts: " + attempts);
return;
}
}
}
if (!match) {
attempts--;
}
}
System.out.println("THE END");
}
I suggest you to modify the last part of your code like I did, and it should work.
public class Game {
public static void main(String[] args) {
String secretWord = "frog";
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0) {
here the loop cycles through the characters in a String, and checks if the user input guessedLetter matches a char in the string. right now the loop cycles through each char starting with the first char in the string through the last, the user must guess the letters in the exact order of they are arranged in the string, how can I fix this so that any character input matching a character in the String will be correct rather than the characters having to be in order?
for (int i = 0; i < secretWord.length(); i++) {
char guessedLetter = input.next().charAt(0);
char currentLetter = secretWord.charAt(i);
if (guessedLetter == currentLetter) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
}
else if (guessedLetter != currentLetter) {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
}
else if (correctGuesses == secretWord.length()) {
System.out.println("You Got It! The Word is: " + secretWord);
}
}
}
}
You could try it as follows:
move all the characters of secretWord to a map (key would be the character and the value would be incidences of that character in the string).
read the character from the keyboard and interate (basically, your logic).
Here is the code.
public static void main(String[] args) {
String secretWord = "frog";
Map<Character, Integer> mapOfLetters = new HashMap<>();
for (char c : secretWord.toCharArray()) {
int count = 1;
if (mapOfLetters.containsKey(c)) {
count = mapOfLetters.get(c) + 1;
}
mapOfLetters.put(c, count);
}
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0 && !mapOfLetters.isEmpty()) {
char guessedLetter = input.next().charAt(0);
if (mapOfLetters.containsKey(guessedLetter)) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
int count = mapOfLetters.get(guessedLetter) - 1;
if (count == 0) {
mapOfLetters.remove(guessedLetter);
} else {
mapOfLetters.put(guessedLetter, count);
}
} else {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
} else if(mapOfLetters.isEmpty()){
System.out.println("You Got It! The Word is: " + secretWord);
}
}
guessedLetter = input.next().charAt(0);
If you want to match the whole UserInput there should not be charAt(0).
On the other hand, if you just want to match any character, at first time you can test guessedLetter == currentLetter is true, then just exit program.
By the way, if you like, just google "KMP algorithm" to learn how to match String.
I'm new to this site. I've decided to create a console base hangmaan game and I've been doing ok up till now. My current problem has me stuck.
I'm trying to make it so that if the user has input a letter and it has been marked as correct or incorrect. The program should then not let the user input that same letter again in later iterations of the while loop.
The comments should give you a better idea of what I'm talking about.
Can anyone please help me?
package hangMan2;
import java.io.IOException;
import java.util.Scanner;
public class mainClss {
public static void main(String[] args) {
int point = 0;
int numberOfLetterInWord;
// prompt user for input and store input into String word
System.out.println("Enter a word in lower case from the dictionary: ");
Scanner inputWord = new Scanner(System.in);
String word = inputWord.next();
// letters remaining in word equals the length of the word at the start
int lettersRemainingInWord = word.length();
for (int i = 0; i < 30; i++) {
System.out.println("\b");
}
// while points are above 7 (7 is when man is hung) and there's more
// than one letter remaining do all the following:
while (point > -7 && lettersRemainingInWord >= 1) {
//prompts user to input letter guess and stores in letter
System.out.print("\nEnter a letter for this " + word.length()
+ " letter word: ");
Scanner inputLetter = new Scanner(System.in);
String letter = inputLetter.next();
if (word.contains(letter)) {
System.out.println("Correct!");
point += 1;
System.out.println("Score: " + point);
lettersRemainingInWord -= 1;
//I need code here to remove the current letter from being able to be used again
if (lettersRemainingInWord > 0) {
continue;
}
else {
System.out.println("\nYou win!!!");
System.out.println("The word was: " + word);
break;
}
}
else {
System.out.println("Incorrect\n");
point -= 1;
System.out.println("Score: " + point);
//I need code here to remove the current letter from being able to be used again
if (lettersRemainingInWord > 0) {
continue;
}
else {
System.out.println("Game over! You lose!");
System.out.println("Score: " + point);
System.out.println("The word was: " + word);
break;
}
}
}
if (point <= -7) {
System.out.println("Game over! You lose!");
System.out.println("Score: " + point);
System.out.println("The word was: " + word);
}
}
}
You could test whether the letter is in a Set. If not, accept it and add it to the set. If so, then reject it.
Set<String> usedLetters = new HashSet<String>();
boolean isUsedLetter(String letter) {
if (usedLetters.contains(letter)) {
return true;
} else {
usedLetters.add(letter);
return false;
}
}
You can use an ArrayList to hold the characters that have already been typed and then check the list to see if the character is in there.
List<Character> used = new ArrayList<Character>();
char let = //letter that they inputted
if(used.contains(let)) {
//do something
}
else {
used.add(let);
}
When I run this code, which is a menu with many different options. it consists of many loops. Some of which I have yet to make. But my issue arises when I have the user select "t" or the coin toss simulator. The loop begins but once the user enters the amount of coin flips say 4, it says 2.0 heads and 2.0 tails means 50.0% were heads
Type code letter for your choice: COIN TOSS SIMULATOR
Enter 0 to quit. How many tosses?
It shouldn't say type the letter for your choice: COIN TOSS SIMULATOR, enter 0 to quit. how many tosses?
Also when I enter 0 it says You have entered an invalid option. 't' is not a valid option. I want to Bring back the main menu!!!! what is going on????
public class toolBox {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
boolean properInput = false;
int usersInput;
while (!properInput) {
System.out.println("Enter seed value:");
if (myScanner.hasNextInt()) {
usersInput = myScanner.nextInt();
properInput = true;
Random randomSeed = new Random(usersInput);
String randomNumberList = "";
for (int i = 0; i < 10; i++) {
randomNumberList += randomSeed.nextInt(80) + " ";
}
} else
{
String helloWorld = myScanner.next();
System.out.println("You have not entered an integer. '" + helloWorld + "' is not an integer");
}
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{
Scanner anotherScanner = new Scanner(System.in);
boolean usersSelection = false;
String c;
outer:
while (!usersSelection) {
{
System.out.print("" + "Type code letter for your choice: ");
}
if (anotherScanner.hasNext("q|Q")) {
c = anotherScanner.next();
usersSelection = true;
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
{
System.out.println("" + "COIN TOSS SIMULATOR" + "");
}
System.out.println("Enter 0 to quit. How many tosses?");
Random rand = new Random();
boolean headsOrTails;
float headsCount = 0;
float tailsCount = 0;
Scanner scanMan = new Scanner(System.in);
int numero = scanMan.nextInt();
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
headsOrTails = rand.nextBoolean();
if (headsOrTails == true) {
headsCount++;
} else {
tailsCount++;
}
}
System.out.println(headsCount + " heads and " + tailsCount + " tails means "
+ (headsCount / (headsCount + tailsCount) * 100 + "% were heads"));
}
}
if (anotherScanner.hasNext("g|G")) // if the user were to enter either case of g, the
// program will register both and initialize the
// grade estimator.
{
c = anotherScanner.next();
usersSelection = true;
}
if (anotherScanner.hasNext("c|C"))
{
c = anotherScanner.next();
usersSelection = true;
System.out.println("Welcome to the Color Challenge!");
}
else {
String zoom = anotherScanner.next();
System.out.println("You have entered an invalid option. '" + zoom + "' is not a valid option.");
}
}
}
}
Your question is not clear, but your title suggests to me you think there is an inner and outer loop.
You don't have an inner and an outer loop.
Your indentation was really messy, but when I cleaned it up and then deleted a lot of extra lines of code, the structure of the code became clear.
Notice the following:
1) You have two loops, one on top switched on !properInput, the lower one switched on !usersSelection. There is also a for loop, but it doesn't do anything related to the code flow you are asking about.
2) You have two identical labels, one outside an anonymous block of code (see my comment in the code below), and another inside the anonymous block. In this case it doesn't affect your question, but it is definitely a problem.
My guess is that your break outer line isn't working because you are breaking out of the lower while loop.
I suggest you try fragmenting your code into functions to make the structure clearer.
while (!properInput) {
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{ /* begin anonymous code block */
outer:
while (!usersSelection) {
if (anotherScanner.hasNext("q|Q")) {
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
System.out.println("Enter 0 to quit. How many tosses?");
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
}
}
}
}