"String cannot be converted to Component" in JOptionPane - java

Keep getting a "String cannot be converted to Component" in the last JOptionPane
My apologies for the awful looking format. I know using switch is much easier, this is just an assignment for my Java class. Any and all suggestions welcomed. Thankyou
import javax.swing.JOptionPane;
import java.util.*;
import java.text.*;
import java.lang.String;
public class Project4A
{
public static void main(String[] args)
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
Scanner sc = new Scanner(System.in);
double dcostBagel = 2.00; //Variables
double dcostDonut = 1.50;
double dcostCrois = 3.00;
double dcostLatte = 1.50;
double dcostCoffee = 1.25;
double dcostMilk = 1.00;
double dcostTea = 0.50;
double dfoodChoiceCost;
double dbevChoiceCost;
double dtotDue;
double dtotCost;
int ichoiceFood;
int ichoiceBev;
int inumOrdered;
String choiceFood;
String choiceBev;
String finChoiceFood;
String finChoiceBev;
//Prompts
choiceFood = JOptionPane.showInputDialog("Welcome to BeBe's Best BreakfastnChoose a Breakfast Item:n1: Bagel # "+formatter.format(dcostBagel) + "n2: Donut # "+formatter.format(dcostDonut) + "n3: Croissant # "+formatter.format(dcostCrois));
ichoiceFood = Integer.parseInt(choiceFood);
choiceBev = JOptionPane.showInputDialog("Choose one of the following beverages:nEnter:n1: Latte # "+formatter.format(dcostLatte)+"n2: Coffee # "+formatter.format(dcostCoffee)+"n3: Milk # "+formatter.format(dcostMilk)+"n4: Tea # "+formatter.format(dcostTea));
ichoiceBev = Integer.parseInt(choiceBev);
//If Elses for Food
if(ichoiceFood == 1)
{
finChoiceFood = "Bagel";
dfoodChoiceCost = dcostBagel;
}
else if(ichoiceFood == 2)
{
finChoiceFood = "Donut";
dfoodChoiceCost = dcostDonut;
}
else
{
finChoiceFood = "Croissant";
dfoodChoiceCost = dcostCrois;
}
//If Elses for Beverages
if(ichoiceBev == 1)
{
finChoiceBev = "Latte";
dbevChoiceCost = dcostLatte;
}
else if(ichoiceBev == 2)
{
finChoiceBev = "Coffee";
dbevChoiceCost = dcostCoffee;
}
else if(ichoiceBev == 3)
{
finChoiceBev = "Milk";
dbevChoiceCost = dcostMilk;
}
else
{
finChoiceBev = "Tea";
dbevChoiceCost = dcostTea;
}
/
//Retreive num ordered
System.out.println("How many items would you like?(1 to 20");
inumOrdered = sc.nextInt();
//Calculations
dtotCost = dbevChoiceCost + dfoodChoiceCost;
dtotDue = dtotCost * inumOrdered;
//Integer.toString(inumOrdered);
//Final Output
JOptionPane.showMessageDialog("Breakfast ordered:n"+finChoiceFood+" # "+formatter.format(dfoodChoiceCost)+"nnBeverage ordered:n"+finChoiceBev+" # "+formatter.format(dbevChoiceCost)+"nnTotal cost: "+formatter.format(dtotCost)+"nNumber ordered: "+inumOrdered,"Your Bill");
}
}

Your code is not matching any method signatures of the showMethodDialogue(...) function(s). Take a look at the JOptionPane Javadoc:
static void showMessageDialog(Component parentComponent, Object
message): Brings up an information-message dialog titled "Message".
static void showMessageDialog(Component parentComponent, Object
message, String title, int messageType): Brings up a dialog that
displays a message using a default icon determined by the messageType
parameter.
static void showMessageDialog(Component parentComponent, Object
message, String title, int messageType, Icon icon): Brings up a dialog
displaying a message, specifying all parameters.
The parentComponent is defined as "determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used".

Related

Read from a file and populate existing JComboBox with new data

I am attempting to write a conversion program in which a new file can be loaded in to the program and change the conversion (needs to also include validation if the file is corrupted). I currently have the conversions hard coded in and want to extend the program so that it accepts the conversion factors from an external txt file.
I am new to programming and don't really understand how to do this can someone help?
public class CurrencyPanel extends JPanel{
//Declaring global variables which include buttons, labels, comboBox and a CheckBox
private final static String[] conversionList = { "Euro (EUR)", "US Dollers(USD)", "Australian Dollars (AUD)",
"Canadian Dollars (CAD)", "Icelandic Króna (ISK)", "United Arab Emirates Dirham (AED)",
"South African Rand (ZAR)", "Thai Baht (THB)"};
private JTextField inputField;
private JLabel labelOutput, labelCount, labelReverse;
private JCheckBox reverseCheck;
private JComboBox<String> comboSelect;
private int count = 0;
public MainPanel mainPanel;
CurrencyPanel() {
//initialising the convertListner to listener
ActionListener listener = new ConvertListener();
//setting comboBox to variable of list of conversions
comboSelect = new JComboBox<String>(conversionList);
comboSelect.setToolTipText("Select Conversion Type"); //ToolTip
JLabel labelEnter = new JLabel("Enter value:"); //enter value label
JButton convertButton = new JButton("Convert"); //convert button
convertButton.addActionListener(listener); // convert values when pressed
convertButton.setToolTipText("Press to convert value"); //ToolTip
JButton clearButton = new JButton ("Clear"); //clear button
clearButton.addActionListener(new ClearLabel()); //clear labels when button pressed
clearButton.setToolTipText("Press to Clear Value & Conversion Counter"); //ToolTip
labelOutput = new JLabel("---"); //label to be changed when conversion done
inputField = new JTextField(5); //textField for the user to input
inputField.addActionListener(listener); //Press return to do conversion
labelOutput.setToolTipText("Conversion Value"); //ToolTip
inputField.setToolTipText("Enter the value you wish to convert"); //ToolTip
labelCount = new JLabel("Conversion Count: 0"); //Conversion count label to be changed when conversion occurs
labelCount.setToolTipText("Amount of conversions made"); //ToolTip
labelReverse = new JLabel("Reverse Conversion"); //ReverseConversion label
reverseCheck = new JCheckBox(); //new CheckBox
reverseCheck.setToolTipText("Check the box to reverse the conversion type"); //ToolTip
//adding components to the panel
add(comboSelect);
add(labelEnter);
add(inputField);
add(convertButton);
add(labelOutput);
//setting size and colour of panel
setPreferredSize(new Dimension(800, 100));
setBackground(Color.cyan);
}
public void clearLabelMethod() {
labelOutput.setText("---");
inputField.setText("");
count = 0;
labelCount.setText("Conversion Count: 0");
}
//ActionListener to clear labels
private class ClearLabel implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
labelOutput.setText("---");
inputField.setText("");
count = 0;
labelCount.setText("Conversion Count: 0");
}
}
//ActionListener that does the main conversions
private class ConvertListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
String text = inputField.getText().trim();
//attempting to clear the combo box before repopulating
comboSelect.removeAllItems();
//try block to display message dialog
try {
Double.parseDouble(text); //checking to see if value is an double
if(inputField.getText().isEmpty())
{ //if statement to check if inputField is empty
}
}catch (Exception e) {
JOptionPane.showMessageDialog(null, "Please enter a valid number"); //message dialogue
return;
}
// if exception isn't thrown, then it is an integer
if (text.isEmpty() == false) {
double value = Double.parseDouble(text); //converting double to string
// the factor applied during the conversion
double factor = 0;
// the offset applied during the conversion.
double offset = 0;
String symbol = null;
// Setup the correct factor/offset values depending on required conversion
switch (comboSelect.getSelectedIndex()) {
case 0: // Euro
factor = 1.359;
symbol = "€";
break;
case 1: // USD
factor = 1.34;
symbol = "$";
break;
case 2: // AUD
factor = 1.756;
symbol = "$";
break;
case 3: // CAD
factor = 1.71;
symbol = "$";
break;
case 4: // ISK
factor = 140.84;
symbol = "kr";
break;
case 5: // AED
factor = 4.92;
symbol = "د.إ";
break;
case 6: // ZAR
factor = 17.84;
symbol = "R";
break;
case 7: // THB
factor = 43.58;
symbol = "฿";
break;
}
double result = 0;
if(mainPanel.reverseCheckMethod() == true) { //if the reverse check option is selected
result = value / factor - offset; //do the opposite conversion
}else {
result = factor * value + offset; //if not then do regular conversion
}
DecimalFormat decFormat = new DecimalFormat("0.00"); //DecimalFormat of output
String formatted = decFormat.format(result); //formatting the result 2 decimal places
mainPanel.conCount();
labelOutput.setText(symbol+formatted); //setting the output label
}
}
}
public void loadFile() {
int itemCount = comboSelect.getItemCount();
for(int i=0;i<itemCount;i++) {
comboSelect.removeAllItems();
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("currency.txt"), "UTF8"));
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
String currencyType = values[0];
String currencyValueTxt = values[1];
String currencySymbol = values[2];
Double conversionValue = Double.parseDouble(currencyValueTxt);
comboSelect.addItem(currencyType);
br.close();
}
}catch(Exception e) {
JOptionPane.showMessageDialog(null, "File Error");
}
}
}
The currency file in question is encoded in UTF-8 and is as follows:
Euro (EUR), 1.41, €
US Dollars (USD), 1.24, $
Australian Dollars (AUD), 1.86, $
Bermudan Dollar (BMD), 1.35, $
Icelandic króna (ISK), 141.24, kr
United Arab Emirates Dirham (AED), 4.12, د.إ
South African Rand (ZAR), 16.84, R
Thai Baht (THB), 42.58, ฿
Well you want to start to use a custom object to hold related data.
So you would start by creating a Currency object with 3 properties:
Name
Rate
Symbol
Something like:
public class Currency
{
private String name;
private double rate;
private String symbol;
public Currency (String name, double rate, String symbol)
{
this.name = name;
this.rate = rate;
this.symbol = symbol;
}
// add getter methods here
#Override
public String toString()
{
return name;
}
}
You would then need to add getter methods, getName(), getRate() and getSymbol() so you can access the data from the object.
Now you can add the "hard coded" currency objects to your combo box with code like:
//comboSelect = new JComboBox<String>(conversionList);
comboSelect = new JComboBox<Currency>();
comboSelect.addItem( new Currency("Euro (EUR)", 1.23, "€") );
comboSelect.addItem( new Currency("US Dollar (USD), 1.23, "$") );
...
The default renderer for the combo box will invoke the toString() method of your Currency object for the text to display in the combo box.
Now the ActionListener code for you combo box is greatly simplified:
Currency currency = (Currency)comboSelect.getSelectedItem();
factor = currency.getRate();
symbol = currency.getSymbol();
No need for the switch statement.
In your current design you have the names hard code in an Array and the rate/symbol hard coded in the ActionListener. With this design you have all the data together in a simple object.
So first get this basic logic working with hard coded Currency objects.
Then when you are ready to create dynamic currency objects your looping code would be something like:
while ((line = br.readLine()) != null)
{
String[] values = line.split(",");
double rate = Double.parseDouble( values[1] );
Currency currency = new Currency(values[0], rate, values[2]);
comboSelect.addItem( currency);
//br.close(); you only close the file after reading all the lines of data
}
br.close();
Note: it really isn't a good idea to use the toString() method for the text to display in the combo box. Instead you should be using a custom renderer. Once you have gotten the above suggestions working you can check out: Combo Box With Custom Renderer for more information on this topic.

Java - changing data fields?

There are two things I need help with but I'm having a hard time figuring out. They are listed below - any assistance is greatly appreciated.
1) I need to add a method that prompts the user to enter an int (1-3) to change the volume (default set to 2). I'm really having trouble figuring out how to make this work.
2) I need to add a similar method that prompts the user to enter an int (1 or 2) to plug the head phones in.
Here's my code; one is the test class:
//Open Package
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
// Creat class for headphones
public class HeadPhone_WK6 {
//Call scanner
Scanner stdin = new Scanner(System.in);
//Initialize input variable
int Input;
//Declare constant Variables
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
//Declare Private variables
private int volume;
private boolean pluggedIn;
private String manufacturer;
private String headPhoneColor;
//Declare Strings
String pluggedInStat;
String volumeNow;
// Constructor for class
public HeadPhone_WK6(int volume, boolean pluggedIn, String manufacturer, String headPhoneColor) {
this.volume = volume;
this.pluggedIn = pluggedIn;
this.manufacturer = manufacturer;
this.headPhoneColor = headPhoneColor;
}
// Default Constructor for default settings
public HeadPhone_WK6() {
volume = MEDIUM;
pluggedIn = false;
manufacturer = "";
headPhoneColor = "";
}
// setVolume
public void setVolume(int volume) {
this.volume = volume;
}
// getVolume
public int getVolume() {
if (volume == 1) {
volumeNow = "LOW";
}
else if (volume == 2) {
volumeNow = "MEDIUM";
}
else {
volumeNow = "HIGH";
}
return volume;
}
// setPluggedIn
public void setPluggedIn(boolean pluggedIn) {
this.pluggedIn = pluggedIn;
}
// getPluggedIn
public boolean getPluggedIn() {
if(pluggedIn == true) {
pluggedInStat = "Plugged In";
}
else {
pluggedInStat = "Not Plugged In";
}
return pluggedIn;
}
// setManufacturer
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
// getManufacturer
public String getManufacturer() {
return manufacturer;
}
// setHeadPhoneColor
public void setHeadPhoneColor(String headPhoneColor) {
this.headPhoneColor = headPhoneColor;
}
// getHeadPhoneColor
public String getHeadPhoneColor() {
return headPhoneColor;
}
// method to create string
public String toString() {
boolean phonesPluggedIn = this.getPluggedIn();
String phoneManufacturer = this.getManufacturer();
String phoneColor = this.getHeadPhoneColor();
String currentVolume = this.volumeNow;
//Build String for characteristics of phones
StringBuilder characteristics = new StringBuilder();
characteristics.append(String.format("\nThe Head Phone Manufacturer "
+ "is: %s", phoneManufacturer));
characteristics.append(String.format("\nThe Color of the Head Phone Set "
+ "is: %s", phoneColor));
characteristics.append(String.format("\nThe Head Phones are Currently: "
+ " %s", phonesPluggedIn));
characteristics.append(String.format("\nThe Head Phone Volume is "
+ "Currently Set on: %s", currentVolume));
//return string for characteristics
return characteristics.toString();
}
}
package headphone_wk6;
//Import scanner since this will require user input
import java.util.Scanner;
//Test class for head phone
public class HeadPhone_WK6_Test {
//Command line arguments
public static void main(String[] args) {
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(2, false, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(2, false, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(2, false, "RCA", "ORANGE");
int bestPairVolume = bestPair.getVolume();
boolean bestPairPluggedIn = bestPair.getPluggedIn();
String bestPairManufacturer = bestPair.getManufacturer();
String bestPairHeadPhoneColor = bestPair.getHeadPhoneColor();
String bestPairVolumeNow = bestPair.volumeNow;
String bestPairPluggedInStat = bestPair.pluggedInStat;
int worstPairVolume = worstPair.getVolume();
boolean worstPairPluggedIn = worstPair.getPluggedIn();
String worstPairManufacturer = worstPair.getManufacturer();
String worstPairHeadPhoneColor = worstPair.getHeadPhoneColor();
String worstPairVolumeNow = worstPair.volumeNow;
String worstPairPluggedInStat = worstPair.pluggedInStat;
int decentPairVolume = decentPair.getVolume();
boolean decentPairPluggedIn = decentPair.getPluggedIn();
String decentPairManufacturer = decentPair.getManufacturer();
String decentPairHeadPhoneColor = decentPair.getHeadPhoneColor();
String decentPairVolumeNow = decentPair.volumeNow;
String decentPairPluggedInStat = decentPair.pluggedInStat;
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
//Loop for random headphone selection
if (Input == 1){
//echo user input
System.out.println("You have chosen the best pair of "
+ "headphones! Here is a list of the characteristics: ");
System.out.println(bestPair.toString());
//End if
}
else if (Input == 2){
System.out.println("You have chosen the worst pair of "
+ "headphones. Here is a list of the characteristics: ");
System.out.println(worstPair.toString());
//End If
}
else if(Input == 3){
System.out.println("You have chosen a decent pair of "
+ "headphones. Here is a list of the characteristics:");
System.out.println(decentPair.toString());
//End If
}
else{
System.out.println("You have expressed that you want to see "
+ "the default pair of headphones. They are the "
+ "decent pair! Here's a list of the characteristics:");
System.out.println(decentPair.toString());
}
}
}
Maybe try something like this, first get input via scanner, then create HeadPhone objects:
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
boolean pluggedIn=true;
if(plugInState==1) pluggedIn = false;
if(plugInState==2) pluggedIn = true;
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
HeadPhone_WK6 bestPair = new HeadPhone_WK6(volumeState, pluggedIn, "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(volumeState, pluggedIn, "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(volumeState, pluggedIn, "RCA", "ORANGE");
You can put if clause in the end, based on your input, you can create one object that you need. If you need separate methods, do this in main():
HeadPhone_WK6 hp = new HeadPhone_WK6();
//Initialize input variable
int Input;
//Call scanner
Scanner stdin = new Scanner(System.in);
//Introduce HeadPhone helper
System.out.print("Hi there! Let's have you try a pair of head phones "
+ "on and we'll see what you think of them! \nStart by choosing a "
+ "random pair of head phones. To do this, enter 1, 2, or 3: ");
//Get user input for random pair of headphones
Input = stdin.nextInt();
System.out.println("Now give me value of plug in 1 or 2");
int plugInState = stdin.nextInt();
hp.setPluggedIn(plugInState);
System.out.println("Now give me value volume (1/2/3");
int volumeState = stdin.nextInt();
hp.setVolume(volumeState);
HeadPhone_WK6 bestPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "SONY", "BLUE");
HeadPhone_WK6 worstPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "BOSE", "BLACK");
HeadPhone_WK6 decentPair = new HeadPhone_WK6(hp.getVolume(), hp.getPluggedIn(), "RCA", "ORANGE");
Where
setPluggedIn(int pluggedInState) {
if(plugInState==1) pluggedIn = false;
else if(plugInState==2) pluggedIn = true;
else {
pluggedIn = false;
}
}

Java Sorting data from a file using JCheckboxes

I'm trying to create a program that will take data in from a random access file and sort it based on whichever checkbox the user selects. The data should be sorted by either the bank account number, customer name or balance (when a user clicks that checkbox the data in the text area becomes sorted based on that). Once the data is sorted, it is outputted into the JTextArea. I'm also trying to output the total amount of entries from the file in the text field below the check boxes.
Thanks!
import java.lang.reflect.Array;
import java.nio.file.*;
import java.text.DecimalFormat;
import java.util.Collections;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.border.Border;
public class GUIBankAcctSorter extends JFrame implements ItemListener {
public static void main(String[] args) {
GUIBankAcctSorter myFrame = new GUIBankAcctSorter();
myFrame.setVisible(true);
Path file = Paths.get("C:\\Java\\Bank.txt");
final String ID_FORMAT = "0000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String BALANCE_FORMAT = "00000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_LENGTH + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final String EMPTY_ACCT = "0000";
String[] array = new String[3];
double balance = 0;
output(s, array, delimiter, balance, EMPTY_ACCT, file);
}
private static final long serialVersionUID = 1L;
private static final int WIDTH = 450;
private static final int HEIGHT = 310;
private static final int X_ORIGIN = 200;
private static final int Y_ORIGIN = 200;
JLabel title = new JLabel("Bank Account Sorter");
JLabel sort = new JLabel("Sort By ");
JLabel total = new JLabel("Total # of Bank Accounts ");
private Container con = getContentPane();
private FlowLayout layout = new FlowLayout();
static JTextArea area = new JTextArea(10, 35);
static JTextField field = new JTextField(5);
JCheckBox cust = new JCheckBox(" Cust # ", false);
JCheckBox bal = new JCheckBox(" Balance ", false);
JCheckBox name = new JCheckBox(" Name ", false);
public static void output(String s, String[] array, String delimiter, double balance, String EMPTY_ACCT, Path file){
String temp = "";
try{
InputStream iStream = new BufferedInputStream(Files.newInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
while(s != null){
array = s.split(delimiter);
if(!array[0].equals(EMPTY_ACCT)){
balance = Double.parseDouble(array[2]);
area.append("Cust # " + array[0] + "\t" + " Name: " + array[1] + " Balance " + "\t$" + array[2] + "\n");
}
s = reader.readLine();
}
reader.close();
}catch(Exception e){
System.out.println("Message: " + e);
}
field.setText(temp);
}
public GUIBankAcctSorter(){
super("Bank Account Sorter");
Font headFont = new Font("Arial", Font.BOLD, 28);
con.setLayout(layout);
title.setFont(headFont);
con.add(title);
area.setEditable(false);
field.setEditable(false);
con.add(new JScrollPane(area));
cust.addItemListener(this);
bal.addItemListener(this);
name.addItemListener(this);
con.add(sort);
con.add(cust);
con.add(bal);
con.add(name);
con.add(total);
con.add(field);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
int select = e.getStateChange();
if(source == cust){
if(select == ItemEvent.SELECTED){
bal.setSelected(false);
name.setSelected(false);
}
}
if(source == bal){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
name.setSelected(false);
}
}
if(source == name){
if(select == ItemEvent.SELECTED){
cust.setSelected(false);
bal.setSelected(false);
}
}
}
}
Here you can see a good example using comparator to sort the object.
Let us suppose:
RowTest is a class that represent a single row of grid.
orderAMT is a class variable/Column/JTextField of Row.
Now the code below show how to sort the List of RowTest according to its attribute orderAMT.
List<RowTest> sortedList = getAllRowsThatNeedToBeSorted();
Comparator comparator = new OrderAMTComparator();
Collections.sort(sortedList, comparator);
public class OrderAMTComparator implements Comparator<RowTest> {
#Override
public int compare(RowTest o1, RowTest o2) {
//Here you can use If condition to check which checkbox is selected and sort the list
//repace getOrderAMT with other fields.
BigDecimal compareRes = o1.getOrderAMT().getBigdecimalValue().subtract(o2.getOrderAMT().getBigdecimalValue());
//You can just return compareRes.compareTo(new BigDecimal(0))
//But Here I want to show that you can check any condition and return -1,1,0 as your
//requirement
if (compareRes.compareTo(new BigDecimal(0)) == -1) {
return -1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 1) {
return 1;
} else if (compareRes.compareTo(new BigDecimal(0)) == 0 ) {
return 0;
}
return compareRes.intValue();
}
}
I hope you have understand this. If not I will elaborate.
Thankyou.
Is there anyway to do it with checkboxes?
Certainly:
Declare an Account class that stores the account number, name & balance.
Add each new Account to a List structure such as ArrayList.
Create a Comparator relevant to each of the 2 fields.
At time of sort, use Collections.sort(list,comparator).
Refresh the text area with the content of the sorted list.
Other tips
Since those check boxes are mutually exclusive, they should really be a ButtonGroup of JRadioButton instances.
Change setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); & setLocationRelativeTo(null) to setLocationByPlatform(true). See this answer for a demo.
Change setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT); for pack() (& use layouts more effectively).

Java code written but no expected output after running

This is a programming assignment I am working on. It takes a single string input that represents a sequence of transactions and prints total gain/loss in the end.
I have my code written and think it should do what I want...but doesn't. I don't get any kind of output after running the program with the specified input.
The input I'm using is:
buy 100 share(s) at $20 each;buy 20 share(s) at $24 each;buy 200
share(s) at $36 each;sell 150 share(s) at $30 each;buy 50 share(s) at
$25 each;sell 200 share(s) at $35 each;
import java.util.*;
import java.text.*;
public class Stocks {
private int shares;
private int price;
private int temp;
private static int total;
private int finalPrice;
private int finalShares;
private Queue<Stocks> StockList = new LinkedList<Stocks>();
private static NumberFormat nf = NumberFormat.getCurrencyInstance();
public Stocks()
{
shares = 0;
price = 0;
}
public Stocks(int shares, int price)
{
this.shares = shares;
this.price = price;
}
public int getShares()
{
return this.shares;
}
public int getPrice()
{
return this.price;
}
public void setShares(int shares)
{
this.shares = shares;
}
public void setPrice(int price)
{
this.price = price;
}
public void sell() {
int sharesToSell = this.getShares();
int priceToSell = this.getPrice();
while (!StockList.isEmpty()) {
int numShares = StockList.peek().getShares();
int sharePrice = StockList.peek().getPrice();
if (numShares < sharesToSell || numShares == sharesToSell) {
temp = sharesToSell - numShares; // remaining shares to sell
finalShares = sharesToSell - temp; // # shares selling at price
finalPrice = priceToSell - sharePrice; // shares sold at adjusted price
total += (finalPrice * finalShares); // Calculates total price
StockList.remove();
sharesToSell = temp; // Remaining shares needed to be sold # price
}
if (numShares > sharesToSell) {
temp = numShares - sharesToSell; // Remaining shares that were bought
finalPrice = priceToSell - sharePrice; // Shares sold at adjusted price
total += (finalPrice * sharesToSell); // adds to running total
StockList.peek().setShares(temp);
}
}
}
public void buy() {
int numShares = this.getShares();
int priceToBuy = this.getPrice();
Stocks newStock = new Stocks(numShares,priceToBuy);
StockList.add(newStock); // adds stock to list
int temptotal = (numShares * priceToBuy); // decreases running total
total += (-1 * temptotal);
}
public static int getTotal() { // gets total profit (or loss)
return total;
}
// *****MAIN METHOD*****
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter transaction sequence:");
String input = scan.nextLine().trim();
String[] inputArray = new String[50];
String[] inputArray2 = new String[50];
int numShares, sharePrice;
inputArray = input.split(";");
for (String i : inputArray) {
if (i.toUpperCase().contains("BUY")) {
inputArray2 = i.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.buy();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
}
else if (i.toUpperCase().contains("SELL")) {
inputArray2 = input.split(" ");
inputArray2[4] = inputArray2[4].substring(1);
try {
numShares = Integer.parseInt(inputArray2[1]);
sharePrice = Integer.parseInt(inputArray2[4]);
Stocks newStock = new Stocks(numShares,sharePrice);
newStock.sell();
} catch (NumberFormatException e) {
System.out.println("Error");
return;
}
} else {
System.out.println("Error - input does not contain buy/sell");
}
} System.out.println(nf.format(getTotal()));
}
}
You can clean up your parsing a lot by taking a look at java.util.regex.Matcher and java.util.regex.Pattern. They will let you match input against regular expressions. In addition, you can place parens in the regex to extract certain parts. So in your example, you really only care about three things: the operation(buy or sell), the quantity, and the price.
Here's a small example
String sentence = "john programs 10 times a day";
// here's our regex - each set of parens is a "group"
Pattern pattern = Pattern.compile("([A-Za-z]+) programs ([0-9]+) times a day");
Matcher matcher = pattern.matcher(sentence);
String person = matcher.group(1); // here we get the first group
String number = Integers.parseInt(matcher.group(2)); // here we get the second group
System.out.println("Person: " + person + " Number: " + number);
Looks like the main method is returning immediately when it parses a BUY transaction. You probably intended to put the return statement inside the catch block.

How do I switch the end function?

As in, the value as the end where it says "X dollars converts to Y russian ruble" (after the two Digits new Decimal Format) - the problem is that it can be russian ruble, british pound, or euro. How can I differentiate? (text inserted at line in question)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class CurrencyConversion extends Applet implements ItemListener
{
//declare variables and color
double dollars, answer;
int empCode;
Image dollarSign;
Color darkRed = new Color(160, 50, 0);
//Create components for applet
Label promptLabel = new Label("Enter the dollar amount (do not use commas or dollar signs):");
TextField currencyField = new TextField(20);
Label codeLabel = new Label ("Select the desired currency:");
CheckboxGroup codeGroup = new CheckboxGroup () ;
Checkbox britishpoundBox = new Checkbox("British Pound",false,codeGroup);
Checkbox euroBox = new Checkbox("Euro",false,codeGroup);
Checkbox russianrubleBox = new Checkbox("Russian Ruble",false,codeGroup);
Checkbox hiddenBox = new Checkbox("",true,codeGroup);
Label outputLabel = new Label("Click an option to convert the desired currency.");
public void init()
{
setBackground(darkRed);
setForeground(Color.white);
add(promptLabel);
add(currencyField);
currencyField.requestFocus();
currencyField.setForeground(Color.black);
add(codeLabel);
add(britishpoundBox);
britishpoundBox.addItemListener(this);
add(euroBox);
euroBox.addItemListener(this);
add(russianrubleBox);
russianrubleBox.addItemListener(this);
add(outputLabel);
}
//This method is triggered by click
public void itemStateChanged(ItemEvent choice)
{
try
{
dollars = getCurrency();
empCode = getCode();
answer = getComm(dollars,empCode);
output(answer, dollars);
}
catch (NumberFormatException e)
{
outputLabel.setText("You must enter a dollar amount greater than zero.");
hiddenBox.setState(true);
currencyField.setText("");
currencyField.requestFocus();
}
}
public double getCurrency()
{
double currency = Double.parseDouble(currencyField.getText());
if (currency <= 0) throw new NumberFormatException();
return currency;
}
public int getCode()
{
int code = 0;
if (britishpoundBox.getState()) code = 1;
else
if (euroBox.getState()) code = 2;
else
if (russianrubleBox.getState()) code = 3;
return code;
}
public double getComm(double currency, int code)
{
double amount = 0.0;
switch(code)
{
case 1:
amount = .79610 * currency;
break;
case 2:
amount = .70880 * currency;
break;
case 3:
amount = 35.88240 * currency;
break;
}
return amount;
}
public void output(double amount, double currency)
{
DecimalFormat twoDigits = new DecimalFormat("##.00");
outputLabel.setText("Your amount of " + twoDigits.format(currency) + " dollars converts to " + twoDigits.format(amount) RIGHT HERE - what do I do? );
}
public void paint(Graphics g)
{
dollarSign = getImage(getDocumentBase(), "dollarsign.gif");
g.drawImage(dollarSign,12,28,this);
}
}
Create a mapping from Integer to String, populate it with the various currency descriptions, and pass the Integer to the output function so that you can get the description from the mapping.
Wrap the currency concept into its own object. Override the ToString() method and return the name of the currency or define an explicit property to return the currency type. Pass the currency object around instead of the not so complex double and make the rate which was previously the double a property on the object.
I'd suggest you to use class java.util.Currency. The exchange rate of each currency should not be hard coded. For first phase just put it into properties file, i.e.:
RUB=35.88240
GBP=.79610
Avoid using hard coded list of currencies. Instead parse this property file, extract all keys, then use Currency.getInstance(currencyCode). Both UI and logic will be generic. Your application will be at least twice shorter and much more flexible.

Categories