Java: removing word from a list - java

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.

Related

Variable value not correctly increasing

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;
}
}

Converting parts of Strings to Character to be used in if/else statements

I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.

Number guessing game keeps repeating same questions and guesses incorrectly

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.

Having difficulty incrementing

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.

Counting the occurrences of a String in an ArrayList

I'm using an ArrayList to save the name, day and time of a show. My program requires me to output the number of shows that play on each day of the week. I've inputted 4 different shows, two of which are on the same day. So far, the only thing the output's given me is "On Thursday there are/is 2 show(s)." The other two didn't show. How can I make is so that it displays the number of shows for each day I've inputted? Here's my code for that:
String showDay = ((showInfo)show.get(0)).day.toString();
int totalShows = 0;
//print occurences for how many shows play each day
for (int i = 0; i < show.size(); i++) {
if (showDay.equals(((showInfo)show.get(i)).day.toString())) {
totalShows++;
}
}
System.out.println("On " + showDay + " there are/is " + totalShows + " show(s).");
}
Here's my code for the shows I input:
//input information
do{
showInfo temp = new showInfo();
System.out.print("Enter the name of show: ");
String showName = br.readLine();
temp.name = showName;
System.out.print("Enter which day of the week a new episode premieres: ");
String showDay = br.readLine();
temp.day = showDay;
System.out.print("Enter time in 24-hour format (e.g. 2100, 1900): ");
int showTime = Integer.valueOf(br.readLine()).intValue();
temp.time = showTime;
show.add(temp);
System.out.print("Would you like to add another show? (y/n) ");
}
while((br.readLine().compareTo("n")) != 0);
Keep in mind that I'm using Java 1.4. No other choice. By teacher's demand.
This is probably obvious, but I'm being oblivious right now. Any help would be great! Thanks in advance!
EDIT:
String showDay = ((showInfo)show.get(0)).day.toString();
if("sunday".equalsIgnoreCase(showDay)){
showdayCount[0]++;
System.out.println("There are/is " + showdayCount[0]++ + " show on Sunday.");
}else if("monday".equalsIgnoreCase(showDay)){
showdayCount[1]++;
System.out.println("There are/is " + showdayCount[1]++ + " show on Monday.");
}else if("tuesday".equalsIgnoreCase(showDay)){
showdayCount[2]++;
System.out.println("There are/is " + showdayCount[2]++ + " show on Tuesday.");
}else if("wednesday".equalsIgnoreCase(showDay)){
showdayCount[3]++;
System.out.println("There are/is " + showdayCount[3]++ + " show on Wednesday.");
}else if("thursday".equalsIgnoreCase(showDay)){
showdayCount[4]++;
System.out.println("There are/is " + showdayCount[4]++ + " show on Thursday.");
}else if("friday".equalsIgnoreCase(showDay)){
showdayCount[5]++;
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
}else if("saturday".equalsIgnoreCase(showDay)){
showdayCount[6]++;
System.out.println("There are/is " + showdayCount[6]++ + " show on Saturday.");
}
This is also only giving me one line. What am I doing wrong?! :(
EDIT:
What I want is to input name/day/time of a TV show, then later be able to display the amount of shows that are on that specific day!
For example, Big Bang Theory and Community are both on Thursday. So the code would output something like
There are 2 shows on Thursday.
Nothing's worked, so far.
You only get one day from this line:
String showDay = ((showInfo)show.get(0)).day.toString();
Here's my hack solution (may have some errors, like a misnamed variable but you should be able to fix it):
//Create a map that maps days to the shows that are on that day
LinkedHashMap showDays=new LinkedHashMap(); //String to Set map
String[] days={"Sunday","Monday", ....};//put the rest of the days in here
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
showDays.put(day,new HashSet());
}
//iterate through the shows and put them in their respective days in the map
for (int i = 0; i < show.size(); i++) {
String dayForShow=((showInfo)show.get(i)).day.toString();
showDays.get(dayForShow).put(show.get(i));
}
//now print out how many shows are on each day
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
int showsToday=showDays.get(day).size();
///do your print out now
}
You can make 'LinkedHashMap showDays' a class variable and add to it each time you add to show (and remove from it each time you remove from show).
PS. Tell your teacher it is no longer 2002, technology moves on and they make my job harder.
Create a Show class
public class Show {
String showName;
String showDay;
int showTime;
static int[] showdayCount = new int[7];
public Show(String showName, String, showDay, iny showTime){
this.showName = showName;
this.showDay = showDay;
this.showTime = showTime;
// increment showDayCOunt[] according to showDay from
switch(showDay){
case "Sunday": showDayCount[0]++; break;
case "Monday": showDayCount[1]++; break;
case "Tuesday": showDayCount[2]++; break;
case "Wednesday": showDayCount[3]++; break;
case "Thursday": showDayCount[4]++; break;
case "Friday": showDayCount[5]++; break;
case "Saturday": showDayCount[6]++; break;
}
}
}
Here's your main method from YourClass
public static void main(String[] args){
// Create Array of Shows
Show[] shosList = new Show[4]; // or how many ever shows you have
// Get your inputs for showName, showDay, showTime
Sting showName =
String showDay =
int showTime =
// Create show Object
Show show = new Show(showName, showDate, showTime);
// add show to ArrayList
showList[someIndex] = show;
// Do all other stuff then print
// when you print, you can get the showDayCount directly from the Show class
}
Now I don't want to do everything for you. I just want to get you headed in the right direction. Note that if you want the above to happen more than once, consider putting inside of a loop.
Edit: With getShowdayCount
Add this to my above Show class
public int getShowdayCount(String showday){
switch(showDay){
case "Sunday": return showDayCount[0]; break;
case "Monday": return showDayCount[1]; break;
case "Tuesday": return showDayCount[2]++; break;
case "Wednesday": return showDayCount[3]++; break;
case "Thursday": return showDayCount[4]++; break;
case "Friday": return showDayCount[5]++; break;
case "Saturday": return showDayCount[6]++; break;
}
}
Edit: With example if/else if from switch statement
// for main method inputs
if ("sunday"equalsIgnoreCase(showDay){
showdayCount[0]++
} else ("monday".equalsIgnoreCase(showDay){
showdayCount[1]++
} // finish if/else if statement
// for getShowdayCount method
if ("sunday"equalsIgnoreCase(showDay){
return showdayCount[0];
} else ("monday".equalsIgnoreCase(showDay){
return showdayCount[1];
} // finish if/else if statement
You can call it from your main class like this
show.getShowdayCount(show.showday);
Edit: Actually, Just put the above edit in you class with the main method
YourClassWithMainMethod{
static int[] showdayCount = new int[7];
public static void mina(String[] args){
// call getShowdayCount here
getShowdayCount(String showday);
}
public static int getShowdayCount(String showday){
}
}
Edit: What you do want and what you don't want
You dont need this in you if statement
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
When you want to print all the shows:
for (int i = 0; i < showdayCount.length; i++){
int showday;
if (i == 0){
showday = "Sunday
finish the if/else if statements
}
System.out.println("There is " + showDayCount[i] + " shows on " + showday);
}

Categories

Resources