Error checking if statements - java

I am doing some practice work by expanding on a homework project I recently wrote. This is not for a grade, but I want to add some error checking to my code.
The program requires you to enter a name, select from a dropdown, select from a listbox and to select a radio button. My goal is to populate an error messagebox if any of the required items is blank.
The code I have so far for the error checking is below, but Im not sure how to take the individual lacking item and populate that to the message box since all of the error checking is in a single "if" statement.
Error checking code:
// Listener to handle the print button.
class ButtonListener implements ActionListener
{
ButtonListener() {}
public void actionPerformed(ActionEvent e)
{
JFrame frame1 = new JFrame("Show Message Dialog");
// Checks for required entries
if (error == 0 || name == "" || flag == 0)
{
JOptionPane.showMessageDialog(frame1,
"You must complete the form: " + missing, "ERROR",
JOptionPane.ERROR_MESSAGE);
}
else
{
// Get values from fields
setText();
System.out.println("Passenger's Name: " + name + "\n");
System.out.println("Age Group: " + ageValue + "\n");
for (int i = 0; i < value.length; i++)
{
System.out.println("Destination: " + value[i] + "\n");
}
System.out.println("Departure Day: " + day + "\n");
}
}
}
Thanks!

It looks like they can actually have multiple things wrong, so why only show one? I'm normally a C# dev so I'm not going to try to get the syntax right on typing this myself, but here's the concept:
Create a collection of some sort, like a list of strings.
Make 3 if statements, one for each of those errors, and put the field
names in for each one that fails. if (name.isEmpty()) {
errorList.Add("name"); }
Check to see if the count of items in the list is greater than 0. If
it is throw your error and put the name of the bad fields from the
collection into the string that you generate.

Related

Need help removing item from ArrayList

Im attempting to remove an object form an array list but if fails everytime.
Im using a function to add and a seperate one to remove. The add function is working but the remove is not. I cant see where it is going wrong and failing.
public void unregister( Basics classToRemove){
if(checkIsRegistered(classToRemove)){
getClassList().remove(classToRemove);
System.out.println(getClassList().remove(classToRemove));
System.out.println("You have unregistered from " + classToRemove.className + " class.");
setTotalTuition();
} else{
System.out.println("\nYou are not currently registered for " + classToRemove.className + " class.\n");
}
}
public void register(Basics classToAdd){
if(!checkIsRegistered(classToAdd)){
getClassList().add(classToAdd);
System.out.println("You have registered for " + classToAdd.className + " class.");
setTotalTuition();
}else{
System.out.println("\nYou are already registered for " + classToAdd.className + " class.\n");
}
}
I have attempted using this.arrayList to remove the object and using getters to get the object and remove it.
You can not just print a class-object with System.out.printline. I assume you want to print the attributes of the class, however you are printing the memory address of the object.
Additionally, this doesn't make sense to me:
getClassList().remove(classToRemove);
System.out.println(getClassList().remove(classToRemove));
You can't access and print an Object you just removed.
If this is not helpful, consider providing a minimal example and explaining what exactly is not working.

Print to the console while user is typing

In Java, when you print to the console while a user is typing. It will destroy what is being typed. Let's say I have a server set up, and you can run commands from the server. Then this is what it might look like.
I'm trClient connected to server
ying to typMessage received from client
e a command
Is there a way to get around this? To have the text be printed on the line above the user is typing on. If you've ever ran a Minecraft server, you might know what I'm talking about. It would look something like this.
Since Minecraft is made using Java, I know that this is possible, but I haven't been able to figure out a way to do it.
Maybe you could do it like this.
You have one while loop with a value of true.
Everything that the user enters is entered in the ArrayList and every time the user enters something that list is printed.
If you want it to print only the entered message, you can empty it each time you print the list.
There you could use LinkedList where when you drag all the variables from the list, it remains empty.
If you want to use a library that gives terminal support, you can use com.googlecode.lanterna for your own terminal where you can set where you want to show the inputs given by the user. You can add the dependency to your program:
<!-- https://mvnrepository.com/artifact/com.googlecode.lanterna/lanterna -->
<dependency>
<groupId>com.googlecode.lanterna</groupId>
<artifactId>lanterna</artifactId>
<version>3.1.1</version>
</dependency>
You can use the Terminal of this library and do such manual positioning of input and printed test like the way you want the interface.
Have a our on this page and browse more to gather knowledge on lanterna.
I've added a very basic code for reading input and showing that on the gui:
public static void main(String[] args) {
try {
int row = 5, col = 5;
Terminal terminal = new DefaultTerminalFactory().createTerminal();
Screen screen = new TerminalScreen(terminal);
TextGraphics tg = screen.newTextGraphics();
screen.startScreen();
KeyStroke key;
List<Character> string = new ArrayList<>();
while (true) {
System.out.println("reading input");
key = terminal.readInput();
if (key != null && key.getCharacter() != null) {
System.out.println("Key not null: " + key.getCharacter());
// you can add more keypress checks, they have a lot of enums for this
if (key.getKeyType() == KeyType.Enter) {
String str = string.stream().map(String::valueOf).collect(Collectors.joining());
System.out.println(col + " " + row + " " + str);
tg.putString(col, row, str);
string.clear();
} else if (key.getKeyType() == KeyType.Escape) {
break;
} else {
string.add(key.getCharacter());
}
} else {
System.out.println("Null input");
break;
}
screen.refresh();
}
screen.stopScreen();
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}

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.

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.

How to print a set of for-looped arrays in a JOptionPane?

This was my original code to print out the information entered into the program, it was designed to create a nice little table displaying tutor names on the left with their pay on the right, and the total pay of all at the bottom:
System.out.println("Tutor Stipend Report");
System.out.println("Tutors\t\tPay");
System.out.println("------\t\t---");
for(int out=0;out<numOfTutors;out++) {
System.out.println(names[out]+"\t\t"+stipend[out]);
}
System.out.println("--------");
System.out.println("Total: " +sum);
Now I need to turn this code to display in JOptionPane and here is where I am stuck. I want to keep the same table setup as before but every time I go to display the information, lets say I need to display 3 tutors, it will just come up with 3 JOptionPane dialog boxes instead of printing the 3 tutors in one dialog box.
I realize the problem is because all the information is inside the for loop, but how do I resolve this issue so I can display the designated number of tutors and pay on one dialog box like I had with the System.out.println solution?
for (int out=0;out<numOfTutors;out++) {
JOptionPane.showMessageDialog(null,
"Tutor Stipend Report" +
"\nTutors Pay" +
"\n--------- -----" +
"\n"+names[out]+" "+stipend[out] +
"\n--------" +
"\nTotal: " +sum);
}
You need to move the call to JOptionPane.showMessageDialog outside of the for-loop.
Check out StringBuilder. It's helpful for this sort of thing:
StringBuilder sb = new StringBuilder();
sb.append("There are ").append(count).append(" people in the following list:\n");
for (int i = 0; i < count; i++) {
sb.append("Person #").append(count).append('\n');
}
JOptionPane.showMessageDialog(null, sb.toString());
The problem is since you're calling JOptionPane.showMessageDialog inside the loop, it will execute 3 times. What you should do instead is concatenating the string you want to print into one string object like this:
String toBeDisplayed = "";
for(int out=0;out<numOfTutors;out++) {
toBeDisplayed += /*.. add your string here.. */;
}
JOptionPane.showMessageDialog(null, toBeDisplayed);
Note that cocatenating string using += is not the most efficient thing to do -- consider using StringBuilder / StringBuffer

Categories