JRadioButton Java GUI - java

JButton calculateBtn = new JButton("Calculate");
calculateBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int iStart, fRate, gen;
try {
iStart = Integer.parseInt(startText.getText());
fRate = Integer.parseInt(fixedText.getText());
gen = Integer.parseInt(genText.getText());
if(FixedRad.isSelected()) {
for(int a = 0; a < gen; a++) {
iStart += iStart*fRate/100;
}
} else {
int vara, varb, varc, vard, vare, varf, varg, varh, vari, varj;
vara = Integer.parseInt(var1.getText());
varb = Integer.parseInt(var2.getText());
varc = Integer.parseInt(var3.getText());
vard = Integer.parseInt(var4.getText());
vare = Integer.parseInt(var5.getText());
varf = Integer.parseInt(var6.getText());
varg = Integer.parseInt(var7.getText());
varh = Integer.parseInt(var8.getText());
vari = Integer.parseInt(var9.getText());
varj = Integer.parseInt(var10.getText());
int[] iaGrowthRate = {vara, varb, varc, vard, vare, varf, varg, varh, vari, varj};
for( int a = 0; a < 10; a++) {
iStart += iStart*iaGrowthRate[a]/100;
}
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "Plese enter a Valid Number");
}
}
});
The first button works perfectly (FixedRad) but when I try with the Variable Button selected it does not work and the message "Please enter a valid number appears"
Thanks!

Related

Why doesn't my find method work here even with all the values saved on the array?

I am fairly new to programming and I cant seem to find the problem in the area where I make the program search for the specific key term tho it's saved in the array.
here is the code where I add the details of the customer:
private void addCustomerToSeat(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Button[] seat = new Button[(SEATING_CAPACITY + 1)];
Button selectSeat = new Button(" Click to Book Seats ");
selectSeat.setLayoutX(320);
selectSeat.setLayoutY(512);
selectSeat.setOnAction(event -> {
window.setScene(scene2);
});
Label header = new Label("TRAIN BOOKING SYSTEM");
header.setLayoutX(250);
header.setLayoutY(30);
header.setStyle("-fx-font-size: 25px;");
Label clientName = new Label("Enter Customer Name: ");
clientName.setLayoutX(225);
clientName.setLayoutY(150);
clientName.setStyle("-fx-font-size: 16px;");
TextField cusName = new TextField();
cusName.setLayoutX(397);
cusName.setLayoutY(150);
Label destination = new Label("Choose destination: ");
destination.setLayoutX(225);
destination.setLayoutY(200);
destination.setStyle("-fx-font-size:16px;");
String [] destinations = {"Colombo to Badulla", "Badulla to Colombo"};
ComboBox Destination = new ComboBox(FXCollections.observableArrayList(destinations));
Destination.setLayoutX(397);
Destination.setLayoutY(200);
Label date = new Label("Select date:");
date.setLayoutY(275);
date.setLayoutX(225);
date.setStyle("-fx-font-size:16px;");
DatePicker datePicker = new DatePicker();
LocalDate now = LocalDate.now();
datePicker.setValue(now);
datePicker.setLayoutX(397);
datePicker.setLayoutY(275);
AnchorPane layout1 = new AnchorPane();
layout1.setStyle("-fx-background-color:#5a89a3; ");
layout1.getChildren().addAll(Destination,destination,selectSeat,clientName,cusName,header,date,datePicker);
scene1 = new Scene(layout1,800,600);
window.setTitle("Train Booking System");
window.setScene(scene1);
window.show();
Label header1 = new Label("TRAIN BOOKING SYSTEM");
header1.setLayoutX(250);
header1.setLayoutY(30);
header1.setStyle("-fx-font-size: 25px;");
Button submit = new Button("Submit");
submit.setLayoutX(640);
submit.setLayoutY(480);
Button exit = new Button("Exit");
exit.setLayoutX(710);
exit.setLayoutY(480);
exit.setOnAction(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
Label greenSeat = new Label("Unbooked Seat");
greenSeat.setLayoutY(160);
greenSeat.setLayoutX(590);
greenSeat.setStyle("-fx-font-size:14px;");
Button unbooked = new Button(" ");
unbooked.setLayoutY(160);
unbooked.setLayoutX(560);
unbooked.setStyle("-fx-background-color:green;");
Label redSeat = new Label("Booked Seat");
redSeat.setLayoutX(590);
redSeat.setLayoutY(200);
redSeat.setStyle("-fx-font-size:14px;");
Button booked = new Button(" ");
booked.setLayoutX(560);
booked.setLayoutY(200);
booked.setStyle("-fx-background-color:red;");
GridPane gridPane = new GridPane();
int columnIndex = 0;
int rowIndex = 0;
int rowIndexes = 0;
int[] reservedSeats = new int[1];
String seatNumber;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++) {
if (i <= 9) {
seatNumber = "0" + (i);
} else {
seatNumber = "" + (i);
}
seat[i] = new Button(seatNumber);
gridPane.add(seat[i], columnIndex, rowIndex);
columnIndex++;
rowIndexes++;
if (rowIndexes == 4) {
columnIndex = 0;
rowIndexes = 0;
rowIndex++;
}
}
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
if (seatBooking[f].equals("Empty")) {
seat[f].setStyle("-fx-background-color: green;");
}
if (seatBooking[f].equals("booked")) {
seat[f].setStyle("-fx-background-color: red");
}
}
List<Integer> bookedCurrent = new ArrayList<>();
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
int finalF = f;
seat[f].setOnAction(event -> {
seat[finalF].setStyle("-fx-background-color: red");
seatBooking[finalF] = "booked";
bookedCurrent.add(finalF);
});
submit.setOnAction(event -> {
String personName = cusName.getText();
personName = personName.toLowerCase();
window.close();
for ( int loopSeatArray = 1; loopSeatArray< (SEATING_CAPACITY + 1); loopSeatArray++) {
if (loopSeatArray == reservedSeats[0]) {
seatBooking[loopSeatArray] = "Booked";
customerName[loopSeatArray] = personName;
}
seatBookingAndCustomerName[loopSeatArray] = seatBooking[loopSeatArray];
}
for (int total = 43; total < (SEATING_CAPACITY + 1); total++){
seatBookingAndCustomerName[total]= customerName[total-42]; }
displayMenu(seatBooking, customerName, seatBookingAndCustomerName);
});
}
gridPane.setLayoutX(160);
gridPane.setLayoutY(80);
gridPane.setHgap(20);
gridPane.setVgap(5);
AnchorPane layout2 = new AnchorPane();
layout2.setStyle("-fx-background-color:#5a89a3; ");
layout2.getChildren().addAll(gridPane,submit,exit,header1,greenSeat,unbooked,redSeat,booked);
scene2 = new Scene(layout2,800,600);
window.setTitle("Train Booking System");
window.show();
window.setOnCloseRequest(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
}
and here is the part of the code where I prompt the user for the name and find the location of given name:
private void findCustomerSeats(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter customer name: ");
String name = input.nextLine();
boolean flag = false;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++){
if (name.toLowerCase().equals(customerName[i])){
System.out.println("Seats booked are: " + seatBooking);
flag = true;
}
}
if (flag !=true){
System.out.println(name + " has not reserved a seat");
}
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
}
when the above code is run, and when I input the name, it plain out does not work.
One potential issue, your for loop is starting at index 1, I would begin by using something like this:
for (int idx = 0; idx < customerName.length; idx++) {
//This way you will not check an index of your array that does not exist
//which could cause a NullPointerException
//Additionally, this is useful if you want to grow your customerName array
}
Another useful tip, that I use all the time. Try printing out more information and see if you can spot the issue. This might seem trivial but I have found it extremely helpful. For example:
System.out.println("Inputted Name: " + name);
for (int idx = 0; idx < customerName.length; idx++) {
System.out.println("Does " + name.toLowerCase() + " = " + customerName[idx] + " ?");
}

ArrayList Index Error

I am trying to finish up a project that uses a graphical User Interface to search through a data Base of geysers in the US. I keep getting an error for one of my Array Lists. I would include my data for the program but is is 10,000 entries long. Any help much appreciated. This is being done in BlueJ
Error : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
DataBase Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class GeyserDatabase
{
private ArrayList < Geyser > Geysers;
private ArrayList < Eruption > Eruptions;
public GeyserDatabase() {
Geysers = new ArrayList < Geyser >();
Eruptions = new ArrayList < Eruption >();
}
public void readGeyserData(String filename){
try{
File f = new File(filename);
Scanner sc = new Scanner(f);
String text;
// keep reading as long as there is more data
while(sc.hasNext()) {
text = sc.nextLine();
Eruption e = new Eruption(text);
Eruptions.add(e);
}
sc.close();
}
catch(IOException e) {
System.out.println("Failed to read the data file: " + filename);
}
createGeyserList();
}
public void addEruption (Eruption e){
Eruptions.add(e);
}
public ArrayList <Eruption> getEruptionList(){
return Eruptions;
}
public ArrayList <Geyser> getGeyserList(){
return Geysers;
}
public int getNumEruptions() {
return Eruptions.size();
}
public int getNumEruptions(int m,int d,int y) {
int count = 0;
for ( Eruption e : Eruptions) {
if (e.getMonth()==m && e.getDay()==d && e.getYear()==y) {
count++;
}
}
return count;
}
public Eruption getLateNightEruption() {
Eruption latestEruption = Eruptions.get(0);
int latestHour = latestEruption.getHour();
int latestMinute = latestEruption.getMinute();
for ( Eruption e: Eruptions ) {
if (e.getHour() > latestHour || (e.getHour()==latestHour && e.getMinute()>latestMinute)) {
latestEruption = e;
latestHour = e.getHour();
latestMinute = e.getMinute();
}
}
return latestEruption;
}
public ArrayList < Eruption > getEruptions(String geyser) {
ArrayList < Eruption > result = new ArrayList < Eruption > ();
for ( Eruption e: Eruptions ) {
if (e.getGeyserName().startsWith(geyser)) {
result.add(e);
}
}
return result;
}
private void createGeyserList(){
ArrayList<String>nameList = new ArrayList<String>();
// create temporary list of unique geyser names
for(Eruption e:Eruptions){
if(!nameList.contains(e.getGeyserName())){
nameList.add(e.getGeyserName());
}
}
// create a list of geysers
ArrayList<Geyser>geyserList = new ArrayList<Geyser>();
for(String s:nameList){
Geyser g = new Geyser(s);
// count number of eruptions for current geyser name
for(Eruption e:Eruptions){
if(e.getGeyserName().equals(g.getName()))
g.increment();
}
geyserList.add(g);
}
}
public int getMostGeysers(){
return Geysers.size();
}
public Geyser findMostActiveGeyser(){
Geyser MostEruptions = Geysers.get(0);
int mostActive = MostEruptions.getNumEruptions();
for( Geyser g : Geysers){
if(g.getNumEruptions() > mostActive){
MostEruptions =g;
mostActive = g.getNumEruptions();
}
}
return MostEruptions;
}
public Geyser findLeastActiveGeyser()
{
Geyser leastActiveGeyser = Geysers.get(0);
int leastActive = leastActiveGeyser.getNumEruptions();
for(Geyser g: Geysers)
{
if(g.getNumEruptions() < leastActive)
{
leastActiveGeyser = g;
leastActive = g.getNumEruptions();
}
}
return leastActiveGeyser;
}
public String findDayWithMostEruptions(int y){
int dayMost = 1;
int monthMost = 1;
int maxSoFar = getNumEruptions(1,1,y);
for(int m = 1; m<=12; m++){
for(int d = 1; d<=31;d++){
int eruptionsDay = getNumEruptions(m,d,y);
if(eruptionsDay>maxSoFar){
dayMost = d;
monthMost = m;
maxSoFar=eruptionsDay;
}
}
}
return monthMost + "/" + dayMost + "/" + y + "Eruptions: " + maxSoFar;
}
public static void main(String args[]){
GeyserDatabase gdb = new GeyserDatabase();
}
}
GUI Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
import java.text.*;
/***********************************************************************
* GUI front end for a Yellowstone Geyser database
*
* #author Scott Grissom
* #version August 1, 2016
public class GeyserGUI extends JFrame implements ActionListener{
/** results box */
private JTextArea resultsArea;
private GeyserDatabase db;
/**JButtons */
private JButton findLateNightEruption;
private JButton findAmountOfEruptionsonDate;
private JButton findMaxEruptionsInYear;
private JButton findGeyserByName;
private JButton findMostActiveGeyser;
private JButton findLeastActiveGeyser;
private JButton getGeyserList;
private JTextField month;
private JTextField day;
private JTextField Year;
private JTextField geyser;
/** menu items */
private JMenuBar menus;
private JMenu fileMenu;
private JMenu reportsMenu;
private JMenuItem quitItem;
private JMenuItem openItem;
private JMenuItem countItem;
private JMenuItem geyserItem;
/*********************************************************************
Main Method
*********************************************************************/
public static void main(String arg[]){
GeyserGUI gui = new GeyserGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Yellowstone Geysers");
gui.pack();
gui.setVisible(true);
}
/*********************************************************************
Constructor - instantiates and displays all of the GUI commponents
*********************************************************************/
public GeyserGUI(){
db = new GeyserDatabase();
// FIX ME: the following line should be removed
db.readGeyserData("GeyserData.txt");
// create the Gridbag layout
setLayout(new GridBagLayout());
GridBagConstraints position = new GridBagConstraints();
// create the Results Text Area (5 x 10 cells)
resultsArea = new JTextArea(20,40);
JScrollPane scrollPane = new JScrollPane(resultsArea);
position.gridx = 0;
position.gridy = 0;
position.gridheight = 10;
position.gridwidth = 5;
position.insets = new Insets(20,20,0,0);
add(scrollPane, position);
/*******************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 0;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Month"), position);
position = new GridBagConstraints();
position.gridx = 0;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
month = new JTextField(2);
add(month, position);
/*************************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 1;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Day"), position);
position = new GridBagConstraints();
position.gridx = 1;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
day = new JTextField(2);
add(day, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 2;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Year"), position);
position = new GridBagConstraints();
position.gridx = 2;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
Year = new JTextField(4);
add(Year, position);
/**********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(0,20,0,0);
position.gridx = 3;
position.gridy = 10;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
add(new JLabel("Geyser"), position);
position = new GridBagConstraints();
position.gridx = 3;
position.gridy = 11;
position.gridwidth = 1;
position.gridheight = 1;
position.anchor = GridBagConstraints.LINE_START;
position.insets = new Insets(0,20,0,0);
geyser = new JTextField(12);
add(geyser, position);
/*********************************************************/
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 0;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Eruptions"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 1;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLateNightEruption = new JButton("Late Night Eruption");
findLateNightEruption.addActionListener(this);
add(findLateNightEruption, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 2;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findAmountOfEruptionsonDate = new JButton("# On Date");
findAmountOfEruptionsonDate.addActionListener(this);
add(findAmountOfEruptionsonDate, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 3;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMaxEruptionsInYear = new JButton("Max Eruptions in Year");
findMaxEruptionsInYear.addActionListener(this);
add(findMaxEruptionsInYear, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 4;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findGeyserByName = new JButton("By Name");
findGeyserByName.addActionListener(this);
add(findGeyserByName, position);
position = new GridBagConstraints();
position.insets = new Insets(30,5,5,5);
position.gridx = 6;
position.gridy = 5;
position.gridwidth = 1;
position.gridheight = 1;
add(new JLabel("Geysers"), position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 6;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findMostActiveGeyser = new JButton("Most Active");
findMostActiveGeyser.addActionListener(this);
add(findMostActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 7;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
findLeastActiveGeyser = new JButton("Least Active");
findLeastActiveGeyser.addActionListener(this);
add(findLeastActiveGeyser, position);
position = new GridBagConstraints();
position.gridx = 6;
position.gridy = 8;
position.gridwidth = 1;
position.gridheight = 1;
position.insets = new Insets(0,5,5,5);
getGeyserList = new JButton("Geyser List");
getGeyserList.addActionListener(this);
add(getGeyserList, position);
// set up File menus
setupMenus();
pack();
}
/*********************************************************************
List all entries given an ArrayList of eruptions. Include a final
line with the number of eruptions listed
#param m list of eruptions
*********************************************************************/
private void displayEruptions(ArrayList <Eruption> m){
resultsArea.setText("");
for(Eruption e: m){
resultsArea.append("\n" + e.toString());
}
resultsArea.append ("\nNumber of Geysers: " + m.size());
}
/*********************************************************************
Respond to menu selections and button clicks
#param e the button or menu item that was selected
*********************************************************************/
public void actionPerformed(ActionEvent e){
Eruption item = null;
// either open a file or warn the user
if (e.getSource() == openItem){
openFile();
}else if(db.getNumEruptions() == 0){
String errorMessage = "Did you forget to open a file?";
resultsArea.setText(errorMessage);
return;
}
// menu item - quit
else if (e.getSource() == quitItem){
System.exit(1);
}
// FIX ME: Count menu item - display number of eruptions and geysers
else if (e.getSource() == countItem){
resultsArea.setText("\nNumber of Eruptions: " + db.getNumEruptions());
}
// FIX ME: display late night eruption
else if (e.getSource() == findLateNightEruption){
resultsArea.setText("Latest Eruption\n" + db.getLateNightEruption());
}
//FIX ME: display all geyser names
else if (e.getSource() == getGeyserList){
displayEruptions(db.getEruptionList());
}
//FIX ME: max eruptions day in a year (check for year)
else if(e.getSource() == findMaxEruptionsInYear){
String aux = Year.getText();
if(aux.length() == 0){
JOptionPane.showMessageDialog(this, "Enter a Year to Search For Maax Eruptions");
}
else
{
int y = Integer.parseInt(Year.getText());
String result = db.findDayWithMostEruptions(y);
resultsArea.setText(result);
}
}
// FIX ME: list all eruptions for a geyser (check for name)
else if(e.getSource() == findGeyserByName){
String name = geyser.getText();
if(name.length() == 0){
JOptionPane.showMessageDialog(this, "Provide Name");
}
else
{
ArrayList<Eruption>result = db.getEruptions(name);
displayEruptions(result);
}
}
// FIX ME: display eruptions for a particular date
else if(e.getSource()==findAmountOfEruptionsonDate){
String aux1 = Year.getText();
String aux2 = month.getText();
String aux3 = day.getText();
if(aux1.length() == 0 || aux2.length() == 0 || aux3.length() == 0)
{
JOptionPane.showMessageDialog(this, "Provide year,month, and day");
}
else
{
int y = Integer.parseInt(Year.getText());
int m = Integer.parseInt(month.getText());
int d = Integer.parseInt(day.getText());
int result = db.getNumEruptions(m, d, y);
resultsArea.setText("Number of Eruptions: " + result);
}
}
else if(e.getSource() == findMostActiveGeyser){
resultsArea.setText("Most active Geyser: " + db.findMostActiveGeyser());
}
else if(e.getSource() == findLeastActiveGeyser){
resultsArea.setText("Least active Geyser: " + db.findLeastActiveGeyser());
}
}
/*********************************************************************
In response to the menu selection - open a data file
*********************************************************************/
private void openFile(){
JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
int returnVal = fc.showOpenDialog(this);
// did the user select a file?
if (returnVal == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
// use the name of your lottery ticket variable
db.readGeyserData(filename);
}
}
/*********************************************************************
Create a custom gridbag constraint
*********************************************************************/
private GridBagConstraints makeConstraints(int x, int y, int h, int w, int align){
GridBagConstraints rtn = new GridBagConstraints();
rtn.gridx = x;
rtn.gridy = y;
rtn.gridheight = h;
rtn.gridwidth = w;
// set alignment: LINE_START, CENTER, LINE_END
rtn.anchor = align;
return rtn;
}
/*********************************************************************
Set up the menu items
*********************************************************************/
private void setupMenus(){
// create menu components
fileMenu = new JMenu("File");
quitItem = new JMenuItem("Quit");
openItem = new JMenuItem("Open...");
reportsMenu = new JMenu("Reports");
countItem = new JMenuItem("Counts");
// assign action listeners
quitItem.addActionListener(this);
openItem.addActionListener(this);
countItem.addActionListener(this);
// display menu components
fileMenu.add(openItem);
fileMenu.add(quitItem);
reportsMenu.add(countItem);
menus = new JMenuBar();
menus.add(fileMenu);
menus.add(reportsMenu);
setJMenuBar(menus);
}
}
Geyser Code:
import java.util.Scanner;
public class Geyser
{
String geyserName;
int count = 0;
public Geyser (String name){
geyserName = name;
}
public void increment (){
count++;
}
public String getName() {
return geyserName;
}
public int getNumEruptions() {
return count;
}
public static void main(String args[]) {
Geyser g = new Geyser("xyz");
if (g.getName().equals("xyz")) {
System.out.println("getName worked well.");
}
else {
System.out.println("getName did not work well.");
}
if (g.getNumEruptions() == 0) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
g.increment();
if (g.getNumEruptions() == 1) {
System.out.println("getNumEruptions worked well.");
}
else {
System.out.println("getNumEruptions did not work well.");
}
}
}
Eruption Code:
import java.util.Scanner;
public class Eruption
{
int month;
int day;
int year;
int hour;
int minute;
String geyserName;
public Eruption(String info){
Scanner scnr = new Scanner(info);
scnr.useDelimiter("/|,|:");
month = scnr.nextInt();
day = scnr.nextInt();
year = scnr.nextInt();
geyserName = scnr.next();
hour = scnr.nextInt();
minute = scnr.nextInt();
}
public int getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year;
}
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public String getGeyserName(){
return geyserName;
}
public String toString( ){
String geyserString = geyserName + " " + "on" + month +"/"+ day +"/" + year + "at" + hour +":"+ minute;
return geyserString;
}
public static void main(String [] args){
Eruption e = new Eruption("1/2/2016,Old Faithful,10:46");
if (e.getMonth() == 1) {
System.out.println("getMonth worked well");
}
}
}

How to use the 'svm_toy' Applet example in LibSVM?

I'm using LIBSVM. In the download package is a svm_toy.java file. I could not find out how it works. Here is the source code:
import libsvm.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
/**
* SVM package
* #author unknown
*
*/
public class svm_toy extends Applet {
static final String DEFAULT_PARAM="-t 2 -c 100";
int XLEN;
int YLEN;
// off-screen buffer
Image buffer;
Graphics buffer_gc;
// pre-allocated colors
final static Color colors[] =
{
new Color(0,0,0),
new Color(0,120,120),
new Color(120,120,0),
new Color(120,0,120),
new Color(0,200,200),
new Color(200,200,0),
new Color(200,0,200)
};
class point {
point(double x, double y, byte value)
{
this.x = x;
this.y = y;
this.value = value;
}
double x, y;
byte value;
}
Vector<point> point_list = new Vector<point>();
byte current_value = 1;
public void init()
{
setSize(getSize());
final Button button_change = new Button("Change");
Button button_run = new Button("Run");
Button button_clear = new Button("Clear");
Button button_save = new Button("Save");
Button button_load = new Button("Load");
final TextField input_line = new TextField(DEFAULT_PARAM);
BorderLayout layout = new BorderLayout();
this.setLayout(layout);
Panel p = new Panel();
GridBagLayout gridbag = new GridBagLayout();
p.setLayout(gridbag);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridwidth = 1;
gridbag.setConstraints(button_change,c);
gridbag.setConstraints(button_run,c);
gridbag.setConstraints(button_clear,c);
gridbag.setConstraints(button_save,c);
gridbag.setConstraints(button_load,c);
c.weightx = 5;
c.gridwidth = 5;
gridbag.setConstraints(input_line,c);
button_change.setBackground(colors[current_value]);
p.add(button_change);
p.add(button_run);
p.add(button_clear);
p.add(button_save);
p.add(button_load);
p.add(input_line);
this.add(p,BorderLayout.SOUTH);
button_change.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_change_clicked(); button_change.setBackground(colors[current_value]); }});
button_run.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
button_clear.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_clear_clicked(); }});
button_save.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_save_clicked(input_line.getText()); }});
button_load.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_load_clicked(); }});
input_line.addActionListener(new ActionListener()
{ public void actionPerformed (ActionEvent e)
{ button_run_clicked(input_line.getText()); }});
this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
void draw_point(point p)
{
Color c = colors[p.value+3];
Graphics window_gc = getGraphics();
buffer_gc.setColor(c);
buffer_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
window_gc.setColor(c);
window_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
}
void clear_all()
{
point_list.removeAllElements();
if(buffer != null)
{
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
repaint();
}
void draw_all_points()
{
int n = point_list.size();
for(int i=0;i<n;i++)
draw_point(point_list.elementAt(i));
}
void button_change_clicked()
{
++current_value;
if(current_value > 3) current_value = 1;
}
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
void button_run_clicked(String args)
{
// guard
if(point_list.isEmpty()) return;
svm_parameter param = new svm_parameter();
// default values
param.svm_type = svm_parameter.C_SVC;
param.kernel_type = svm_parameter.RBF;
param.degree = 3;
param.gamma = 0;
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 40;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = new int[0];
param.weight = new double[0];
// parse options
StringTokenizer st = new StringTokenizer(args);
String[] argv = new String[st.countTokens()];
for(int i=0;i<argv.length;i++)
argv[i] = st.nextToken();
for(int i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
if(++i>=argv.length)
{
System.err.print("unknown option\n");
break;
}
switch(argv[i-1].charAt(1))
{
case 's':
param.svm_type = atoi(argv[i]);
break;
case 't':
param.kernel_type = atoi(argv[i]);
break;
case 'd':
param.degree = atoi(argv[i]);
break;
case 'g':
param.gamma = atof(argv[i]);
break;
case 'r':
param.coef0 = atof(argv[i]);
break;
case 'n':
param.nu = atof(argv[i]);
break;
case 'm':
param.cache_size = atof(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'h':
param.shrinking = atoi(argv[i]);
break;
case 'b':
param.probability = atoi(argv[i]);
break;
case 'w':
++param.nr_weight;
{
int[] old = param.weight_label;
param.weight_label = new int[param.nr_weight];
System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
}
{
double[] old = param.weight;
param.weight = new double[param.nr_weight];
System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
}
param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
default:
System.err.print("unknown option\n");
}
}
// build problem
svm_problem prob = new svm_problem();
prob.l = point_list.size();
prob.y = new double[prob.l];
if(param.kernel_type == svm_parameter.PRECOMPUTED)
{
}
else if(param.svm_type == svm_parameter.EPSILON_SVR ||
param.svm_type == svm_parameter.NU_SVR)
{
if(param.gamma == 0) param.gamma = 1;
prob.x = new svm_node[prob.l][1];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.y[i] = p.y;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[1];
x[0] = new svm_node();
x[0].index = 1;
int[] j = new int[XLEN];
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
{
x[0].value = (double) i / XLEN;
j[i] = (int)(YLEN*svm.svm_predict(model, x));
}
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(0,0,0,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(0,0,0,YLEN-1);
int p = (int)(param.p * YLEN);
for(int i=1;i<XLEN;i++)
{
buffer_gc.setColor(colors[0]);
buffer_gc.drawLine(i,0,i,YLEN-1);
window_gc.setColor(colors[0]);
window_gc.drawLine(i,0,i,YLEN-1);
buffer_gc.setColor(colors[5]);
window_gc.setColor(colors[5]);
buffer_gc.drawLine(i-1,j[i-1],i,j[i]);
window_gc.drawLine(i-1,j[i-1],i,j[i]);
if(param.svm_type == svm_parameter.EPSILON_SVR)
{
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
window_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
buffer_gc.setColor(colors[2]);
window_gc.setColor(colors[2]);
buffer_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
window_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
}
}
}
else
{
if(param.gamma == 0) param.gamma = 0.5;
prob.x = new svm_node [prob.l][2];
for(int i=0;i<prob.l;i++)
{
point p = point_list.elementAt(i);
prob.x[i][0] = new svm_node();
prob.x[i][0].index = 1;
prob.x[i][0].value = p.x;
prob.x[i][1] = new svm_node();
prob.x[i][1].index = 2;
prob.x[i][1].value = p.y;
prob.y[i] = p.value;
}
// build model & classify
svm_model model = svm.svm_train(prob, param);
svm_node[] x = new svm_node[2];
x[0] = new svm_node();
x[1] = new svm_node();
x[0].index = 1;
x[1].index = 2;
Graphics window_gc = getGraphics();
for (int i = 0; i < XLEN; i++)
for (int j = 0; j < YLEN ; j++) {
x[0].value = (double) i / XLEN;
x[1].value = (double) j / YLEN;
double d = svm.svm_predict(model, x);
if (param.svm_type == svm_parameter.ONE_CLASS && d<0) d=2;
buffer_gc.setColor(colors[(int)d]);
window_gc.setColor(colors[(int)d]);
buffer_gc.drawLine(i,j,i,j);
window_gc.drawLine(i,j,i,j);
}
}
draw_all_points();
}
void button_clear_clicked()
{
clear_all();
}
void button_save_clicked(String args)
{
FileDialog dialog = new FileDialog(new Frame(),"Save",FileDialog.SAVE);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
try {
DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
int svm_type = svm_parameter.C_SVC;
int svm_type_idx = args.indexOf("-s ");
if(svm_type_idx != -1)
{
StringTokenizer svm_str_st = new StringTokenizer(args.substring(svm_type_idx+2).trim());
svm_type = atoi(svm_str_st.nextToken());
}
int n = point_list.size();
if(svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.y+" 1:"+p.x+"\n");
}
}
else
{
for(int i=0;i<n;i++)
{
point p = point_list.elementAt(i);
fp.writeBytes(p.value+" 1:"+p.x+" 2:"+p.y+"\n");
}
}
fp.close();
} catch (IOException e) { System.err.print(e); }
}
void button_load_clicked()
{
FileDialog dialog = new FileDialog(new Frame(),"Load",FileDialog.LOAD);
dialog.setVisible(true);
String filename = dialog.getDirectory() + dialog.getFile();
if (filename == null) return;
clear_all();
try {
BufferedReader fp = new BufferedReader(new FileReader(filename));
String line;
while((line = fp.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
if(st.countTokens() == 5)
{
byte value = (byte)atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x,y,value));
}
else if(st.countTokens() == 3)
{
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x,y,current_value));
}else
break;
}
fp.close();
} catch (IOException e) { System.err.print(e); }
draw_all_points();
}
protected void processMouseEvent(MouseEvent e)
{
if(e.getID() == MouseEvent.MOUSE_PRESSED)
{
if(e.getX() >= XLEN || e.getY() >= YLEN) return;
point p = new point((double)e.getX()/XLEN,
(double)e.getY()/YLEN,
current_value);
point_list.addElement(p);
draw_point(p);
}
}
public void paint(Graphics g)
{
// create buffer first time
if(buffer == null) {
buffer = this.createImage(XLEN,YLEN);
buffer_gc = buffer.getGraphics();
buffer_gc.setColor(colors[0]);
buffer_gc.fillRect(0,0,XLEN,YLEN);
}
g.drawImage(buffer,0,0,this);
}
public Dimension getPreferredSize() { return new Dimension(XLEN,YLEN+50); }
public void setSize(Dimension d) { setSize(d.width,d.height); }
public void setSize(int w,int h) {
super.setSize(w,h);
XLEN = w;
YLEN = h-50;
clear_all();
}
public static void main(String[] argv)
{
new AppletFrame("svm_toy",new svm_toy(),500,500+50);
}
}
class AppletFrame extends Frame {
AppletFrame(String title, Applet applet, int width, int height)
{
super(title);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
applet.init();
applet.setSize(width,height);
applet.start();
this.add(applet);
this.pack();
this.setVisible(true);
}
}
Could someone give me an example or explanation? I also would like to scale my training data. Where is the right place to scale?
Thanks
SVM-Toy
SVM Toy is - as the name suggests - a simple toy build by the LIBSVM dev team and is not recommended for "productive" visualization of the SVM's decision boundary.
Moreover looking into the source-code of svm_toy it becomes clear, that this tool only supports 2D vectors.
Relevant code fragment is taken from the button_load_clicked() Method:
while ((line = fp.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
if (st.countTokens() == 5) {
byte value = (byte) atoi(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
st.nextToken();
double y = atof(st.nextToken());
point_list.addElement(new point(x, y, value));
} else if (st.countTokens() == 3) {
double y = atof(st.nextToken());
st.nextToken();
double x = atof(st.nextToken());
point_list.addElement(new point(x, y, current_value));
} else {
break;
}
}
As you can see, the svm_toy implementation can only handle 2D vectors, which means it only supports vectors, which were constructed out of two features.
That means, you can only read and display files which are build from only two features like for example the fourclass dataset provided by the LIBSVM authors. However it seems, that this feature is not supported within this implementation.
I think, that the tool is designed for interactive visualization. You are able to change the color and click on the black application screen. After you set some points (each color representing an own class), you can click "run" and the decision boundary is displayed.
Displaying the desicion boundary in an high dimensional vector space is even nearly impossible. I would recommend to not use this tool implementation for any productive / scientific purpose.
Scaling
Scaling of your training data should be done after you transformed it into it's numeric representation and before you are going forward to train your SVM with this data.
In short that means, you have to do the following steps before using svm_train
Construct the numeric representation for each data point (with the help of feature selection, ...)
Analyse the resulting numeric representation for each data point
Scale your data for example to [-1,1]
Go ahead and train your SVM model. Note well, that you have to repeat 1-3 for predicting unknown data points. The only difference is, that you already know the necessary features, so there is no need for feature selection.

crystal reports RCAPI

Is there is a way to display the data in specified format using RCAPI.
Pls find the code below.
ReportClientDocument boReportClientDocument = new ReportClientDocument();
boReportClientDocument.open("blankreport.rpt", 0);
public void displayReportData(ReportClientDocument document,ISection detailArea) {
int INSERT_AT_END = -1;
DBUtil dBUtil = new DBUtil();
Field field = null;
Fields fields = null;
FieldObject boFieldObject = null;
try {
document.getDatabaseController().addDataSource(dBUtil.getData());
// ISection detailArea = document.getReportDefController().getReportDefinition().getDetailArea().getSections().get(0);
Tables tables = document.getDatabaseController().getDatabase().getTables();
for (int i = 0; i < tables.size(); i++) {
fields = tables.getTable(i).getDataFields();
int leftInc = 0;
int topInc =0;
System.out.println("no of records iiii::::" + i);
for (int j = 0; j < fields.size(); j++) {
System.out.println("no of records jjjj::::" + j);
field = (Field) fields.get(j);
boFieldObject = new FieldObject();
boFieldObject.setDataSource(field.getFormulaForm());
boFieldObject.setFieldValueType(field.getType());
boFieldObject.setLeft(250 +leftInc);
boFieldObject.setTop(800);
boFieldObject.setWidth(3);
boFieldObject.setHeight(250);
// leftInc += 30;
//topInc += 50;
document.getReportDefController().getReportObjectController().add(boFieldObject,detailArea,-1);
}
}
} catch (ReportSDKException ex) {
Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println(ex);
}
}

java image processing sobel edge detection

I have a problem with java program, in which i'm using sobel operator for edge detection, but when I'm trying to use that funcion, console says:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 262144
at sun.awt.image.ByteInterleavedRaster.getPixels(ByteInterleavedRaster.java:1015)
at Obrazek.jButtonSobelActionPerformed(Obrazek.java:566)
And the code for that is:
FileInputStream inFile = null;
try {
long beginTime = (new java.util.Date()).getTime();
int i, j;
double Gx[][], Gy[][], G[][];
inFile = new FileInputStream("D://lenacsmall.bmp");
BufferedImage bi = ImageIO.read(inFile);
int width = bi.getWidth();
int height = bi.getHeight();
int[] pixels = new int[width * height];
int[][] output = new int[width][height];
int[] raster = bi.getRaster().getPixels(0,0,width,height,pixels);
int counter = 0;
for(i = 0 ; i < width ; i++ )
{
for(j = 0 ; j < height ; j++ )
{
output[i][j] = pixels[counter];
counter = counter + 1;
}
}
Gx = new double[width][height];
Gy = new double[width][height];
G = new double[width][height];
for (i=0; i<width; i++) {
for (j=0; j<height; j++) {
if (i==0 || i==width-1 || j==0 || j==height-1)
Gx[i][j] = Gy[i][j] = G[i][j] = 0;
else{
Gx[i][j] = output[i+1][j-1] + 2*output[i+1][j] + output[i+1][j+1] -
output[i-1][j-1] - 2*output[i-1][j] - output[i-1][j+1];
Gy[i][j] = output[i-1][j+1] + 2*output[i][j+1] + output[i+1][j+1] -
output[i-1][j-1] - 2*output[i][j-1] - output[i+1][j-1];
G[i][j] = Math.abs(Gx[i][j]) + Math.abs(Gy[i][j]);
}
}
}
counter = 0;
for(int ii = 0 ; ii < width ; ii++ )
{
for(int jj = 0 ; jj < height ; jj++ )
{
pixels[counter] = (int) G[ii][jj];
counter = counter + 1;
}
}
BufferedImage outImg = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
outImg.getRaster().setPixels(0,0,width,height,pixels);
FileOutputStream outFile = null;
try {
outFile = new FileOutputStream("D://copyTop.bmp");
} catch (FileNotFoundException ex) {
}
try {
ImageIO.write(outImg,"BMP",outFile);
} catch (IOException ex) {
}
JFrame TheFrame = new JFrame("obrazek " + width + " " + height);
JLabel TheLabel = new JLabel(new ImageIcon(outImg));
TheFrame.getContentPane().add(TheLabel);
TheFrame.setSize(600, 600);
TheFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
TheFrame.setVisible(true);
} catch (FileNotFoundException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inFile.close();
} catch (IOException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm really need some help. I hope someone will answer for that post, thank you.
Greetings :)
Try this, edge detection using sobel approach, I just did this yesterday.
`
static BufferedImage inputImg,outputImg;
static int[][] pixelMatrix=new int[3][3];
public static void main(String[] args) {
try {
inputImg=ImageIO.read(new File("your input image"));
outputImg=new BufferedImage(inputImg.getWidth(),inputImg.getHeight(),TYPE_INT_RGB);
for(int i=1;i<inputImg.getWidth()-1;i++){
for(int j=1;j<inputImg.getHeight()-1;j++){
pixelMatrix[0][0]=new Color(inputImg.getRGB(i-1,j-1)).getRed();
pixelMatrix[0][1]=new Color(inputImg.getRGB(i-1,j)).getRed();
pixelMatrix[0][2]=new Color(inputImg.getRGB(i-1,j+1)).getRed();
pixelMatrix[1][0]=new Color(inputImg.getRGB(i,j-1)).getRed();
pixelMatrix[1][2]=new Color(inputImg.getRGB(i,j+1)).getRed();
pixelMatrix[2][0]=new Color(inputImg.getRGB(i+1,j-1)).getRed();
pixelMatrix[2][1]=new Color(inputImg.getRGB(i+1,j)).getRed();
pixelMatrix[2][2]=new Color(inputImg.getRGB(i+1,j+1)).getRed();
int edge=(int) convolution(pixelMatrix);
outputImg.setRGB(i,j,(edge<<16 | edge<<8 | edge));
}
}
File outputfile = new File("your output image");
ImageIO.write(outputImg,"jpg", outputfile);
} catch (IOException ex) {System.err.println("Image width:height="+inputImg.getWidth()+":"+inputImg.getHeight());}
}
public static double convolution(int[][] pixelMatrix){
int gy=(pixelMatrix[0][0]*-1)+(pixelMatrix[0][1]*-2)+(pixelMatrix[0][2]*-1)+(pixelMatrix[2][0])+(pixelMatrix[2][1]*2)+(pixelMatrix[2][2]*1);
int gx=(pixelMatrix[0][0])+(pixelMatrix[0][2]*-1)+(pixelMatrix[1][0]*2)+(pixelMatrix[1][2]*-2)+(pixelMatrix[2][0])+(pixelMatrix[2][2]*-1);
return Math.sqrt(Math.pow(gy,2)+Math.pow(gx,2));
}
`
In your for loops when you check
if (i==0 || i==width-1 || j==0 || j==height-1)
you should probably be checking for i >= width-2 rather than i==width-1.
For example, if width is 10 it falls into the statement if i == 9.
you want to catch if i == 8 since you later check [i+1], which in your code would be out of the bounds of your image array, since the maximum you can have is 9 (width-1).
Obviously the same applies for j.

Categories

Resources