Just started a computer science degree and have been tasked with making a Hangman game, it seems to work find other than it doesn't print "You won" and I cannot see/figure out why it doesn't. Any help from you guys would be great.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
char[] alpha = new char[26];
Arrays.fill(alpha, ' ');
String a1 = "intro to programming";
String a2 = "computer";
String a3 = "mouse and keyboard";
String a4 = "skyrim";
String a5 = "hello world";
int selector = rand.nextInt(5) + 1;
char[] words = null;
char[] show = null;
if (selector == 1) {
words = a1.toCharArray();
show = a1.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 2) {
words = a2.toCharArray();
show = a2.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 3) {
words = a3.toCharArray();
show = a3.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 4) {
words = a4.toCharArray();
show = a4.toCharArray();
Arrays.fill(show, '-');
} else if (selector == 5) {
words = a5.toCharArray();
show = a5.toCharArray();
Arrays.fill(show, '-');
}
int length = words.length;
System.out.println("Please enter the amount of tries you would like:");
int amount = scan.nextInt();
String guessed;
char guessedchar;
for (int i = 0; i < length; i++) {
if (words[i] == ' ') {
show[i] = ' ';
}
}
int x = 0;
while (amount >= 0) {
System.out.print("String to guess: ");
for (char n : show) {
System.out.print(n);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Number of tries left: " + amount);
System.out.print("Number of times you have tried: ");
for (char a : alpha) {
System.out.print(a);
System.out.print(" ");
}
System.out.println(" ");
System.out.println("Enter a guess");
guessed = scan.next();
guessedchar = guessed.charAt(0);
alpha[x] = guessedchar;
for (int i = 0; i < length; i++) {
if (guessedchar == words[i]) {
show[i] = guessedchar;
}
}
x = x + 1;
amount = amount - 1;
if (amount == 0) {
System.out.println("You lose");
return;
} else if (show == words) {
System.out.println("You won");
}
}
}
Convert the words and show arrays to Strings and check if they are equal with .equals(), this should then display the correct message
Related
So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
I am very new to java and I was wondering if you could help me out. Here is my code:
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
for (int i = 0; i <= length; i++) {
String letter = string.substring(i, ++i);
if (letter.equalsIgnoreCase("a")){vowels++;}
if (letter.equalsIgnoreCase("e")){vowels++;}
if (letter.equalsIgnoreCase("i")){vowels++;}
if (letter.equalsIgnoreCase("o")){vowels++;}
if (letter.equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
The number is off but I can't figure out why.
This here is wrong
string.substring(i, ++i)
because the variable i is already incremented in the for-loop
so you are basically skipping chars in the string
implement the right logic, use the right data type
int length = string.length();
for (int i = 0; i < length; i++) {
char letter = string.charAt(i);
System.out.println(letter);
if (letter == 'a') {
vowels++;
} else if (letter == 'e') {
vowels++;
} else if (letter == 'i') {
vowels++;
} else if (letter == 'o') {
vowels++;
} else if (letter == 'u') {
vowels++;
}
}
Here is another solution you could try:
The split method will split the string into a String array. Then in your for loop it will check every item in your array.
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
String[] stringArray = string.split("");
for (int i = 0; i < length; i++) { //I took out the = sign in your for loop arguments.
if (stringArray[i].equalsIgnoreCase("a")){vowels++;}
if (stringArray[i].equalsIgnoreCase("e")){vowels++;}
if (stringArray[i].equalsIgnoreCase("i")){vowels++;}
if (stringArray[i].equalsIgnoreCase("o")){vowels++;}
if (stringArray[i].equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
i have a problem writing guess the word game java code .
i'll show you my current code and till you the problem .
import java.util.Scanner;
class Q
{
public static void main(String argss[])
{
String strs[] = { "kareem", "java", "izz", "tamtam", "anas" };
Scanner input = new Scanner(System.in);
int index = ((int) (Math.random() * 5));
int points = 50;
String c;
boolean result = false;
boolean finalResult = false;
boolean tempResult = false;
String word = strs[index];
System.out.println(
"\t *** Enter a character and guess the world*** \n\t ***You will loose if your points become 0 *** \n ");
System.out.println(stars(word));
System.out.println("Your points: " + points);
System.out.print("Enter and guess a character! ");
String temp = stars(word);
String oldTemp = temp;
c = input.next();
while (points > 0)
{
for (int i = 0; i < word.length(); i++)
{
result = (word.charAt(i) + "").equals(c);
if (result == true)
{
temp = toChar(i, temp, c);
}
}
finalResult = temp.equals(word);
tempResult = temp.equals(oldTemp);
System.out.println(temp);
if (finalResult == true)
{
System.out.println("\n \n YOU HAVE GUESSED THE WORLD,YOU WON ! ");
break;
}
if (tempResult == true)
{
points = points - 5;
System.out.println("False and now your points are " + points);
}
else if (tempResult == false)
{
System.out.println("True and now your points are " + points);
}
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
System.out.print("Guess another time,enter a character: ");
c = input.next();
}
}
public static String stars(String word)
{
String temp = "";
for (int i = 0; i < word.length(); i++)
temp = temp + "*";
return temp;
}
public static String toChar(int index, String temp, String c)
{
char[] tempChar = temp.toCharArray();
char s = c.charAt(0);
tempChar[index] = s;
temp = String.valueOf(tempChar);
return temp;
}
}
now as you can see in line number 39 , i have a little problem here because when its false it'll be no longer right .
do you know another way to compare if the entry is right or not ?
Doesn't look like you are changing oldTemp inside the while loop. Try setting it to equal to temp after all of the if statements.
if (points <= 0)
{
System.out.println("\n\n*********************\n* Sorry , you loose *\n********************* ");
break;
}
oldTemp = temp; // add this here
System.out.print("Guess another time,enter a character: ");
c = input.next();
I am writing a program that is supposed to calculate the Flesch index of a passage or string and tell the minimum education level required to comprehend.
What is supposed to happen is a person types in a string that the want to be calculated and the program is supposed to count the number of words and count the number of sentences as well as go through each word and calculate how many syllables there are in the word and add that to the total syllable counter. The way to calculate syllables is to count the number of adjacent vowels in a word, so "Computer" for instance has the vowels o, u, and e so 3 syllables. But, if the word ends in the letter e, subtract 1 from the total syllable count so, "Passage" has a, a, and e, but since the e is at the end, the syllable count is 2.
Here is what I got so far:
// Import scanner to get input from the user
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
public static final double BASE = 206.835;
public static final double WORD_LENGTH_PENALTY = 84.6;
public static final double SENTENCE_LENGTH_PENALTY = 1.015;
Scanner input = new Scanner (System.in);
// Declare variables for syllables and words
int totalWords = 0;
int totalSyllables = 0;
// Prompt user for a passage of text
System.out.println ("Please enter some text:");
String passage = input.nextLine();
// Words
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == ' ') {
totalWords++;
}
else if (passage.charAt(i) == '.') {
totalWords++;
}
else if (passage.charAt(i) == ':') {
totalWords++;
}
else if (passage.charAt(i) == ';') {
totalWords++;
}
else if (passage.charAt(i) == '?') {
totalWords++;
}
else if (passage.charAt(i) == '!') {
totalWords++;
}
}
System.out.println ("There are " + totalWords + " words.");
char syllableList [] = {'a', 'e', 'i', 'o', 'u', 'y'};
// Syllables
for (int k = 0; k < syllableList.length; k++)
{
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == syllableList[k]) {
totalSyllables = totalSyllables + 1;
}
if (lastChar(passage) == 'E' || lastChar(passage) == 'e') {
totalSyllables = totalSyllables - 1;
} else {
break;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
input.close();
public static char lastChar (String aWord)
{
char aChar = aWord.charAt(aWord.length() - 2);
System.out.print (aChar);
return aChar;
}
/** Return true if the last character in the parameter word is
* a period, question mark, or exclaimation point, and false
* otherwise
**/
public static boolean sentenceEnd (String word)
{
if (lastChar(passage) == '.') {
return true;
} else if (lastChar(passage) == '?') {
return true;
} else if (lastChar(passage) == '!') {
return true;
} else {
return false;
}
}
double fleschIndex = BASE - WORD_LENGTH_PENALTY * (totalSyllables / totalWords) - SENTENCE_LENGTH_PENALTY * (totalWords / totalSentences);
if (fleschIndex > 100) {
educationLevel = "4th grader";
} else if (fleschIndex <= 100) {
educationLevel = "5th grader";
} else if (fleschIndex <= 90) {
educationLevel = "6th grader";
} else if (fleschIndex <= 80) {
educationLevel = "7th grader";
} else if (fleschIndex <= 70) {
educationLevel = "8th grader";
} else if (fleschIndex <= 60) {
educationLevel = "9th grader";
} else if (fleschIndex <= 50) {
educationLevel = "high school graduate";
} else if (fleschIndex <= 30) {
educationLevel = "college graduate";
} else if (fleschIndex < 0) {
educationLevel = "law school graduate";
}
System.out.println ("The Flesch idex is " + fleschIndex + ".");
System.out.println ("The text can be understood by a " + educationLevel + ".");
}
}
I keep getting some weird error messages telling me to put semi-colons around the boolean declarations which makes no sense to me.
It looks to me like you mixed up your methods.
The methods sentenceEnd and lastChar are inside the main-method. This is not allowed.
They have to be outside of the main-method but inside the Flesch-Class.
I am not sure how to get the program to print out double letters in a word like soccer. Whenever soccer is chosen by the random generator, and I guess the letter "c" the system out prints ••c•••. I would want it to print ••cc••. Any help at all would be appreciated
import TurtleGraphics.*;
import java.util.Scanner;
import java.util.Random;
public class HangmanGame
{
public static void main(String [] args)
{
String repeat = "yes";
while((repeat.equals("yes"))||(repeat.equals ("Yes")))
{
SketchPadWindow pad = new SketchPadWindow(800, 800);
StandardPen pen = new StandardPen(pad);
Scanner scan = new Scanner(System.in);
HangmanTest hang = new HangmanTest();
Random randomGenerator = new Random();
//Ints
int index=0;
int number=0;
int counter=0;
int randomNum = 0;
//Strings
String Secretword = "";
String choose = "";
String guessLetter = "";
String guesses = "";
String diff = "";
String Pokemon [] = {"pikachu", "jigglypuff", "dugtrio", "muk", "ditto", "eevee", "mewtwo", "cyndaquil", "raikou"};
String Sports [] = {"tennis", "rowing", "golf", "lacrosse", "sailing", "soccer", "football", "baseball", "volleyball"};
String Periodic [] = {"iron", "carbon", "radon", "ununcodium", "oxygen", "magnesium", "antimoney", "iodine", "cadmium"};
String Food [] = {"pizza", "spaghetti", "muffin", "bagel", "chicken", "steak", "apple", "chips", "cookies"};
String Boardgames [] = {"life", "monopoly", "battleship", "boggle", "sorry", "operation", "blokus", "cranium", "gab"};
String Planets [] = {"mars", "pluto", "saturn", "earth", "jupiter", "uranus", "neptune", "mercury", "venus"};
String States [] = {"utah", "washington", "colorado", "california", "texas", "wyoming", "missouri", "kentucky", "connecticut"};
String Spanish [] = {"hola", "adios", "feliz", "durante", "conocer", "sobre", "decir", "trabajar", "manzana"};
String ACT [] = {"congregation", "camaraderie", "digression", "emulate", "fortuitous", "frugal", "evanescent", "hypothesis", "extenuating"};
String dashes = "";
hang.drawGallo(pen);
System.out.println("There are three difficulties to chose from with sub categories in each");
System.out.println("They are: Easy, Medium and Hard");
diff = scan.nextLine();
if(diff.equals("Easy")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Sports, Food or Boardgames");
choose = scan.nextLine();
if(choose.equals("Sports")){
randomNum = randomGenerator.nextInt(Sports.length-1);
Secretword = Sports[randomNum];
}else if (choose.equals("Food")){
randomNum = randomGenerator.nextInt(Food.length-1);
Secretword = Food[randomNum];
}else if (choose.equals("Boardgames")){
randomNum = randomGenerator.nextInt(Boardgames.length-1);
Secretword = Boardgames[randomNum];
}
}else if (diff.equals("Medium")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Pokemon, Planets or States");
choose = scan.nextLine();
if(choose.equals("Pokemon")){
randomNum = randomGenerator.nextInt(Pokemon.length-1);
Secretword = Pokemon[randomNum];
}else if(choose.equals("Planets")){
randomNum = randomGenerator.nextInt(Planets.length-1);
Secretword = Planets[randomNum];
}else if(choose.equals("States")){
randomNum = randomGenerator.nextInt(States.length-1);
Secretword = States[randomNum];
}
}else if (diff.equals ("Hard")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Periodic, Spanish or ACT");
choose = scan.nextLine();
if(choose.equals("Periodic")){
randomNum = randomGenerator.nextInt(Periodic.length-1);
Secretword = Periodic[randomNum];
}else if(choose.equals("Spanish")){
randomNum = randomGenerator.nextInt(Spanish.length-1);
Secretword = Periodic[randomNum];
}else if(choose.equals("ACT")){
randomNum = randomGenerator.nextInt(ACT.length-1);
Secretword = ACT[randomNum];
}
}
for(int x = 0; x< Secretword.length(); x++)
dashes += "*";
System.out.println(dashes);
while(number <= 9 && !dashes.equals(Secretword) )
{
String letter = "";
System.out.println("Please enter a letter or the entire word.");
letter = scan.nextLine();
if(letter.equals(Secretword))
{
System.out.println("You correctly guessed the word. Good job!");
break;
}
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
/*for (int x=0; x <Secretword.length() - 1; x++)
{
if (Secretword.charAt(x) == Secretword.charAt(x +1))
{
System.out.println("Word contains double");
}else
{
System.out.println("Normal word found");
}
}
*/
System.out.println("You entered a letter in the word");
dashes = dashes.substring(0, index) + letter + dashes.substring(index +1);
System.out.println(dashes);
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
if(number == 1)
hang.drawHead(pen);
if(number == 2)
{
hang.drawReye(pen);
hang.drawLeye(pen);
hang.drawPupils(pen);
}
if(number == 3)
{
hang.drawNose(pen);
hang.drawMouth1(pen);
}
if(number == 4)
hang.drawTeeth(pen);
if(number == 5)
hang.drawHair(pen);
if(number == 6)
hang.drawLglasses(pen);
if(number == 7)
hang.drawBody(pen);
if(number == 8)
{
hang.drawRarm(pen);
hang.drawLarm(pen);
}
if(number == 9)
{
hang.drawLleg(pen);
hang.drawRleg(pen);
}
}
if(number == 10){
System.out.println("You lose");
System.out.println("The word was:" + " " + Secretword);
}else
{
System.out.println("You win");
}
System.out.println("Game Over");
System.out.println("Would you like to play again?");
repeat = scan.nextLine();
}//end over all while loop
System.exit(0);
}//close main function
}//close class
I see you tried to fix it so you know where the problem is. The simplest way to get it working would be something like:
if(Secretword.indexOf(letter) != -1)
{
System.out.println("You entered a letter in the word");
while(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
dashes = dashes.substring(0, index) + letter + dashes.substring(index +1);
}
System.out.println(dashes);
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
That is until someone enters * and it'll freeze. I'll leave that to you to fix ;)