traverse an array in GUI Java - java

I am doing a questionnaire with questions and written answers.
I need that when adding the answer, press the main button, tell me if it is correct or not and show me the other question of the array, until the array is finished. Here I upload the whole code.
mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i=0;i<question;i++) {
if(answer.getText()==(option[i])) {
message.setText("is correct");
corrects++;
}
else {
message.setText("incorrect");
}
};

You have the right idea, but you need to process the questions one at a time, not all at once inside the ActionListener.
One way to approach this is to keep track of the question outside of the action listener, in this example we use int questionCounter = 0; to keep track of the current question, then we can remove the for loop and process the questions one at a time. Here is a simple example of how it could work using your code, note how we reset the fields and add the next question every time the previous question is answered.
//Use a variable outside of the action listener to keep track of the current question:
int questionCounter = 0;
//Show first question in the text area:
area.setText(question[questionCounter]);
mainbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(answer.getText().equals(option[questionCounter])) {
message.setText("The previous answer was correct");
corrects++;
//Update the total each time you get one correct
correct_answers.setText("correct answers: "+corrects);
}
else {
message.setText("The previous answer was incorrect");
}
//Increment for the next question
questionCounter++;
//Check if there is another question, then show it
if (questionCounter < question.length){
answer.setText("");
area.setText(question[questionCounter]);
}
//Show the overall results if there are no more answers to check
else{
area.setText("Quiz complete, you got " + corrects + " out of " + question.length + " correct.");
}
};

Related

For loop runs through an ArrayList of objects and checks their names to display them in GUI but Error Message still shows up

I've decided to programm a search system for finding students and teachers in a school via GUI. It is an OOP and need some tweaking here and there, but there is one issue which doesn't seem logical to me. When I'm searching for a teacher, I have to type there name or surname into a JTextField and press the Search button which runs a method that loops through an ArrayList of teacher-objects and checks if their names match with the one in the Textfield. Then it checks if these teachers have multiple subjects and grades and it goes through nested if-statements. After the teacher is found, their information is displayed on a GUI with several Texfields. Theoretically if the name I typed into the TextField doesn't match one from the teacher objects, a Error Message should pop-up saying the teacher I'm looking for isn't in the system. But even though I type in the correct name and get all the information displayed, it sends me to the Error Message everytime. I tried to fix it with a break statement but that didn't work either. Can someone please help me with this.
Here is the code I'm talking about:
public void lehrerSuche()
{
String lehrername = tfSuchfeldLehrer.getText();
for(int i = 0; i < td.getFachliste(0).getListenLaengeLehrerListe();i++)
{
if(td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) || td.getFachliste(0).getLehrerliste(i).getNachname().equals(lehrername))
{
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() && td.getFachliste(0).getLehrerliste(i).isMehrereklassen())
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfKlasse_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlass2().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
tfFach_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach2().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() == false && td.getFachliste(0).getLehrerliste(i).isMehrereklassen())
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfKlasse_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlass2().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() && td.getFachliste(0).getLehrerliste(i).isMehrereklassen()==false)
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
tfFach_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach2().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() == false && td.getFachliste(0).getLehrerliste(i).isMehrereklassen()==false)
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
}
break;
}
else
{
switchPanels_3(panelErrorLehrer);
}
}
}
I've uploaded my project to GitHub. Methods and variables are written in German, so I'm really sorry if you can't understand what I have written. If u have questions please hit me up. I use Eclipse to code.
This link should direct you to my GitHub:
https://github.com/Gonzo-CR/Home-Projects.git
If the link doesn't work, look for Gonzo-CR on GitHub and check out my Home-projects repository where I uploaded all the files.
For better undestanding these are the Object oriented classes:
Person(Abstract)
Schueler
Lehrer
Fach
Schulklasse
Spezial
Sprecher
GUI classes:
Suchsystem
Testdaten(A class which generates all my objects)
The problem is likely that if td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) is not true the very first time the loop runs, switchPanels_3(panelErrorLehrer); will be triggered - regardless of whether the condition is met on a later iteration of the loop.
What you need is to check a sentinel value after the loop finishes - e.g.:
bool lehrerGefunden = false;
for(int i = 0; i < td.getFachliste(0).getListenLaengeLehrerListe();i++){
if(td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) || td.getFachliste(0).getLehrerliste(i).getNachname().equals(lehrername)){
//etc.
lehrerGefunden = true;
break;
}
}
if(!lehrerGefunden){
switchPanels_3(panelErrorLehrer);
}
That way, you check every entry in the list before deciding whether to show the error.

Method is called more than once from one ActionEvent

I'm trying to code a trivia based game with ActionEvent based buttons. I organized each specific event that is connected to JButton instances in a if-else structure and inside each of these structures, a method would be called. One of these methods would increment a variable that holds the number of the answers that are correct (cor) and wrong (inc):
public void compare(String sel , String ans)
{
//if correct
if(sel.compareToIgnoreCase(ans) == 0)
{
q.setText("Correct! 10 points added!");
score += 10;
cor++;
}
//if incorrect
else
{
q.setText("Incorrect! The correct answer was: " + ans);
inc++;
}
}
This set of code would be run from this:
public void actionPerformed(ActionEvent event)
{
if(e.equals("GUESS"))
{
userGuess = entry.getText();
answer = ans.get(currentQuestionIndex);
base.remove(entry);
base.remove(submit);
submit.setText("OK");
submit.setActionCommand("OK");
submit.addActionListener(this);
base.add(submit);
compare(userGuess, answer);
}
...
}
However, whenever the compare method is called, the inc and cor value seems to increment by an ambiguous value. For example, if I were to answer one question right, the new value for cor would be 2 instead of 1. When I answer another right, cor would be 5 instead of two. I tried using tracers in my code but so far, I appears that the program detects the actionEvent that runs compare() is being pressed multiple times, and as a result, it runs said code multiple times. How can I fix my code so that these variables can be incremented correctly by 1.
submit.addActionListener(this);
Don't add the ActionListener in the actionPerformed() method.
Each time the actionPerformed is invoked you add another listener, so when you click on the "Submit" button you have code that is executed multiple times.

Someone have a look at my source code for a number guessing game that seems to keep failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hello please may someone run my code and assist me in debugging it. I'm having a lot of troubles trying to figure it out and i have not a lot of guidance when it comes to coding.
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
reccomendations to fix it. Thanks in advance
a brief of what i'm trying to do:
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
import javax.swing.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
/*
number guessing game
the idea is that the computer will generate a random number and will ask the user if they know the number
if the user gets the answer correct they will get a congrats message and then the game will end but if the user
enters a wrong number they get a try again message and then they will try again
the problem with my code right now is that it runs certain parts twice. please annotate the issue and any
recomendations to fix it. Thanks in advance
*/
enterScreen();
if (enterScreen() == 0){
number();
userIn();
answer();
}
}
public static int enterScreen (){
String[] options = {"Ofcourse", "Not today"};
int front = JOptionPane.showOptionDialog(null,
"I'm thinking of a number between 0 and 100, can you guess what is is?",
"Welcome",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, options, "Yes" );
if(front == 0){
JOptionPane.showMessageDialog(null, "Goodluck then, you might need it. :D");
}
else {
JOptionPane.showMessageDialog(null, "okay i dont mind");
}
return front;
}
private static int number(){
double numD;
numD = (Math.random() * Math.random()) * 100;
int numI = (int) numD;
System.out.println(numD);
return numI;
}
private static int userIn(){
String userStr = JOptionPane.showInputDialog("What number do you think im thinking of?");
int user = Integer.parseInt(userStr);
return 0;
}
private static void answer(){
// here is the problem
if(userIn() == number()){
JOptionPane.showMessageDialog(null, "Well done! You must be a genius.");
}
else {
JOptionPane.showMessageDialog(null, "Shame, TRY AGAIN!");
userIn();
}
}
}
Your problem is this part:
enterScreen();
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You can leave out the first enterScreen(). Because you call it again in the if statement. If you look at the return type of the method: public static int, it returns and int. This makes it so that the outcome of the method is directly available in the if statement. The fist enterScreen is basicly useless, because you dont use the result.
You could do this:
int num = enterscreen();
if (num == 0) {
number();
userIn();
answer();
}
Which is basicly the same as:
if (enterScreen() == 0) {
number();
userIn();
answer();
}
You call enterScreen() twice. Just call it once, and compare the value returned only once.
Also, StackOverflow typically is not for "Here's my code, fix it" kind of not questions.
https://stackoverflow.com/help/how-to-ask
You call enterScreen() and userIn() functions twice or more. Please Computer Science and coding. Hint: Computer's execute intructions from top to bottom.

How can I make this program display a counter a different way?

So I understand how to make it so when a user presses a button, the count goes up, but how would I make it so it displays the amount of times the button has been pressed in a different way. For example, if the user pressed the button 3 times, it would say 123, instead of 3.
This is my current method with does it a conventional way,
public void actionPerformed(ActionEvent event) {
count++;
label.setText("Pushes: " + count);
}
So I'm thinking maybe I can make it so it loops through each posted value and displays that?
Initialise countStr globally, than on the button click append the count with StringBuilder like:
StringBuilder countStr= new StringBuilder();
public void actionPerformed(ActionEvent event) {
count++
countStr.append(count);
label.setText("Pushes: " +countStr);
}

How to write code that if something happens nothing else happens afterward?

Lets say if the last level of a game is beaten then you dont show a dialog box asking if the player wants to go on to the next level, but rather to the mainmenu. SO basically if something happens the things that are supposed to happen afterward dont.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
final ImageIcon pokeballIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\pokeball5.gif");
final ImageIcon pokemoneggIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\nidoking.gif");
final ImageIcon pokemonredIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\red.gif");
String userAnswer = answertextArea.getText().trim();
if (userAnswer.equalsIgnoreCase(answers.get(questionNumber))) {
answerLabel.setText("Correct");
levelScore ++;
triviagui.totalScore ++;
} else {
answerLabel.setText("Incorrect");
}
answertextArea.setText("");
questionNumber++;
if(questionNumber == questions.size()){
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores",JOptionPane.INFORMATION_MESSAGE, pokeballIcon );
if(difficulty == 3){
JOptionPane.showMessageDialog(null, "Good job you beat the game! \n Your total score was " + triviagui.totalScore + " out of 30.", "Thanks for playing!", JOptionPane.INFORMATION_MESSAGE, pokemonredIcon);
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
int leveloptionPane = JOptionPane.showConfirmDialog(null,"Would you like to go on to the next level?" , "Next Level?", JOptionPane.YES_NO_OPTION, levelScore, pokemoneggIcon);
if(leveloptionPane == JOptionPane.YES_OPTION){
difficulty++;
triviagui.questionFrame.setVisible(false);
triviagui.questionFrame=new QuestionFrame(difficulty);
triviagui.questionFrame.setVisible(true);
}
if(leveloptionPane == JOptionPane.NO_OPTION){
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
return;
}
updateQuestionScore();
}
You simply want to do:
if(something happens) {
return;
}
If you want to jump out from method use
return;
example of something like that:
public void myMethod(){
if(mynumber==5){
doThis();
}else{
return;
}
/*
*do something else <- this wont be executed if number doesnt equal 5
*cause we are already out of method.
*/
}
If you dont want to jump out from whole method bud only form part of it for instance loop.
break;
example of that:
public void myMethod(String[] stringArr){
for(String s:stringArr){
if(s.equals("hello")){
break; //get me out of this loop now !
}else{
s+="alriight";
}
}
}
doSomethingElse();//this will be executed even if you go thru break; you are still inside method dont forget.You are just out of loop
}
There are better uses for that maybe examples aint best bud you will understand how to use it form this:).
When you use break or return.In eclipse for instance you will be shown Where you actually exit. it will highlight "}"
There are several ways to do this:
You can return from a method.
You can break to exit a loop or continue to start the next iteration of the loop.
You can use an 'else' to only execute other code if the first section did not execute.
You can set a boolean flag variable and then check for that elsewhere in your code.
Depending on what you are trying to do each of these is sometimes the best way, sometimes not the best way.

Categories