Why isn't my JOptionPane.showMessageDialog working? - java

I'm a beginner programmer and I wrote this for my school class. But somehow even my JOptionPane.showMessageDialog under displaypay() won't work!!! I expect that a message box will pop up, but instead after I enter the amount of hours for each day, nothing happens! It doesn't even skip the part, the whole program just pauses! I am so confused! Instead if I use System.out.println(), it works fine.
Also I don't want to do System.out.println for the displaypay(), I have to use showMessageDialog.
package payroll.program;
import java.util.Scanner;
import javax.swing.JOptionPane; //imports
class Employee
{
int hourlypay;
int totalhours = 0;
String name; //variables
void getname()
{
Scanner scan = new Scanner(System.in);
System.out.println("What is this employee's name?");
name = scan.next(); //gets name
}
void calculatepay()
{
int[] hours = new int[5]; //creates array for hours
Scanner scan = new Scanner(System.in);
System.out.println("How much is " + name + " paid per hour?");
hourlypay = scan.nextInt(); //gets hourly pay
for (int i = 0; i < 5; i++)
{
System.out.println("How many hours did " + name + " work on day " + (i + 1) + "?");
hours[i] = scan.nextInt(); //gets hour on each day
totalhours = totalhours + hours[i]; //adds hours up
}
}
void displaypay()
{
JOptionPane.showMessageDialog(null, "You have to pay " + " $" + totalhours * hourlypay + " to " + name + "!"); //displays total pay
}
}
public class PayrollProgram {
public static void main(String[] args) {
int numberofemployees; //variable for # of employees
System.out.println("Welcome to the Payroll Program!"); //welcomes user
Scanner scan = new Scanner(System.in);
System.out.println("How many employees do you have?");
numberofemployees = scan.nextInt(); //gets input for # of employees
Employee[] ArrayofEmployees = new Employee[numberofemployees]; //creates array of employees with the same size as the number of employees
for (int i = 0; i < numberofemployees; i++)
{
ArrayofEmployees[i] = new Employee(); //creates an Employee for each space in the array
}
for (int i = 0; i < numberofemployees; i++)
{
ArrayofEmployees[i].getname();
ArrayofEmployees[i].calculatepay();
ArrayofEmployees[i].displaypay(); //runs functions in class Employee for each employee
}
}
}
This is my program and the JOptionPane.showMessageDialog doesn't work.
Please help!

When you try to display swing components, you are expected to do so from an event dispatching thread. Otherwise, you won't get reliable results. So, in this case, wrap all your code inside your main inside a call to SwingUtilities.invokeLater:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
int numberofemployees; //variable for # of employees
System.out.println("Welcome to the Payroll Program!"); //welcomes user
Scanner scan = new Scanner(System.in);
System.out.println("How many employees do you have?");
numberofemployees = scan.nextInt(); //gets input for # of employees
Employee[] ArrayofEmployees = new Employee[numberofemployees]; //creates array of employees with the same size as the number of employees
for (int i = 0; i < numberofemployees; i++) {
ArrayofEmployees[i] = new Employee(); //creates an Employee for each space in the array
}
for (int i = 0; i < numberofemployees; i++) {
ArrayofEmployees[i].getname();
ArrayofEmployees[i].calculatepay();
ArrayofEmployees[i].displaypay(); //runs functions in class Employee for each employee
}
}
});
}
More info can be found here: The Event Dispatch Thread.
In particular, notice what it says can happen if you fail to run Swing components from the event dispatcher thread:
Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

Related

How do I add randomly generated strings and integers to arrays while the code is running?

I'm trying to make a text-based business game, where you can hire and fire employees. Max there can be 5 employees, once strength is reached five, we may fire employees. I have written code to randomly generate details of a new applicant, but I am not able to save the hired employee. Can someone please guide?
package TestPackage;
import java.util.*;
public class EmployeeRandomizer {
/*this is where the employee's profile will be created and chosen by user. */
public static void main (String args[]) {
int spacesAvailable = 5;
int employeesHired = 0;
while(true) {
Random generate = new Random();
String[] name = {"John", "Marcus", "Susan", "Henry"};
int[] age = {20,21,22,23,24,25,25,26,26,27,28,29,30,20,21,22,23,24,25,25,26,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
String[] education = {"business", "accountant", "human resources","none"};
for(int i = 0; i < employeesHired; i++){
int index = (int)(Math.random() * 10);
System.out.println(name[index]+age[index]+education[index]);
}
System.out.println("name: " +name[generate.nextInt(4)]);
System.out.println("age: "+age[generate.nextInt(40)]);
System.out.println("education: " +education[generate.nextInt(4)]);
System.out.println("will you hire this person? (y/n)");
Scanner hire = new Scanner(System.in);
String hireEmployee = hire.next();
if(hireEmployee.equals("y")) {
System.out.println("you have hired a new employee!");
spacesAvailable = spacesAvailable-1;
employeesHired = employeesHired+1;
System.out.println("employees: " + employeesHired);
if(spacesAvailable>0 && employeesHired<5) {
System.out.println("There's " +spacesAvailable+" available spaces in your employee list.");
System.out.println("1. hire more employees");
System.out.println("2. view employees list");
Scanner hireMore = new Scanner(System.in);
String hireMoreAnswer =hireMore.next();
if (hireMoreAnswer.equals("1")) {
continue;
}
if (hireMoreAnswer.equals("2")) {
for(int i = 0; i < employeesHired;){
int index = (int)(Math.random() * 10);
System.out.println(name[index]);
System.out.println(age[index]);
System.out.println(education[index]);
break;
}
break;
}
}
if(spacesAvailable==0 || employeesHired==5) {
System.out.println("You have no more spaces left to hire more employees. (1 or 2?)");
System.out.println("1. Fire an employee (+1 space)");
System.out.println("2. Exit (more coming soon!)");
Scanner oneTwo = new Scanner(System.in);
String oneOrTwo = oneTwo.next();
if(oneOrTwo.equals("1")) {
}
if (oneOrTwo.contentEquals("2")) {
break;
}
}
}
if(hireEmployee.equals("n")) {
System.out.println("you have declined this application");
System.out.println("There's " +spacesAvailable+" available spaces in your employee list. Would you like to hire more employees? (y/n)");
Scanner hireMoreTwo = new Scanner(System.in);
String hireMoreAnswerTwo =hireMoreTwo.next();
if (hireMoreAnswerTwo.equals("y")) {
continue;
}
if (hireMoreAnswerTwo.equals("n")) {
break;
}
}
}
}
}

How to loop a prompt for a user to re-enter a number if they input a number outside of the parameters

I'm trying to set up a program where the user(student) inputs how many courses they have left to graduate and and how many classes the intend to take per terms and the program will form this data into an array and print out how many terms they have left. The user is not allowed to take more than 5 courses per term so I want to prompt the user that the number they input is incorrect while also looping that input for that specific student without have to close the console and re-run the program. I've tried placing a while(true){} loop there in order to loop it but i can't seem to get the loop i desire.
I've tried placing the while(true){} loop in multiple spots of the code and can't get the desired result.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[][] students = new int[10][2];
for (int i = 0; i < students.length; i++) {
System.out.println("Enter classes remaining and taking each term for student " + (i + 1) + ": ");
for (int j = 0; j < students[i].length; j++) {
students[i][j] = input.nextInt();
if (students[i][1] > 5)
System.out.println("The number of classes per term for student " + (i + 1) + " is invalid.");
}
}
System.out.println();
for (int i = 0; i < students.length; i++) {
System.out.println("Student " + (i + 1) + " has " + (int) Math.round(students[i][0] / students[i][1]) + " terms left to graduate.");
}
}
I expect the output for the first input to print","The number of class per term for student n is invalid." and repeat the prompt to enter the numbers for that same student n without proceeding to the next student input.
Here is the updated one based on your new comments. You should be good from here, make changes whatever you need.
public class StudentInfo
{
public static int totalStudents = 6;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[][] Students = new int[totalStudents][3];
// Student[i][0] will hold the Remaining classes.
// Student[i][1] will hold the Classes per semester and
// Student[i][2] will hold the number of total Semesters to complete all courses.
for (int i = 0; i < totalStudents; i++)
{
System.out.print("\n\nEnter the information for " + (i + 1) + "-th student.");
System.out.print("\n\nEnter the total number of remaining courses: ");
Students[i][0] = input.nextInt();
System.out.print("\nEnter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
while (Students[i][1] > 5)
{
System.out.println("\nStudents are not allowed to take more than 5 classes per semester.");
System.out.print("Enter the total number of courses per semester: ");
Students[i][1] = input.nextInt();
}
int ts = Students[i][0] / Students[i][1];
if (Students[i][0] % Students[i][1] != 0)
ts++;
Students[i][2] = ts;
System.out.println("\nThis student needs a total of " + ts + " semesters to finish all courses.");
}
input.close();
}
}
public static void main(String[] args) {
//scanner library
Scanner input = new Scanner (System.in);
//Initialize array
int[][] students = new int [10][2];
//iterate scanner and condition loop
for(int i=0; i<students.length; i++){
System.out.print("Enter classes remaining and taking each term for student "+ (i+1) +": ");
for (int j=0; j<students[i].length;j++){
students[i][j]= input.nextInt();
}
while(students [i][1] > 5) {
System.out.println("The number of classes per term for student " + (i+1) + " is invalid.");
i--;
break;
}
}
System.out.println();
//Print out results compiled from array
for(int i =0; i<students.length; i++) {
System.out.println("Student "+(i+1)+" has "+ (int) Math.ceil((double)students[i][0]/students[i][1]) + " terms left to graduate.");
}
}

JAVA Employee Type with Arrays

package javaapplication2;
import java.util.Scanner;
public class JavaApplication2
{
public static void main(String[] args)
{
person_type salespeople[] = new person_type [100];
person_type person = new person_type();
int counter = 0;
person.gross=0;
person.salary=0;
System.out.println("How many workers are there?");
Scanner number_of_workers = new Scanner(System.in);
counter=number_of_workers.nextInt();
for(int i=0; i<counter; i++)
{
salespeople[i] = person;
System.out.println(person.salary);
}
for(int i=0; i<counter; i++)
{
System.out.print("Enter the salary of the salesperson ");
System.out.print(i+1);
System.out.println(":");
Scanner salary = new Scanner(System.in);
salespeople[i].salary = salary.nextInt();
System.out.print("Enter the gross of the salesperson ");
System.out.print(i+1);
System.out.println(":");
Scanner gross = new Scanner(System.in);
salespeople[i].gross = gross.nextInt();
System.out.println("1---- " + salespeople[0].salary);
System.out.println(i);
}
System.out.println("First worker's salary is: " + salespeople[0].salary);
System.out.println("First worker's gross " + salespeople[0].gross);
System.out.println("Second worker's salary is: " + salespeople[1].salary);
System.out.println("Second worker's gross is: " + salespeople[1].gross);
}
private static class person_type
{
int salary;
int gross;
}
}
I am trying to put every employee stored to the array, but all the employees' details are overwritten by the very last one entered by the user. Can you please help? Thanks in advance!!
All the elements in the array refer to the same person_type instance :
for(int i=0; i<counter; i++)
{
salespeople[i] = person;
System.out.println(person.salary);
}
You must create a new person_type instance for each index of the array.
for(int i=0; i<counter; i++)
{
salespeople[i] = new person_type ();
}
BTW, I suggest you change your class name to either Person or PersonType to conform to Java naming conventions.

How do you incorperate an AVERAGE and LETTERGRADE in a java program which has 2D Array

I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)

Having trouble with array

I am currently trying to program a array based program. We have to make a employee class then a tester main class that holds a array of five user input employee names, salaries, and performance rating. The performance rating is used to determine a supplied raise amount. I have it basically done, but when i run the program, nothing happens even though java virtual machine is running. I have looked up and down for the error, anyone can point out what i am doing wrong?
Employee Class
public class Employee
{
private String employeeName;
private int salary;
private int performanceRating;
public Employee()
{
employeeName = "";
salary = 0;
performanceRating = 0;
}
public String getEmployeeName()
{
return employeeName;
}
public int getSalary()
{
return salary;
}
public int getPerformanceRating()
{
return performanceRating;
}
}
And this is the tester main class where the error comes in somewhere
import java.util.Scanner;
public class Tester
{
public static void main(String[] args)
{
Employee[] work = new Employee[5];
Scanner scanString = new Scanner(System.in);
Scanner scanInt = new Scanner(System.in);
String employeeName = "";
double salary = 0;
double performanceRating = 0;
String choice = scanString.nextLine();
while(choice.equals("yes"))
{
for(int i = 0; i < 5 ;i++)
{
System.out.println("What is the employee's name?");
employeeName = scanString.nextLine();
System.out.println("Enter Employee's salary");
salary = scanInt.nextInt();
System.out.println("Performance? 1 = excellent, 2 = good, 3 = poor");
performanceRating = scanInt.nextInt();
work[i] = new Employee();
}
for(int j = 0; j < 5; j ++)
if(work[j].getPerformanceRating() == 1)
{
salary = salary * 0.06;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 2)
{
salary = salary * 0.04;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating == 3)
{
salary = salary * 0.015;
System.out.println("Employee " + employeeName + " salary raised to " + salary);
}
else if(performanceRating < 5)
{
salary = salary;
System.out.println("Rating is off scale. No raise for emplyee " + employeeName);
}
System.out.println("Enter more employees? type 'yes' if you want to go again");
choice = scanString.nextLine();
}
System.out.println("Done");
}
}
The program reads from System.in. If you don't enter anything, nothing will happen.
Not sure why you have 2 Scanners instead of just one.
You have while(choice.equals("yes")) except you never prompt the user to make a choice. The program does do stuff (some of which may not all work properly), but you have to give the program input. What you can do is ask the user a question before the line String choice = scanString.nextLine();.
As a side note, you could use a switch in place of the if and else if's and it might be a little easier to read and understand.

Categories

Resources