No suitable constructor found for FacultyListFrame1 - java

I am working on a creating a simple GUI window to manage faculty list,
The error i have is :
--------------------Configuration: FacultyListFrame1 - JDK version 1.7.0_02 <Default> - <Default>--------------------
C:\Users\lm_b116\Documents\JCreator Pro\MyProjects\Myfaculty\FacultyListFrame1.java:175: error: no suitable constructor found for Faculty(String,Name,MyDate,boolean)
Facultylistframe[noOfFaculty++] = new Faculty(ssnS,new Name(firstName,lastName), new MyDate(month, day, year),selectedStatus);
^
constructor Faculty.Faculty(int,Name,MyDate,double,boolean) is not applicable
(actual and formal argument lists differ in length)
constructor Faculty.Faculty(int,Name,MyDate) is not applicable
(actual and formal argument lists differ in length)
Note: C:\Users\lm_b116\Documents\JCreator Pro\MyProjects\Myfaculty\FacultyListFrame1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
I would really appreciate any help,
The code for FacultyListFrame1 is :
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import java.awt.*;
public class FacultyListFrame1 extends JFrame {
private JButton store;
private JTextArea outputTextArea;
private JTextField fname, lname, dmonth, dday, dyear, ssalary,nssn,fstatus;
Faculty Facultylistframe[];
JComboBox statusSelection;
int noOfFaculty;
String[] status={"Fulltime","Parttime"};
public FacultyListFrame1(int num) {
super("Faculty List");
setLayout(new FlowLayout());
Facultylistframe = new Faculty[num];
noOfFaculty = 0;
JLabel jl1 = new JLabel("First Name:");
add(jl1);
fname = new JTextField(22);
add(fname);
JLabel jl2 = new JLabel("Last Name");
add(jl2);
lname = new JTextField(22);
add(lname);
JLabel jl7 = new JLabel("SSN:");
add(jl7);
nssn = new JTextField(20);
add(nssn);
JLabel jl8 = new JLabel("Salary:");
add(jl8);
ssalary = new JTextField(20);
add(ssalary);
JLabel jl9 = new JLabel("Status:");
add(jl9);
statusSelection= new JComboBox(status);
statusSelection.setMaximumRowCount(2);
add(statusSelection);
JLabel jl4 = new JLabel("Birthdate: MM");
add(jl4);
dmonth = new JTextField(3);
add(dmonth);
JLabel jl5 = new JLabel("DD");
add(jl5);
dday = new JTextField(3);
add(dday);
JLabel jl6 = new JLabel("Year");
add(jl6);
dyear = new JTextField(5);
add(dyear);
store = new JButton("Store Data");
store.addActionListener(new buttonEvent());
add(store);
outputTextArea = new JTextArea();
add(outputTextArea);
}
public static void main(String[] args) {
final int SIZEOFARRAY = 10;
FacultyListFrame1 plFrame = new FacultyListFrame1(SIZEOFARRAY);
plFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
plFrame.setSize(380, 500);
plFrame.setLocation(500, 200);
plFrame.setVisible(true);
}
private class buttonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() != store) return;
{
String firstName = fname.getText();
if (firstName.length() == 0) {
JOptionPane.showMessageDialog(null, "No first name",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String lastName = lname.getText();
if (lastName.length() == 0) {
JOptionPane.showMessageDialog(null, "No last name",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String ssnS = nssn.getText();
int ssn;
if (ssnS.length() == 0) ssn = -1;
else
try {
ssn = Integer.parseInt(ssnS);
} catch (NumberFormatException ne) { ssn = -1; }
if (ssn < 0) {
JOptionPane.showMessageDialog(null, "Invalid SSN",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String salaryS = ssalary.getText();
int salary;
if (salaryS.length() == 0) ssn = -1;
else
try {
salary = Integer.parseInt(ssnS);
} catch (NumberFormatException ne) { ssn = -1; }
if (salary < 0) {
JOptionPane.showMessageDialog(null, "Invalid Salary",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
String monthS = dmonth.getText();
int month, day, year;
try {
month = Integer.parseInt(monthS);
} catch (NumberFormatException ne) { month = 0; }
String dayS = dday.getText();
try {
day = Integer.parseInt(dayS);
} catch (NumberFormatException ne) { day = 0; }
String yearS = dyear.getText();
try {
year = Integer.parseInt(yearS);
} catch (NumberFormatException ne) { year = -1; }
int ret = MyDate.checkDate(month, day, year);
if (ret != 0) {
String t="";
switch (ret) {
case 1: t = "Month"; break;
case 2: t = "Day"; break;
case 3: t = "Year"; break;
}
JOptionPane.showMessageDialog(null, t + " is invalid",
"Warning", JOptionPane.WARNING_MESSAGE);
return;
}
fname.setText("");
lname.setText("");
nssn.setText("");
dmonth.setText("");
dday.setText("");
dyear.setText("");
ssalary.setText("");
int j=statusSelection.getSelectedIndex();
boolean selectedStatus=true;
if(j>0) selectedStatus=false;
if (noOfFaculty < Facultylistframe.length)
Facultylistframe[noOfFaculty++] = new Faculty(ssnS,new Name(firstName,lastName), new MyDate(month, day, year),selectedStatus);
else
JOptionPane.showMessageDialog(null, "Faculty List is full", "Warning", JOptionPane.WARNING_MESSAGE);
outputTextArea.setText("Last-Name\t First-Name\t SSN\t Salary\t Birth-Date\n");
for (int i=0; i<Facultylistframe.length; i++) {
if (Facultylistframe[i]!=null)
outputTextArea.append(Facultylistframe[i].toString() + "\n");
}
}
}
}
}
.......................................................................................
Sorry
here is the code for Faculty
public class Faculty extends Person{
private double salary;
private boolean fullTime;
public Faculty (int ssn, Name name, MyDate birth)
{
super(ssn, name, birth);
}
public Faculty (int ssn, Name name, MyDate birth, double salary, boolean f)
{
super(ssn, name, birth);
this.salary = salary;
fullTime = f;
}
public void setSalary (double salary)
{
this.salary = salary;
}
public double getSalary()
{
return salary;
}
public void setFullTime (boolean f)
{
fullTime = f;
}
public boolean getFullTime()
{
return fullTime;
}
public String toString()
{
String faculty = new String ("");
if (fullTime == false)
faculty = super.toString() + "\t" + salary + "\t part time ";
else
faculty = super.toString() + "\t" + salary + "\t full time ";
return faculty;
}
}

You are attempting to pass 4 arguments, but according to the error message, the constructors for Faculty expect either 3 or 5 arguments.
Either don't pass your selectedStatus variable to the constructor, to match Faculty(int,Name,MyDate), or include a double value before selectedStatus to match Faculty(int,Name,MyDate,double,boolean).
Another alternative: create the 4-argument constructor to match what you are attempting to call: Faculty(int,Name,MyDate,boolean).

Related

How to solve problem with list's constructor of static function in Java?

I have problem with putting values to my list in static switch. I have seen this can be easier done with String[] but for educational reasons please see my logical code to help me see where the problem is.
Bulding a String of this list is so easy, surely the problems is somewhere with filling my list with data but still can't see how to solve it.
When I try to print data nothing shows every time:(
package Loop2_hospital;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.util.stream.Stream;
public class Hospital {
public static void main(String[] args) {
List<Patient> listToDisplay = new ArrayList<>();
boolean exit = false;
Scanner in = new Scanner(System.in);
do {
System.out.println("0 - wyjście z programu, 1 - dopisanie pacjenta, 2 - wyświetlenie listy zapisanych pacjentów.");
int nr = in.nextInt();
isExit(listToDisplay, nr, exit);
} while (exit != true);
}
public static void isExit(List<Patient> listToDisplay, int nr, boolean exit) {
int actualPatientsNumber = 0;
int MaxPatientsAmount = 10;
Hospital ref3 = new Hospital();
Patient patient = new Patient();
switch (nr) {
case 0:
exit = true;
break;
case 1:
Scanner in2 = new Scanner(System.in);
System.out.println("Podaj imię pacjenta ");
String name = in2.nextLine();
System.out.println("Podaj nazwisko pacjenta");
String secondName = in2.nextLine();
System.out.println("Podaj PESEL pacjenta");
int PEELER = in2.nextInt();
if (actualPatientsNumber < MaxPatientsAmount){
actualPatientsNumber++;
Patient tmp = new Patient(name, secondName, PEELER);
listToDisplay.add((tmp));}
break;
case 2:
display(listToDisplay);
break;
default:
System.out.println("Podaj właściwy nr przy wyborze operacji");
break;
}
}
public static void display(List<Patient> listToDisplay) {
if(listToDisplay != null){
StringBuilder words = new StringBuilder();
for (Patient one : listToDisplay){
words.append(one);
}
System.out.println(words);
}
// final String d = listToDisplay.toString();
// System.out.println(d);
// Stream.of(listToDisplay).peek(System.out::println);
// System.out.println("Zapisani pacjenci: ");
// for (int i = 0; i < actualPatientsNumber; i++) {
// System.out.println(listToDisplay.get(i).getName() + " " + listToDisplay.get(i).getSecondName() + " nr PESEL: " + listToDisplay.get(i).getPEEL_NR());
}
}
package Loop2_hospital;
public class Patient {
String name;
String secondName;
int PEELER;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public int getPEEL_NR() {
return PEELER;
}
public void setPEEL_NR(int PEEL_NR) {
this.PEELER = PEEL_NR;
}
public Patient() {}
public Patient(String name, String secondName, int PEELER) {
this.name = name;
this.secondName = secondName;
this.PEELER = PEELER;
}
}
I tried following the suggestions given in the comments, but it's still not working.
package Loop2_hospital;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
public class Hospital {
public static void main(String[] args) {
List<Patient> listToDisplay = new ArrayList<>();
boolean exit = false;
Scanner in = new Scanner(System.in);
do {
System.out.println("0 - wyjście z programu, 1 - dopisanie pacjenta, 2 - wyświetlenie listy zapisanych pacjentów.");
int nr = in.nextInt();
if (!Objects.equals(nr, 0)){
isExit(listToDisplay, nr, exit);}
else exit = true;
} while (exit != true);
}
public static boolean isExit(List<Patient> listToDisplay, int nr, boolean exit) {
int actualPatientsNumber = 0;
int MaxPatientsAmount = 10;
Hospital ref3 = new Hospital();
Patient patient = new Patient();
switch (nr) {
case 0:
return true;
case 1:
Scanner in2 = new Scanner(System.in);
System.out.println("Podaj imię pacjenta ");
String name = in2.nextLine();
System.out.println("Podaj nazwisko pacjenta");
String secondName = in2.nextLine();
System.out.println("Podaj PESEL pacjenta");
int PEELER = in2.nextInt();
if (actualPatientsNumber < MaxPatientsAmount){
actualPatientsNumber++;
Patient tmp = new Patient(name, secondName, PEELER);
listToDisplay.add((tmp));}
break;
case 2:
display(listToDisplay);
break;
default:
System.out.println("Podaj właściwy nr przy wyborze operacji");
break;
}
return false;
}
public static void display(List<Patient> listToDisplay) {
if(listToDisplay != null){
StringBuilder words = new StringBuilder();
for (Patient one : listToDisplay){
words.append(one);
}
System.out.println(words);
}
// final String d = listToDisplay.toString();
// System.out.println(d);
// Stream.of(listToDisplay).peek(System.out::println);
// System.out.println("Zapisani pacjenci: ");
// for (int i = 0; i < actualPatientsNumber; i++) {
// System.out.println(listToDisplay.get(i).getName() + " " + listToDisplay.get(i).getSecondName() + " nr PESEL: " + listToDisplay.get(i).getPEEL_NR());
}
}

In Java, How do I access a stored string object in an arrayLIst?

import java.util.ArrayList;
public class Portfolio {
ArrayList<String> myportfolio = new ArrayList<>();
int portfolioSize;
int holding;
public Portfolio(){
}
public void addStockHolding(StockHolding mystock){
myportfolio.add(String.valueOf(mystock));
}
public int getSize(){
portfolioSize = myportfolio.size();
return portfolioSize;
}
public boolean isInPortfolio(String ticker){
String temp = myportfolio.toString();
if (temp.contains(ticker)) return true;
else return false;
}
public void delaStock(int stockArray){
// String temp = myportfolio.toString();
//int tickerloc = temp.indexOf(ticker);
//int dot = temp.indexOf('.', tickerloc);
//String stocksumm = temp.substring(tickerloc, dot+3);
//myportfolio.remove(stocksumm);
}
public int getstockShares(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int colon = temp.indexOf(':', tickerloc);
int boughtStr = temp.indexOf("bought", tickerloc);
String stockShares = temp.substring(colon+1, boughtStr-1);
stockShares = stockShares.trim();
int sharesOwned = Integer.parseInt(stockShares);
return sharesOwned;
}
public double getstockPrice(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int dsign = temp.indexOf('$', tickerloc);
int dot = temp.indexOf('.', tickerloc);
String orgPrice = temp.substring(dsign+1, dot+3);
orgPrice = orgPrice.trim();
double purchasePrice = Double.parseDouble(orgPrice);
return purchasePrice;
}
public int stockLength(String ticker){
String temp = myportfolio.toString();
int tickerloc = temp.indexOf(ticker);
int dot = temp.indexOf('.');
String stock = temp.substring(tickerloc, dot +2);
int stockloc = myportfolio.indexOf(stock);
return stockloc;
}
public String toString(){
String summary = (myportfolio.toString());
return summary;
}
}
public class StockHolding {
String ticker;
int numberShares;
double initialPrice;
double initialCost;
double currentValue;
double currentProfit;
double currentPrice;
public StockHolding(String ticker, int numberShares, double initialPrice){
this.ticker = ticker;
this.numberShares = numberShares;
this.initialPrice = initialPrice;
}
public String getTicker(String ticker){
return ticker;
}
double getInitialSharePrice(){
return initialPrice;
}
int getShares(){
return numberShares;
}
public double getCurrentSharePrice(){
return currentPrice;
}
public double getInitialCost(){
initialCost = numberShares * initialPrice;
return initialCost;
}
public double getCurrentValue(){
currentValue = numberShares * currentPrice ;
return currentValue;
}
public double getCurrentProfit(){
this.currentProfit = numberShares * (currentPrice - initialPrice);
return this.currentProfit;
}
public String toString(){
String summary = ("Stock " + ticker + ": " + numberShares + " bought at $ " + initialPrice + '\n');
return summary;
}
public void setCurrentSharePrice(double sharePrice){
currentPrice = sharePrice;
}
}
public class StockProject {
public static void main(String[] arg){
PortfolioAction transactions = new PortfolioAction();
}
}
public class Calculations {
private int haveShares;
private double pricePaid;
private String ticker;
private int num;
private int updShares;
private double price;
private double sale;
private Portfolio myportfolio;
private double priceDiff;
public Calculations(String ticker, int num, double price, Portfolio myportfolio){
this.ticker = ticker;
this.num = num;
this.price = price;
this.myportfolio = myportfolio;
}
public void setHaveShares() {
this.haveShares = myportfolio.getstockShares(ticker);
}
public int getHaveShares(){
return this.haveShares;
}
public void setPricePaid(){
pricePaid = myportfolio.getstockPrice(ticker);
}
public double getPricePaid(){
return this.pricePaid;
}
public void setSale(){
sale = num * price;
}
public double getSale(){
return sale;
}
public int getnumShares(){
return haveShares;
}
public void setUpdShares(){
this.updShares = haveShares - num;
}
public int getUpdShares(){
return this.updShares;
}
public void setPriceDiff(){
this.priceDiff = pricePaid - price;
}
public double getpriceDiff(){
this.priceDiff = pricePaid - price;
return this.priceDiff;
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
public class PortfolioAction {
private JLabel jlticker;
private JTextField jtenterTkr;
private JLabel jlnumShares;
private JTextField jtenterShares;
private JLabel jlPrice;
private JTextField jtenterPrice;
private JLabel jlLeft;
private JLabel jlCash;
private JLabel jlCashAmt;
private JLabel jlRight;
private JLabel butLeft;
private JButton jbsell;
private JButton jbbuy;
private JLabel butRight;
private JTextArea jtsummary;
Portfolio myportfolio = new Portfolio();
Account myaccount = new Account();
public PortfolioAction(){
Messages.getDisclaimer();
WidgetView wv = new WidgetView();
jlticker = new JLabel(" Stock Ticker "); //16
jtenterTkr = new JTextField(" "); //25
jlnumShares = new JLabel(" Number of Shares: "); //21
jtenterShares = new JTextField(" "); //25
jlPrice = new JLabel(" Price per Share: "); //21
jtenterPrice = new JTextField(" "); //25
jlLeft = new JLabel(" "); //65
jlCash = new JLabel(" Cash: $ "); //11
jlCashAmt = new JLabel(" 1000.00 " ); //11
jlRight = new JLabel(" "); //65
butLeft = new JLabel(" "); //60
jbsell = new JButton(" Sell ");
jbbuy = new JButton(" Buy ");
butRight = new JLabel(" ");
jtsummary = new JTextArea();
ButtonSell sellaction = new ButtonSell(jtenterTkr, jtenterShares, jtenterPrice, jlCashAmt, jtsummary);
ButtonBuy buyaction = new ButtonBuy(jtenterTkr, jtenterShares, jtenterPrice, jlCashAmt, jtsummary);
jbsell.addActionListener(sellaction);
jbbuy.addActionListener(buyaction);
wv.add(jlticker);
wv.add(jtenterTkr);
wv.add(jlnumShares);
wv.add(jtenterShares);
wv.add(jlPrice);
wv.add(jtenterPrice);
wv.add(jlLeft);
wv.add(jlCash);
wv.add(jlCashAmt);
wv.add(jlRight);
wv.add(butLeft);
wv.add(jbsell);
wv.add(jbbuy);
wv.add(butRight);
wv.add(jtsummary);
}
class ButtonSell extends WidgetViewActionEvent {
private JTextField enterTkr;
private JTextField enterShares;
private JTextField enterPrice;
private JLabel balance;
private JTextArea summary;
private boolean tkrLoc;
private int num;
private double price;
private String currBal;
private int previousShares;
private String ticker;
private double priceDiff;
private int haveShares;
private String salesummary;
public ButtonSell(JTextField jtenterTkr, JTextField jtenterShares, JTextField jtenterPrice, JLabel jlCashAmt, JTextArea jtSummary) {
enterTkr = jtenterTkr;
enterShares = jtenterShares;
enterPrice = jtenterPrice;
balance = jlCashAmt;
summary = jtsummary;
}
#Override
public void actionPerformed(ActionEvent e) {
this.ticker = enterTkr.getText();
this.ticker = ticker.trim();
try {
String numShares = enterShares.getText();
numShares = numShares.trim();
this.num = Integer.parseInt(numShares);
String getPrice = enterPrice.getText();
getPrice = getPrice.trim();
this.price = Double.parseDouble(getPrice);
String currBal = balance.getText();
this.currBal = currBal.trim();
}catch
(NumberFormatException ex) {
Messages.getNumErrMess();
}catch (NullPointerException ex){
Messages.getnotOwned();
}finally {
this.tkrLoc = myportfolio.isInPortfolio(ticker);
if (this.tkrLoc == false) {
Messages.getnotOwned();
} else{
Calculations sellStocks = new Calculations(ticker, num, price, myportfolio);
sellStocks.setHaveShares();
sellStocks.setPricePaid();
sellStocks.setUpdShares();
sellStocks.setPriceDiff();
sellStocks.setSale();
this.previousShares = sellStocks.getnumShares();
if(this.num > this.previousShares){
Messages.lowStockMsg();
balance.setText(currBal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
}else {
double sales = sellStocks.getSale();
myaccount.creditAccount(sales);
double newBal = myaccount.getBalance();
int holding = myportfolio.stockLength(ticker);
myportfolio.delaStock(holding);
int updShares = sellStocks.getUpdShares();
double pricePaid = sellStocks.getPricePaid();
StockHolding mystock = new StockHolding(ticker,updShares, pricePaid);
myportfolio.addStockHolding( mystock);
String bal = String.format("%.2f", newBal);
balance.setText(bal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
priceDiff = sellStocks.getpriceDiff();
haveShares = sellStocks.getHaveShares();
if (this.priceDiff < 0) {
double profit = priceDiff * haveShares* -1;
String hasProfit = String.format("%.2f" , profit);
salesummary = ("You made a profit of " + hasProfit);
} else if (this.priceDiff > 0) {
double loss = priceDiff * haveShares* -1;
String hasLoss = String.format("%.2f" , loss);
salesummary = ("You had a loss of " + hasLoss);
} else {
salesummary = "You have broke even.";
}
summary.setText(salesummary + '\n' + myportfolio.toString());
}
}
}
}
}
class ButtonBuy extends WidgetViewActionEvent {
private JTextField enterTkr;
private JTextField enterShares;
private JTextField enterPrice;
private JLabel balance;
private JTextArea summary;
public ButtonBuy(JTextField jtenterTkr, JTextField jtenterShares, JTextField jtenterPrice, JLabel jlCashAmt, JTextArea jtsummary) {
enterTkr = jtenterTkr;
enterShares = jtenterShares;
enterPrice = jtenterPrice;
balance = jlCashAmt;
summary = jtsummary;
}
#Override
public void actionPerformed(ActionEvent e) {
String ticker = enterTkr.getText();
ticker = ticker.trim();
try {
String numShares = enterShares.getText();
numShares = numShares.trim();
int num = Integer.parseInt(numShares);
String getPrice = enterPrice.getText();
getPrice = getPrice.trim();
double price = Double.parseDouble(getPrice);
double availCash = Double.parseDouble(balance.getText());
if ((price * num) > availCash) {
Messages.getMoneyMess();
}
else {
StockHolding mystock = new StockHolding(ticker, num, price);
myportfolio.addStockHolding(mystock);
double cost = mystock.getInitialCost();
myaccount.debitAccount(cost);
double newBal = myaccount.getBalance();
String bal = String.format("%.2f", newBal);
balance.setText(bal);
enterTkr.setText(" "); //25
enterShares.setText(" "); //25
enterPrice.setText(" "); //25
summary.setText(myportfolio.toString());
}
}
catch (NumberFormatException ex) {
Messages.getNumErrMess();
}
}
}
}
import javax.swing.JOptionPane;
public class Messages {
static String notEnuffFunds = "Transaction denied: Not enough Funds";
static String errNum = "Error: Number of Shares and Share price must be numbers only";
static String warn = "Warning";
static String noStock = "Stock not available to sell.";
static String disclaim = "Disclaimer";
static String disclosure = "This program is for entertainment purposes only. The account on this program does not represent" +
" any money in the real world nor does this predict any profit or loss on stocks you purchase in the real world.";
static String lowStock = "Not that meaning stock to sell";
public Messages(){
}
public static void getNumErrMess(){
JOptionPane.showMessageDialog(null, errNum, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getMoneyMess(){
JOptionPane.showMessageDialog(null, notEnuffFunds, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getnotOwned(){
JOptionPane.showMessageDialog(null, noStock, warn, JOptionPane.WARNING_MESSAGE);
}
public static void getDisclaimer(){
JOptionPane.showMessageDialog(null, disclosure, disclaim, JOptionPane.INFORMATION_MESSAGE);
}
public static void lowStockMsg(){
JOptionPane.showMessageDialog(null, lowStock, warn, JOptionPane.WARNING_MESSAGE);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A really simple class to display Swing widgets in a FlowLayout GUI.
* <p>
*
* #author parks
*/
public class WidgetView {
public static final int DEFAULT_X_SIZE = 600;
public static final int DEFAULT_Y_SIZE = 400;
private JFrame jframe;
private JPanel anchor;
private boolean userClicked = false;
private Lock lock;
private Condition waitingForUser;
private JComponent userInputComponent = null;
private ActionListener eventHandler;
/**
* Default constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a default size.
*/
public WidgetView() {
this(DEFAULT_X_SIZE, DEFAULT_Y_SIZE);
}
/**
* Constructor will display an empty JFrame that has a Flow layout
* JPanel as its content pane and initialize the frame to a given size.
*/
public WidgetView(int pixelSizeInX, int pixelSizeInY) {
lock = new ReentrantLock();
waitingForUser = lock.newCondition();
// lambda expression requires Java 8
// eventHandler = e -> {
// if (e.getSource() != userInputComponent) {
// return;
// }
// lock.lock();
// userClicked = true;
// waitingForUser.signalAll();
// lock.unlock();
// };
//* java 7 solution
eventHandler = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() != userInputComponent) {
return;
}
lock.lock();
userClicked = true;
waitingForUser.signalAll();
lock.unlock();
}
};
jframe = new JFrame();
anchor = new JPanel();
jframe.setContentPane(anchor);
jframe.setSize(pixelSizeInX, pixelSizeInY);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
/**
* Add a Swing widget to the GUI.
*
* #param jcomp Swing widget (subclasses of JComponent--like JLabel and
* JTextField) to be added to the JFrame
*/
public void add(JComponent jcomp) {
anchor.add(jcomp);
jframe.setContentPane(anchor);
}
/**
* Add an Abstract Button (like a JButton) to the JFrame. Create an action
* listener to wait (suspend the caller) until it is clicked.
*
* #param absButton Button (like a JButton) to add to the JFrame
*/
public void addAndWait(AbstractButton absButton) {
userInputComponent = absButton;
absButton.addActionListener(eventHandler);
addWait(absButton);
}
/**
* Add a JTextField to the JFrame, and wait for the user to put the cursor
* in the field and click Enter. The caller is suspended until enter is
* clicked.
*
* #param jTextField Field to add to the JFrame
*/
public void addAndWait(JTextField jTextField) {
userInputComponent = jTextField;
jTextField.addActionListener(eventHandler);
addWait(jTextField);
}
private void addWait(JComponent jcomp) {
add(jcomp);
lock.lock();
try {
while (!userClicked) {
waitingForUser.await();
}
}
catch (InterruptedException e1) {
System.err.println("WidgetView reports that something really bad just happened");
e1.printStackTrace();
System.exit(0);
}
userClicked = false;
waitingForUser.signalAll();
lock.unlock();
}
}
import java.awt.event.ActionListener;
public abstract class WidgetViewActionEvent implements ActionListener {
}
public class Account {
double availableBalance = 1000.00;
public Account(){
}
public void debitAccount(double cost){
availableBalance -= cost;
}
public void creditAccount(double sale){
availableBalance += sale;
}
public double getBalance (){
return availableBalance;
}
}
I am working on a school project; a program that has the user enter a sticker, number of stocks and the price. then they have the option to buy and sell. The problem I am having is that say they bought 6 shares of IBM at 34.45 and want to sell 4 of them; I want to update the stock in the portfolio. I figured I would need to delete the original stock bought and put in the remaining stock as a new StockHolding. The problem is how do I find the index of the String in the arrayList of Portfolio to delete the old now out-dated StockHolding? The project has a Calculation class, a portfolioAction class, Messages class, and Account class, with the use of a WidgetView class that was supplied by the teacher. It is my first semester of Java. Thanks for any help.
updated: all the classes for the program are there now. The instructor wanted the inclusion of certain classes. We have not done hash maps and can only use the materials we have covered to this point. So I apologize.
: Output window for sell
I do not get any error messages; I am using IntelliJ IDEA. My problem is in the screenshot. It gives me the update stock but doesn't delete the old one. I have tried index of methods and am just stuck. But all the classes are here and it runs without error. Thank you again and sorry this is so lengthy.
To find the index of the string based on categories..
Try to use this below method:
private ArrayList<String> _categories;
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
To replace the old value in array list use set:
Instead of removing,
_categories.set( your_index, your_item )
Hope it helps.
your code is a bit long without specifications or sample output. But to find and change the stock you could use
myportfolio.set(indexOf(oldStock), newStock)

Can't seem to get it to write to an arrayList and then to a file

I have been working on this and can't seem to get it to run correctly. It should create an arraylist then add, remove, mark as loaned, mark as returned, and write to a file when you quit. I can't find what I messed up.
package cs1181proj1;
import static cs1181proj1.Media.media;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* #author Veteran
*/
public class CS1181Proj1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Create ArrayList and mediaFile.
ArrayList<Media> Item = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
File mediaFile = new File("mediaFile.dat");
String Title;
String Format;
String loanedTo = null;
String dateLoaned = null;
int number = 0;
if (mediaFile.exists()) {
try {
try (ObjectInputStream dos = new ObjectInputStream(
new FileInputStream(mediaFile))) {
Item = (ArrayList<Media>) dos.readObject();
}
} catch (FileNotFoundException a) {
System.out.println("Thou hast erred! The file doth not exist!");
} catch (IOException b) {
System.out.println("GIGO My Lord or Lady!");
} catch (ClassNotFoundException c) {
System.out.println("Avast! I am in a quandry");
}
}
//Print out menu of choices
while (number != 6) {
System.out.println("");
System.out.println("1. Add new media item");
System.out.println("2. Mark an item out on loan");
System.out.println("3. Mark an item as Returned");
System.out.println("4. List items in collection");
System.out.println("5. Remove a media item");
System.out.println("6. Quit");
System.out.println("");
//accept users menu choice
try {
number = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.println("That's not a number between 1 and ` `6. IS IT!");
}
//Switch to tell program what method to use depending on user ` `//option
switch (number) {
case 1:
insert();
break;
case 2:
onLoan();
break;
case 3:
returned();
break;
case 4:
list();
break;
case 5:
removeItem();
break;
case 6:
System.out.println("Goodbye");
Quit(mediaFile);
break;
}
}
}
//Method for inserting items in arraylist
public static void insert() {
ArrayList<Media> media = new ArrayList<>();
System.out.println("New titles name");
Scanner newEntry = new Scanner(System.in);
String title = newEntry.nextLine();
System.out.println("");
//title of media
while (titleAlreadyExists(title, media)) {
System.out.println("Title already exists");
title = newEntry.nextLine();
System.out.println("");
}
//format of media
System.out.println("What format");
String format = newEntry.nextLine();
media.add(new Media(title, format));
System.out.println("Your entry has been created.");
}
//In case entry already exists
public static boolean titleAlreadyExists(
String title, ArrayList<Media> media) {
for (Media entry : media) {
if (entry.getTitle().equals(title)) {
return true;
}
}
return false;
}
//Method for putting item on loan
public static void onLoan() {
System.out.println("Enter name of Title on loan");
Scanner newLoan = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String loanTitle = newLoan.nextLine();
System.out.println("Who did you loan this to");
Scanner To = new Scanner(System.in);
String loanedTo = To.nextLine();
System.out.println("");
System.out.println("When was it lent out?");
Scanner date = new Scanner(System.in);
String dateLoaned = date.nextLine();
System.out.println("");
for (Media title : media) {
if (title.getTitle().equals(loanTitle)) {
title.setDateLoaned(dateLoaned);
title.setloanedTo(loanedTo);
System.out.println(title + " loaned to " + loanedTo + ` `"on date" + dateLoaned + "is listed as loaned");
}
}
}
//Method for returning item in collection
public static void returned() {
System.out.println("Enter name of Title returned");
Scanner returned = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String returnedTitle = returned.nextLine();
String loanedTo = null;
String dateLoaned = null;
System.out.println("");
for (Media title : media) {
if (title.getTitle().equals(returnedTitle)) {
title.setDateLoaned(dateLoaned);
title.setloanedTo(loanedTo);
System.out.println(title + "is listed as returned");
}
}
}
//Method for listing items in collection
public static void list() {
System.out.println("Your collection contains:");
for (int i = 0; i < media.size(); i++) {
System.out.print((media.get(i)).toString());
System.out.println("");
}
}
//method for removing an item from the collection
private static void removeItem() {
System.out.println("What item do you want to remove?");
Scanner remover = new Scanner(System.in);
ArrayList<Media> media = new ArrayList<>();
String removeTitle = remover.nextLine();
System.out.println("");
media.stream().filter((title) -> ` ` (title.getTitle().equals(removeTitle))).forEach((title) -> {
media.remove(removeTitle);
System.out.println(title + "has been removed");
});
}
//method for saving to file when the user quits the program.
//To ensure there is no data loss.
public static void Quit(File mediaFile) {
try {
ArrayList<Media> media = new ArrayList<>();
try (ObjectOutputStream oos = new ObjectOutputStream(new ` ` FileOutputStream(mediaFile))) {
oos.writeObject(media);
System.out.println("Your file has been saved.");
}
} catch (IOException e) {
System.out.println("Unable to write to file. Data not ` `saved");
}
}
}
Here is its companion media file:
package cs1181proj1;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
/**
*
* #author Veteran
*/
public class Media implements Serializable {
static ArrayList<String> media = new ArrayList<>();
private String Title;
private String Format;
private String loanedTo = null;
private String dateLoaned = null;
Media() {
this.Title = ("Incorrect");
this.Format = ("Incorrect");
this.loanedTo = ("Available");
this.dateLoaned = ("Available");
}
Media(String Title, String Format) {
this.Title = Title;
this.Format = Format;
this.loanedTo = ("Available");
this.dateLoaned = ("Available");
}
//Get and Set Title
public String getTitle() {
return this.Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
//Get and Set Format
public String getFormat() {
return this.Format;
}
public void setFormat(String Format) {
this.Format = Format;
}
//Get and Set loanedTo
public String getLoanedTo() {
return this.loanedTo;
}
public void setloanedTo (String loanedTo){
this.loanedTo = loanedTo;
}
//Get and set dateLoaned
public String getDateLoaned() {
return this.dateLoaned;
}
public void setDateLoaned(String dateLoaned){
this.dateLoaned = dateLoaned;
}
#Override
public String toString(){
return this.Title + ", " + this.Format +", " + this.loanedTo + ", "
+ this.dateLoaned;
}
public static Comparator <Media> TitleComparator = new Comparator <Media>(){
#Override
public int compare(Media t, Media t1) {
String title = t.getTitle().toUpperCase();
String title1 = t1.getTitle().toUpperCase();
return title.compareTo(title1);
}
};
}

Using ObservaleList to add element into ListView

I am having the problem with adding an array to ObservableList the use it to add that array into ListView. When I compiled, I got NullPointerException. This exception occurs when I call the listAllItems() method. If I do not use the GUI control, instead of using switch-statement and letting the user choose the option, then there are no exception occur at the run time. Could someone help me figure out what happen? Thanks
Requirement
Create a LibraryGUI class
◦ This class should have a Library object as one of its fields. In the LibraryGUI constructor
you will need to call the library constructor method to initialize this field and then call its
open() method to read in the items from the data file.
◦ Use a JList to display the contents of the library. Use the setListData method of the JList
class together with the listAllItems method of the Library class to keep the list current with
the library contents.
import javax.swing.JOptionPane;
public class MediaItem {
/*Fields*/
private String title;
private String format;
private boolean onLoan;
private String loanedTo;
private String dateLoaned;
/*Default Constructor - Initialize string variables for null and boolean variable for false*/
public MediaItem()
{
title = null;
format = null;
onLoan = false;
loanedTo = null;
dateLoaned = null;
}
/*Parameterized Constructor*/
public MediaItem(String title, String format)
{
this.title = title;
this.format = format;
this.onLoan = false;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public boolean isOnLoan() {
return onLoan;
}
public void setOnLoan(boolean onLoan) {
this.onLoan = onLoan;
}
public String getLoanedTo() {
return loanedTo;
}
public void setLoanedTo(String loanedTo) {
this.loanedTo = loanedTo;
}
public String getDateLoaned() {
return dateLoaned;
}
public void setDateLoaned(String dateLoaned) {
this.dateLoaned = dateLoaned;
}
/*Mark item on loan*/
void markOnLoan(String name, String date){
if(onLoan == true)
JOptionPane.showMessageDialog(null,this.title + " is already loaned out to " + this.loanedTo + " on " + this.dateLoaned);
else {
onLoan = true;
loanedTo = name;
dateLoaned = date;
}
}
/*Mark item return*/
void markReturned(){
if(onLoan == false)
JOptionPane.showMessageDialog(null, this.title + " is not currently loaned out");
onLoan = false;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javafx.scene.control.TextInputDialog;
public class Library extends MediaItem {
/*Fields*/
private ArrayList<MediaItem> itemsList = new ArrayList<>();
public ArrayList<MediaItem> getItemsList() {
return itemsList;
}
public void setItemsList(ArrayList<MediaItem> itemsList) {
this.itemsList = itemsList;
}
public int displayMenu()
{
Scanner input = new Scanner(System.in);
System.out.println("\nMenu Options \n"
+"\n1. Add new item\n"
+"\n2. Mark an item as on loan\n"
+"\n3. List all item\n"
+"\n4. Mark an item as returned\n"
+"\n5. Quit\n"
+"\n\nWhat would you like to do?\n");
int choices = input.nextInt();
while (choices < 1 || choices >5)
{
System.out.println("I'm sorry, " + choices + " is invalid option");
System.out.println("Please choose another option");
choices = input.nextInt();
}
return (choices);
}
public void addNewItem(String title, String format)
{
MediaItem item = new MediaItem(); // the object of item
/*Use the JOptionPane.showInputDialog(null,prompt) to let the user input the title and the format
* store the title and the format to the strings and pass it to the parameter of addNewItem(String, String) method
* title and format will go through the loop if title already exited let the user input another title and format
* Using the same method JOptionPan.ShowInputDialog and JOptionPane.showMessage()
*/
boolean matches = false;
for(int i = 0; i< itemsList.size(); i++){
if(title.equals(itemsList.get(i).getTitle())){
String newTitle = JOptionPane.showInputDialog(null, "this " + title + " already exited. Please enter the title again");
String newFormat = JOptionPane.showInputDialog(null, "Enter the format again");
item = new MediaItem(newTitle,newFormat);
itemsList.add(item);
matches = true;
}
}if(!matches){
item = new MediaItem(title,format);
itemsList.add(item);
}
}
public void markItemOnLoan(String title, String name, String date)
{
boolean matches = false;
for(int i = 0; i < itemsList.size(); i++)
{ if (title.equals(itemsList.get(i).getTitle()))
{
itemsList.get(i).markOnLoan(name,date);
matches = true;
}
}
if (!matches)
{
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
}
public String[] listAllItems()
{
String[] list = new String[itemsList.size()];
for (int n = 0; n < itemsList.size(); n++)
{
if(itemsList.get(n).isOnLoan() == true)
list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + " ) loaned to " + itemsList.get(n).getLoanedTo() + " on " + itemsList.get(n).getDateLoaned();
else
list[n] = itemsList.get(n).getTitle() + " (" + itemsList.get(n).getFormat() + ")";
if(list[n] == null){
String title = "title ";
String format = "format ";
String loanTo = "name ";
String date = "date ";
list[n] = title + format + loanTo + date;
}
}
return list;
}
public void markItemReturned(String title)
{
boolean matches = false;
for( int i = 0; i < itemsList.size(); i++)
{
if(title.equals(itemsList.get(i).getTitle()))
{
matches = true;
itemsList.get(i).markReturned();
}
}
if(!matches)
{
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
}
public void deleteItem(String title){
boolean matches = false;
for(int i = 0; i < itemsList.size(); i++){
if(title.equals(itemsList.get(i).getTitle())){
itemsList.get(i).setTitle(null);
itemsList.get(i).setFormat(null);
itemsList.get(i).setDateLoaned(null);
itemsList.get(i).setLoanedTo(null);
itemsList.get(i).setOnLoan(false);
}
}
if(!matches)
JOptionPane.showMessageDialog(null,"I am sorry. I couldn't find " + title + " in the library");
}
public void openFile(){
Scanner input = null;
try{
input = new Scanner(new File("library.txt"));
Scanner dataInput = null;
MediaItem item = new MediaItem();
int index = 0;
String title = " ";
String format = " ";
String date = " ";
String onLoanTo = " ";
Boolean onLoan = false;
Boolean checkString= false;
Boolean checkBoolean = false;
itemsList = new ArrayList<>();
while(input.hasNextLine()){
dataInput = new Scanner(input.nextLine());
dataInput.useDelimiter("-");
while(input.hasNext()){
Boolean dataBoolean = dataInput.nextBoolean();
String dataString = dataInput.next();
if(index == 0){
item.setTitle(dataString);
title = item.getTitle();
checkString = true;
}else if(index == 1){
item.setFormat(dataString);
format = item.getFormat();
checkString= true;
}else if(index == 2){
item.setOnLoan(dataBoolean);
checkBoolean = true;
}else if(index == 3){
item.setLoanedTo(dataString);
checkString = true;
}else if(index == 4){
item.setDateLoaned(dataString);
checkString = true;
}else {
if(checkString == false)
throw new Exception("Invalid data " + dataString);
if(checkBoolean == false)
throw new Exception("Invalid data " + dataBoolean);
}
index++;
itemsList.add(new MediaItem(title,format));
}
index = 0;
title = " ";
format = " ";
date = " ";
onLoan = false;
onLoanTo = " ";
checkString= false;
checkBoolean = false;
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}finally{
if(input != null){
try{
input.close();
}catch(NullPointerException ex){
JOptionPane.showMessageDialog(null,"Error: File can not be closed");
}
}
}
}
public void saveFile(){
PrintWriter output = null;
try{
output = new PrintWriter(new File("library.txt"));
for(int i = 0; i < itemsList.size(); i++){
output.println(itemsList.get(i).getTitle() + "-" + itemsList.get(i).getFormat()+ "-" + itemsList.get(i).isOnLoan() + "-"
+ itemsList.get(i).getLoanedTo() + "-" + itemsList.get(i).getDateLoaned());
}
}catch(FileNotFoundException e1){
JOptionPane.showMessageDialog(null,"Could not find the data file. Program is exiting.");
}catch(IOException e2){
JOptionPane.showMessageDialog(null, "Something went wrong with writing to the data file.");
}catch(Exception e3){
JOptionPane.showMessageDialog(null,"Something went wrong.");
}
finally{
if( output != null){
try{
output.close();
System.exit(0);
}catch (NullPointerException e4){
JOptionPane.showMessageDialog(null, "Error: File can not be closed");
}
}
}
}
}
enter code here
import java.util.ArrayList;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
public class LibraryGUI extends Application{
private ListView<String> listView;
private Library library;
private Button btAdd, btCheckIn, btCheckOut, btDelete;
public void LibraryGUI(){
library = new Library();
library.openFile();
}
public void start(Stage primaryStage) throws Exception {
listView = new ListView<>();
//Add all item in the listAllItem() method to the list view
String[] list = library.listAllItems();
int length = library.getItemsList().size();
for (int i = 0; i < length; i++)
{
ObservableList<String> element = FXCollections.observableArrayList( list[i].toString());
listView.setItems(element);
}
listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
btAdd = new Button(" Add");
btCheckIn = new Button(" CheckIn ");
btCheckOut = new Button(" CheckOut ");
btDelete = new Button(" Delete ");
FlowPane flowP = new FlowPane();
listView.setPrefSize(400, 275);
btAdd.setPrefSize(100, 25);
btAdd.setAlignment(Pos.BOTTOM_LEFT);
btCheckIn.setPrefSize(100, 25);
btCheckIn.setAlignment(Pos.BOTTOM_LEFT);
btCheckOut.setPrefSize(100, 25);
btCheckOut.setAlignment(Pos.BOTTOM_LEFT);
btDelete.setPrefSize(100,25);
btDelete.setAlignment(Pos.BOTTOM_LEFT);
flowP.getChildren().addAll(listView,btAdd,btCheckIn,btCheckOut,btDelete);
Scene scene = new Scene (flowP,400,300);
primaryStage.setTitle("Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Code for Switch-Statement
import java.util.Scanner;
public class Code8 {
public static void main(String[] args) {
MediaItem newItem = new MediaItem();
Library library = new Library();
Scanner in = new Scanner(System.in);
int option = 0;
while (option != 5)
{
option = library.displayMenu();
switch(option)
{
case 1:
System.out.print("What is the title? ");
String newTitle = in.nextLine();
newItem.setTitle(newTitle);
System.out.println("What is the format? ");
String newFormat = in.nextLine();
newItem.setFormat(newFormat);
library.addNewItem(newTitle, newFormat);
break;
case 2:
System.out.println("Which item (enter the title)? ");
newTitle = in.nextLine();
newItem.setTitle(newTitle);
System.out.println("Who are you loaning it to? ");
String name = in.nextLine();
newItem.setLoanedTo(name);
System.out.println("When did you loan it to them? ");
String date = in.nextLine();
library.markItemOnLoan(newTitle, name, date);
break;
case 3:
String[] list = library.listAllItems();
int length = library.getItemsList().size();
for (int i = 0; i < length; i++)
{
System.out.println(list[i].toString());
}
break;
case 4:
System.out.println("Which item (enter the title)? ");
newTitle = in.nextLine();
newItem.setTitle(newTitle);
library.markItemReturned(newTitle);
break;
case 5:
System.out.println("Goodbye");
break;
}// switch statement
}//while statement
} //main method
}

Why is my quizzcount doubling its value

I'm having a problem with this code in that the quizzcount variable is not outputting the correct value, it doubles the value.
I found a work around by diving the quizzcount by 2 and it works but i would really like to figure out why its doubling the value.
So for example, without dividing quizzcount by 2, if the user gets 7 out of the 10 questions correct the messagedialog will display that the user got 14 out of 10 correct.
What is causing this?
Thanks guys, any help would be appreciated.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.*;
import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.Image;
import java.lang.*;
public class MathFiles extends JFrame implements ActionListener
{
private ObjectOutputStream toFile;
private String name;
private boolean open;
private static String response;
private static int menuOption = 0;
private static int numberOfMaths = 0;
private FileInputStream fis;
private ObjectInputStream fromFile;
Math aMath = null;
private int quizcount =0;
String checkbutton = "";
private static int tracker =1;
int count = 0;
int fimage =0;
JRadioButton questA, questB, questC, questD, questE;
ButtonGroup questGroup;
JPanel questPanel;
JLabel question;
JPanel questionPanel;
JTextField resultText;
JLabel resultLabl;
JPanel resultPanel;
JButton nextButton;
JPanel quizPanel;
ImageIcon image;
JLabel imageLabl;
JPanel imagePanel;
JTextArea questionText;
JScrollPane scrollPane;
Random rand;
/** #param fileName is the desired name for the binary file. */
public MathFiles()
{
setTitle( "Math Quiz Competition" );
rand = new Random();
toFile = null;
//tracker = rand.nextInt(5)+1;
tracker = 1;
name = "Quiz"+tracker+".txt";
open = false;
//openFile(); //Use only when creating file
//writeMathsToTextFile(name);
setLayout( new FlowLayout() );
inputFile();
beginquiz();
showquestions();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // end MathFiles constructor
/** Writes all Maths from a text file and writes them to a binary file.
#param fileName the text file */
public void writeMathsToTextFile(String fileName)
{
Scanner inputFile = null;
Math nextMath = null;
String question_num;
String question;
String answera;
String answerb;
String answerc;
String answerd;
String answer_cor;
String file_name;
String SENTINEL ="DONE";
try
{
inputFile = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Text file " + fileName + " not found.");
System.exit(0);
}
Scanner keyboard = new Scanner(System.in);
System.out.print("Question number: ");
question_num = keyboard.nextLine();
while (!question_num.equalsIgnoreCase(SENTINEL))
{
System.out.print("Question: ");
question = keyboard.nextLine();
System.out.print("Answer A: ");
answera = keyboard.nextLine();
System.out.print("Answer B: ");
answerb = keyboard.nextLine();
System.out.print("Answer C: ");
answerc = keyboard.nextLine();
System.out.print("Answer D: ");
answerd = keyboard.nextLine();
fimage = rand.nextInt(30)+1;
file_name = "image"+fimage+".gif";
System.out.print(file_name);
System.out.print("Correct Answer: ");
answer_cor = keyboard.nextLine();
nextMath = new Math(question_num, question, answera, answerb,
answerc, answerd, answer_cor, file_name);
writeAnObject(nextMath);
numberOfMaths++;
System.out.print("\nQuestion number: ");
question_num = keyboard.nextLine();
} // end while
System.out.println("successfully created = " + name);
} // end readMathsFromTextFile
/** Opens the binary file for output. */
public void openFile()
{
try
{
FileOutputStream fos = new FileOutputStream(name);
toFile = new ObjectOutputStream(fos);
open = true;
}
catch (FileNotFoundException e)
{
System.out.println("Cannot find, create, or open the file " + name);
System.out.println(e.getMessage());
open = false;
}
catch (IOException e)
{
System.out.println("Error opening the file " + name);
System.out.println(e.getMessage());
open = false;
}
//System.out.println("successfully opened = " + name);
} // end openFile
/** Writes the given object to the binary file. */
public void writeAnObject(Serializable anObject)
{
try
{
if (open)
toFile.writeObject(anObject);
}
catch (InvalidClassException e)
{
System.out.println("Serialization problem in writeAnObject.");
System.out.println(e.getMessage());
System.exit(0);
}
catch (IOException e)
{
System.out.println("Error writing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end writeAnObject
public void result()
{
System.out.println("Your score is");
}
public void inputFile()
{
try
{
fromFile = new ObjectInputStream(new FileInputStream(name));
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end displayFile
/** Closes the binary file. */
public void closeFile()
{
System.out.println("closed name = " + name);
try
{
toFile.close();
open = false;
}
catch (IOException e)
{
System.out.println("Error closing the file " + name);
System.out.println(e.getMessage());
System.exit(0);
}
} // end closeFile
/** #return the fileís name as a string */
public String getName()
{
return name;
} // end getName
/** #return true if the file is open */
public boolean isOpen()
{
return open;
} // end isOpen
public void beginquiz()
{
try
{
aMath = (Math)fromFile.readObject();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error reading input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
}
void showquestions()
{
//question group
/*question = new JLabel();
question.setText(aMath.getquestion());
question.setFont(new Font("Arial", Font.BOLD, 20));
question.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.add( question );*/
questionText = new JTextArea(5,20);
questionText.setWrapStyleWord(true);
questionText.setLineWrap(true);
questionText.setText(aMath.getquestion());
questionText.setFont(new Font("Arial", Font.BOLD, 20));
questionText.setForeground(Color.BLUE);
questionPanel = new JPanel();
questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.PAGE_AXIS));
questionPanel.add( questionText );
// quest group
questA = new JRadioButton(aMath.getanswera(), false );
questB = new JRadioButton(aMath.getanswerb(), false );
questC = new JRadioButton(aMath.getanswerc(), false );
questD = new JRadioButton(aMath.getanswerd(), false );
questGroup = new ButtonGroup();
questGroup.add( questA );
questGroup.add( questB );
questGroup.add( questC );
questGroup.add( questD );
questPanel = new JPanel();
questPanel.setLayout( new BoxLayout( questPanel, BoxLayout.Y_AXIS ) );
questPanel.add( new JLabel("Choose the Correct Answer") );
questPanel.add( questA );
questPanel.add( questB );
questPanel.add( questC );
questPanel.add( questD );
// result panel
//resultText = new JTextField(20);
//resultText.setEditable( false );
//resultLabl = new JLabel("Result");
//resultPanel = new JPanel();
//resultPanel.add( resultLabl );
//resultPanel.add( resultText );
//button
nextButton = new JButton("Next");
quizPanel = new JPanel();
quizPanel.add(nextButton);
//Image image1 = new ImageIcon("image/image1.gif").getImage();
image = new ImageIcon("image1.gif");
imageLabl=new JLabel(image);
imagePanel = new JPanel();
imagePanel.add(imageLabl);
// frame: use default layout manager
add( imagePanel);
add( questionPanel);
add( questPanel);
//add( resultPanel);
questA.setActionCommand(aMath.getanswera());
questB.setActionCommand(aMath.getanswerb());
questC.setActionCommand(aMath.getanswerc());
questD.setActionCommand(aMath.getanswerd());
questA.addActionListener(this);
questB.addActionListener(this);
questC.addActionListener(this);
questD.addActionListener(this);
nextButton.setActionCommand( "next" ); // set the command
// register the buttonDemo frame
// as the listener for both Buttons.
nextButton.addActionListener( this );
add(quizPanel);
}
public void actionPerformed( ActionEvent evt)
{
//evt.getActionCommand() = aMath.getanswer_cor();
if (questA.isSelected()&&
aMath.getanswera().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questB.isSelected()&&
aMath.getanswerb().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questC.isSelected()&&
aMath.getanswerc().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if (questD.isSelected()&&
aMath.getanswerd().equalsIgnoreCase(aMath.getanswer_cor().trim()))
quizcount++;
if(questA.isSelected() || questB.isSelected() || questC.isSelected() || questD.isSelected())
if ( evt.getActionCommand().equals( "next" ))
{
try
{
aMath = (Math)fromFile.readObject();
questionText.setText(aMath.getquestion());
questA.setText(aMath.getanswera());
questB.setText(aMath.getanswerb());
questC.setText(aMath.getanswerc());
questD.setText(aMath.getanswerd());
imageLabl.setIcon(new ImageIcon(aMath.getfile()));
questGroup.clearSelection();
repaint();
}
catch (ClassNotFoundException e)
{
System.out.println("The class Math is not found.");
System.out.println(e.getMessage());
System.exit(0);
}
catch(StreamCorruptedException e)
{
System.out.println("Error in input stream: " + name);
System.out.println(e.getMessage());
System.exit(0);
}
catch(IOException e)
{
if (count<=0)
count = 0;
else
count--;
JOptionPane.showMessageDialog(null,"Your score is "+quizcount/2 +" out of 10");
try{
Thread.sleep(2000);
System.exit(0);
}catch (InterruptedException em) { }
}
}
}
public static void main ( String[] args )
{
MathFiles mat = new MathFiles();
mat.setSize( 450, 550 );
mat.setLocationRelativeTo(null);
mat.setResizable( false );
mat.setVisible( true );
}
} // end MathFiles
class Math implements java.io.Serializable
{
private String question_num;
private String question;
private String answera;
private String answerb;
private String answerc;
private String answerd;
private String answer_cor;
private String file_name;
public Math(String quesno, String quest, String ansa, String ansb, String ansc,
String ansd, String ans_cor, String file)
{
question_num = quesno;
question = quest;
answera = ansa;
answerb = ansb;
answerc = ansc;
answerd = ansd;
answer_cor = ans_cor;
file_name = file;
}
public void setquestion(String lName)
{
question = lName;
} // end setquestion
public void setquestion_num(String fName)
{
question_num = fName;
} // end setquestion_num
public void setanswera(String add)
{
answera = add;
} // end setanswera
public void setanswerb(String cty)
{
answerb = cty;
} // end setanswerb
public void setanswerc(String st)
{
answerc = st;
} // end setanswerc
public void setanswerd(String z)
{
answerd = z;
} // end setanswerd
public void setanswer_cor(String phn)
{
answer_cor = phn;
} // end setanswer_corr
public String getquestion_num()
{
return question_num;
} // end getquestion_num
/** #return the question */
public String getquestion()
{
return question;
} // end getquestion
/** #return the answera*/
public String getanswera()
{
return answera;
} // end getanswera
/** #return the answerb */
public String getanswerb()
{
return answerb;
} // end getanswerb
public String getanswerc()
{
return answerc;
} // end getanswerc
public String getanswerd()
{
return answerd;
} // end getanswerd
public String getanswer_cor()
{
return answer_cor;
} // end getanswer_corr
public String getfile()
{
return file_name;
} // end getanswer_corr
/** #return the Math information */
public String toString()
{
String myMath = getquestion_num() + " " + getquestion() + "\n";
myMath += getanswera() + "\n";
myMath += getanswerb() + " " + getanswerc() + " " + getanswerd() + "\n";
myMath += getanswer_cor() + "\n";
myMath += getfile() + "\n";
return myMath;
} // end toString
} // end Math
It looks like your problem is that you've registered ActionListeners on the radio buttons. This means the event fires when you select an answer as well as clicking the 'next' button. With that in mind it should be obvious why your score is doubling itself.
As far as I can tell you don't need ActionListeners for the radio buttons. You should only be checking the answer when the user has indicated they are done with their selection. That the score is exactly doubling itself also suggests that you basically haven't tested the program besides naively selecting a radio button and clicking 'next'. Before commenting out the lines where you add the listeners to the radio buttons, try changing your answer. Open the program, select the correct answer, then select an incorrect answer, then select the correct answer again and click 'next'. See what happens.
This kind of error can also be easily found with a debugger. Just insert a breakpoint inside actionPerformed and it will be obvious it's being called by more than one action.

Categories