I'm having some difficulty incrementing my counter called right. Instead of incrementing it constantly prints out 1 and doesn't add the numbers together. I tried using another variable to total up the counter but no luck. Any ideas to why it is not incrementing?
Code:
tf.addActionListener(new ActionListener() {
int wrong = 0;
int right = 0;
#Override
public void actionPerformed(ActionEvent e) {// enter key
JTextField tf = (JTextField) e.getSource();
letter = tf.getText();
tf.setText("");
// tf.requestFocus();
jlLetsUsed.setText(jlLetsUsed.getText() + letter + " ");// sets
char[] jlabelText = jlLines.getText().toCharArray();// converts
char userEnteredChar = letter.charAt(0);
System.out.println(wordList[level]);
if (!wordList[level].contains(letter)) {
wrong++;
if (wrong == 6) {
JOptionPane.showMessageDialog(frame,
"He's dead, game over." + "\n"
+ "The word was " + wordList[level]
+ ".", "You Lost",
JOptionPane.INFORMATION_MESSAGE, ic);
GameStructure restart = new GameStructure();
level = (int) (Math.random() * 64);// generate new
// random word
restart.window();
}
return;
}
int i = 0;
for (i = 0; i < wordList[level].length(); i++) {
if (wordList[level].charAt(i) == userEnteredChar) {
jlabelText[3 * i] = ' ';
jlabelText[3 * i + 1] = userEnteredChar;
right++;
}// end if
}// end for
jlLines.setText(String.valueOf(jlabelText));
if (jlabelText.length / 3 == right) {
JOptionPane.showMessageDialog(frame, "You got the word!.",
"You Lost", JOptionPane.INFORMATION_MESSAGE, ic);
GameStructure restart = new GameStructure();
level = (int) (Math.random() * 64);// generate new
// random word
restart.window();
}
}// end actionPerformed method
});
My guess is that you're expecting right to print the number of times you've guessed right, but it appears as though you call
int right = 0;
every time you guess.
Try loading up a word with at least 2 of the same letter, and guess that letter. I'll bet that you see the number go up to 2 in that case.
If you want a number to increment every time you've guessed a correct letter, than you're going to have to declare it outside the scope of your guess.
Related
I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:
Question 1: num1 + num2 =
or
Question 2: num1 - num2 =
I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.
Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!
As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
heres my code so far:
public static void main(String[] args) {
//mental arithmetic game
System.out.println("You will be presented with 8 addition questions.");
System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");
//set up input scanner
Scanner keyboard = new Scanner(System.in);
//declare constant variables
final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;
long start_time, end_time;
//generate 2 random numbers
int random_number1 = (int) ((Math.random() * max_range) + min_range);
int random_number2 = (int) ((Math.random() * max_range) + min_range);
//declare variables
int question_number = 1;
int guess;
//prompt user to start the game
System.out.println();
System.out.print("Press y to Start the Game: ");
String start_program = keyboard.next();
if (start_program.equals("y")) {
//start timer
start_time = System.currentTimeMillis();
//ask the question
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
System.out.println("Correct");
++question_number;
//generate a new question
//generate 2 random numbers
random_number1 = guess;
random_number2 = (int) ((Math.random() * max_range) + min_range);
//ask the question again
System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
//take in user input
guess = keyboard.nextInt();
}
end_time = System.currentTimeMillis();
int time_taken = (int) (end_time - start_time);
if (guess != (random_number1 + random_number2))
System.out.println("Wrong");
else {
System.out.println();
System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
}
}
}
You can use Random#nextInt to pick a random int from 0 to array.length - 1 which you can use as the index of an array of operators.
import java.util.Random;
public class Main {
public static void main(String[] args) {
char[] operators = { '+', '-', '*', '/' };
// Pick a random operator
Random random = new Random();
char op = operators[random.nextInt(operators.length)];
System.out.println(op);
}
}
A sample run:
/
I think for the random - and + characters you could use boolean like so:
Random rd = new Random(); // creating Random object
if(rd.nextBoolean()) {
//Do something
} else {
//Do Something else
}
For the enter, i think this is a game that is played in the console of the ide? Because then you can use a Scanner to track when enter is being pressed.
This will help you i think:
Java using scanner enter key pressed
The thing with the "Enter 'y' to start the game" is totally superfluous, as evidenced by the fact that you obviously don't have sensible things to do when the user does not enter 'y'.
So, since this is a command line application, why would anyone start it and then not want to play the game? Just go ahead and ask the first question! If the user did start that program by accident somehow, there will be no harm whatsoever, it's not that you're going to overwrite important files, start missiles or something like that.
You could try something like this.
Random r = new Random();
int[] signs = { 1, -1 };
char[] charSigns = { '+', '-' };
int a = r.nextInt(20);
int b = r.nextInt(20);
int sign = r.nextInt(2);
System.out.printf("%s %s %s = ?%n", a, charSigns[sign], b);
// then later.
System.out.printf("The answer is " + (a + signs[sign] * b));
In my code I have a variable, points, that increments based on the consanants and vowels in strings inputted. The method parseSentence is supposed to increase points per word but also ignore spaces.
I've tried running a debugger to see where the problem is but the debugger dies when it reaches the for loop in parseSentence. The method makes the point variable's value the word's point value instead of adding it to the variable. What could be causing this?
import java.util.*;
public class WordGolf1 {
public static int points = 1;
public static void main(String[] args) {
String Input;
System.out.println("Enter word: ");
Scanner sc = new Scanner(System.in);
Input = sc.nextLine();
System.out.println("Not enough points. " + (100 - points) + " needed.");
while (points < 100) {
System.out.println("Enter word: ");
Input = sc.nextLine();
parseSentence(Input);
System.out.println(points + ": points");
System.out.println("Not enough points. " + (100 - points) + " needed.");
}
boolean overshot = true;
Loop:
while (overshot = true) {
if (points == 100) {
overshot = false;
break Loop;
}
points = 100 - (points - 100);
System.out.println("Overshot by " + (points - 100) + " points.");
Input = sc.nextLine();
parseSentence(Input);
}
System.out.println("Congratulations you win!");
sc.close();
}
public static int parseSentence(String input) {
String[] pieces = input.split("\\s+");
for (int y = 0; y < pieces.length; y++) {
if (pieces.length > 1) {
if (y == 0) {
parseWord(input);
} else {
parseWord(input, y);
}
} else {
parseWord(input);
}
}
return points;
}
public static int parseWord(String input) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[0].length(); x++) {
if (charList.indexOf(pieces[0].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[0].charAt(x))
!= -1) {
pointsTemp++;
}
}
points = pointsTemp;
return points;
}
public static int parseWord(String input, int number) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[number].length(); x++) {
if (charList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp++;
}
}
points += pointsTemp;
return points;
}
}
You are not using the value returned by the parseSentence method.
Edit: I tried to rewrite this to be as close your original code with making the changes I feel where necessary.
Now Obviously your teacher has requirements and we can't go against that, but some points of interest you should keep in mind.
Multi Splitting
In your example you split the text to get the amount of words. Then instead of looping the already split text. You are sending the original input and then splitting it again. The "Double" splitting is why you needed "three" methods. If you don't double split you can simply loop the length from the single split and just use a single ParseWord method.
Deducting Values
In your example you take away 100 if the player overshot. The problem with this is let's say the person received a score like 200. Then it would loop twice to lower the value submitting the "You overshot message" twice. However let's say by some magical way a score of 100,000,000 was received. Then as you can see we would loop 1 million times to deduct this value essentially creating an not infinite but might as well be infinite loop.
To resolve this problem we simply do the below.
Value = Value % 100.
This will give us the remainder of our Value between 0 and 99. I.e. 167 will equal 67 and 12384 will be equal 84.
Using String (IndexOf)
What this does is takes the Character you provided and loop iterates over the String you provided. The worst case is 12 loops. There's also a lot of other stuff String and IndexOf do that is extra work and I recommend staying away from it if you can.
The alternative solution which I did is take the character and use " | 32" on it. I'm not going to go deep into how bits work, but basically these characters are 8 bit values but we only use 7 of it's bits ranging from 32 to 127. The amount of bits is like the power of 2. so 2^7 = 128 and 2^8 = 256. When we perform the "|" we are turning a bit on so if it's already on it won't change the value.
So in our example let's say we have the value 64.
This is bit 6 turned on. Now we want to turn on bit 5 "32" so the value becomes 96, but if we already had the value 96 and we turn bit 32 on it will still be 32.
Full List of ASCII Characters..
https://www.ascii-code.com/
The Game Loop
In your example you created "TWO" game loops the first one is when you start off, but once you overshot your score you enter the second loop and forget the first one. The problem is now your "Enter Words" and "You Undershot" code are never used anymore. So all someone will see is the line to enter text with no information on what to do or what occurred unless they overshot then they get the overshot message.
To fix this I made a single Game Loop which processes until the code ends via the SCORE == 100. You can see in the code that we begin every game loop with "Enter Words: " and parse the sentence. Then we add up our score and compare. If we undershot we simply restart the loop and try again. If we overshot we reduce the score and try again. If we succeeded we prompt the user if they would like to play again or end the game. Playing again will set the SCORE to 0 and start over the loop. Ending the game will "BREAK" the loop and cause it to end.
The Full Working Code With Recommended Changes
Feel free to comment if you need additional assistance.
import java.util.*;
public class WordGolf1
{
private static int SCORE = 0;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (true)
{
System.out.print("\n\nEnter word: ");
ParseSentence(sc.nextLine());
if (SCORE == 100)
{
System.out.print("\nYou Won! Would you like to play again: Y/N?");
if ((sc.nextLine().charAt(0) | 32) == 'y')
{
SCORE = 0;
System.out.print("\nResetting Game...");
} else {
break;
}
}
else
{
if (SCORE > 100)
{
int overshot = SCORE - 100;
SCORE = SCORE % 100;
System.out.print("\nYou Overshot By " + overshot + " Points. You now have " + SCORE + " points.");
} else {
System.out.print("\nYou currently have " + SCORE + " points you need " + (100 - SCORE) + " more.");
}
}
}
}
private static int ParseSentence(String input)
{
String[] split = input.split(" ");
for (Strng s : input)
SCORE += ParseWord(s);
}
private static int ParseWord(String word)
{
int value = 1;
for (int i = 0; i < word.length(); ++i)
{
int c = (int)word.charAt(i) | 32;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
value *= 2;
} else {
value += 1;
}
}
return value;
}
}
Why does the second while loop while (numberOfTries < 2) cancel both while loops? It runs perfect if there is no incorrect answer. But let's say I select 4 problems to be made, and I am only on the first problem. I give the incorrect answer 2 times so the program should say Incorrect two times and then give me a new question because while (numberOfTries < 2) should force it to break from that loop. But it doesn't, it just quits the whole thing. I know it has to be a logic issue, so what am I missing?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
numberOfTries is initialized outside of your loops. Once you try twice, it never gets set back to 0 which causes the loops to skip and finish on the next question because numberOfTries is already 2.
I am currently working on making a vocable test were you can make your own vocables and their translation. I have faced a problem were I do not know how to make an option were you have different translations to pick from.
public static void WritingYourVocables(List<VocableList> data) {
String antal = JOptionPane.showInputDialog(null, "Write the numbers of vocables you want to have");
int temp = Integer.parseInt(antal);
for (int i = 0; i < temp; i++) {
String Vocable = JOptionPane.showInputDialog(null, "Write a vocable");
String Translation = JOptionPane.showInputDialog(null, "Write the translation for the vocable");
data.add(new VocableTest(Vocable, Translation));
}
}//WritingYourVocables ends
The method above is the the method were you write the numbers of vocables you want to have in your test, then you write your vocables and their translation.
public static void PlayWithAlternatives(List<Alternatives> data) {
int a = data.size();
for (int n = 0; n < a; n++) {
int Translate2;
int Translate3;
int Translate1 = (int)(Math.random() * data.size()) ;
do {
Translate2 = (int)(Math.random() * data.size()) ;
}while (Translate1 == Translate2);
do{
Translate3 = (int)(Math.random() * data.size()) ;
}while (Translate1 == Translate3 || Translate2 == Translate3);
int answer [] = {Translate1, Translate2, Translate3};
int Right = (int)(Math.random() * 3) ;
int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "What is the translation of the vocable? " +
data.get(answer[Right]).getVocable() +
"\n1: " + data.get(Translate1).getTranslation() +
"\n2: " + data.get(Translate2).getTranslation() +
"\n3: " + data.get(Translate3).getTranslation()));
switch(choice){
case 1:
if (answer[Right] == Translate1){
data.remove(?);
JOptionPane.showMessageDialog(null, "Right");
}else{ JOptionPane.showMessageDialog(null, "Wrong");
}
break;
case 2:
if (answer[Right] == Translate2){
data.remove(?);
JOptionPane.showMessageDialog(null, "Right");
}else{ JOptionPane.showMessageDialog(null, "Wring");
}
break;
case 3:
if (answer[Right] == Translate3){
data.remove(?);
JOptionPane.showMessageDialog(null, "Right");
}else{ JOptionPane.showMessageDialog(null, "Wrong");
}
break;
default:
JOptionPane.showMessageDialog( null, "Wrong choice!");
}
}
}//PlayingWithAlternatives ends
The method above is a method for playing with different alternatives to the translation for a random generated vocable. If the player picks the right alternative, the vocable that the alternative is connected with is supposed to be deleted. To remove the vocable I use "data.remove()", the problem is that I do not know what to write in the brackets to remove the vocable.
Please help
There are better ways to handle your design but as far as your question is concerned just remove the vocable you asked in the first place.
data.remove(answer[Right]);
Remove elements from ArrayList :
You use :
arrlist.remove(index);
The parameter of List.remove is either the index of the thing you want to remove, or the object you want to remove.
It looks like Translate1, Translate2 and Translate3 are indexes into the list - so call
data.remove(Translate1); // or whichever variable is correct.
You can make life easier for yourself if you put your TranslateN variables in an array:
int[] Translate = new int[3];
So, replace every occurrence of Translate1 with Translate[0], Translate2 with Translate[1] etc.
Then, instead of the switch with almost identical handling of the 3 cases, you can simply use:
if (answer[Right] == Translate[choice-1]){
data.remove(Translate[choice-1]);
JOptionPane.showMessageDialog(null, "Right");
} else {
JOptionPane.showMessageDialog(null, "Wrong");
}
You should also watch out for the infinite loop in the code, when you have fewer than 3 choices left: you can't pick 3 different values for the Translate variables if there are only 2 possible values.
If you run the the game you can see that certain numbers the game cannot guess correctly. For example if your number is 13 the game will loop two times too many and will also guess your number as 12 instead of 13. I think this is an issue with the counting but I've tried tracing the loops repeatedly but cannot find the error. I think the issue mainly lies within my while loop.
//import statements
import java.util.Scanner;
public class Numbers
{
public static void binarySearch()
{
int position=0;
String answer;
int upper_BOUND=100;
int lower_BOUND=0;
Scanner input=new Scanner(System.in);
while( (lower_BOUND <= upper_BOUND))
{
position = (lower_BOUND + upper_BOUND) / 2;
System.out.println("Is your value greater than " + position + "?");
answer=input.next();
if((upper_BOUND-lower_BOUND<=1))
{
break;
}
if (answer.equals("no")) // If the number is > key, ..
{ // decrease position by one.
upper_BOUND = position --;
}
if(answer.equals("yes"))
{
lower_BOUND = position ++; // Else, increase position by one.
}
}
System.out.println("Is your number " + position + "?");
String answer2=input.next();
System.out.println(position+" is the answer.\n Thank you for playing the guessing game.");
//else
// System.out.println("Bruh pick a number from 1 to 100 ");
}
}
......
tester class
public class NumberGuesser
{
public static void main(String[] args)
{
int[ ] num = new int [100];
// Fill array
for (int i = 0; i <= 99; i++)
num[i]=i;
//The search method
Numbers.binarySearch();
}
}
Your issue should be with the increment that you do in "lower_BOUND = position ++; " here what happens is when you increment the position value, the "++" first increments and then assigns the value to position variable. The lowerbound is not actually assigned the incremented value of position but old value of positon. So please make a change to "lower_BOUND = ++ position ; "
Like below
if(answer.equals("yes"))
{
lower_BOUND = ++ position ; // Else, increase position by one.
}
And also my suggestion is to check your " if((upper_BOUND-lower_BOUND <= 1))" condition. I guess the condition should be like this " if((upper_BOUND-lower_BOUND == 0)) "
And please remove unused code in your "NumberGuesser" class, this will confuse people who are trying to answer your question.