d2jsp
Log InRegister
d2jsp Forums > Off-Topic > General Chat > User Blogs > Assignment Log
Prev123Next
Add Reply New Topic
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Mar 26 2013 08:12pm
111 A12

Code
import java.util.Scanner;
public class YuepA12
{

public static void main(String[] args)
{

 Scanner keybd = new Scanner(System.in);
 

 double total = 0;
 double sValue = 0;
 int count = 0;
 while (true)
 {
  System.out.println("Enter a number (or nothing to stop).");
  String a = keybd.nextLine();
 
  int b = a.length();
 
  if (b <= 0)
  {
   break;
  }
  try {
  double num = Double.parseDouble(a);
 
  } catch(NumberFormatException e)
  {
   System.out.println("Please enter an integer.");
   continue;
  }

  double num = Double.parseDouble(a);
 
  if(count == 0)
  {
   sValue = num;
  }
  else if (num < sValue)
  {
   sValue = num;
  }
   
 
 
  total += num;
  count++;
 
  continue;
 
 }
 if(count == 0)
 {
 System.out.println("You entered " + count + " number(s). ");
 System.out.println("Total = " + total);
 System.out.println("Smallest Value = " + sValue);
 
 }
 else
 {
 System.out.println("You entered " + count + " number(s). ");
 System.out.println("Total = " + total);
 System.out.println("Average = " + total/count);
 System.out.println("Smallest Value = " + sValue);
 }
}

}
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Mar 26 2013 08:12pm
111 A13 (Think I didn't finish this)

Code
import java.util.Scanner;
import java.util.InputMismatchException;

public class YuepA13
{
public static void main(String args[])
{

 
 System.out.println("Enter the size of a square to draw (an odd number between 1 and 79): ");
 
 try{
 
  Scanner keybd = new Scanner(System.in);
 /*
  int width = keybd.nextInt();
  if ( (!(width <= 79)) || (!(width >= 1)) || (width % 2 == 0) )
  {
   System.out.println("Sorry, not a valid input.");
   
   return;
  }
 */
  int width = 9;
  //square drawing
  for (int y = 0; y < width; y++)
  {
   
    for (int x = 0; x < width; x++)
    {
      int distance = Math.max(Math.abs(x), Math.abs(y));

     if (  (y == 0) || (x == 0) || (y == width - 1)||(x == width - 1) )
   {
    System.out.print("#");
   }

     else if (  (y == 1) || (y==width-2) )
   {
    System.out.print(" ");
   }

   else if (  (x == 1) || (x == width-2) )
   {
    System.out.print(" ");
   }

   else
     System.out.print("#");
   
   
      }
     
    System.out.println();
  }
 
 }catch(InputMismatchException ime)
   {
    System.out.println("You didn't enter an integer.");
     return;
   }

}
}


This post was edited by bakalolo on Mar 26 2013 08:13pm
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Apr 3 2013 02:04am
321 p1

Code
import java.awt.*;
import javax.swing.*;


public class project322 {

/**
 * @param args
 */
public static void main(String[] args) {
 appW content = new appW();
 
 JFrame frame = new JFrame("Library Catalog");
 frame.setContentPane(content.container);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.pack();
 frame.setSize(600, 400);
 frame.setVisible(true);
 
}

}


Code
                                                                   
/*******************

PrintSQLTable.java
Connect to db2 database

NOTE: Run using "java -cp /opt/ibm/db2/V9.7/java/db2jcc.jar:. PrintSQLTable" in command line

*******************/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import java.util.*;


public class libCatalog {

final static String dbdriver = "com.ibm.db2.jcc.DB2Driver";//URL to DB2 driver
final static String dburl = "jdbc:db2://localhost:50000/ICSPROJ";//port for database
final static String dbuser = "db2inst1";//username
final static String dbpassword = "89";//password
final static String dbtable = "book";//table in database
Connection connection=null;

public libCatalog() throws Exception{
 //load driver
 Class.forName(dbdriver);

 //start connection to db2
 connection = DriverManager.getConnection(dburl, dbuser,dbpassword);
}
public String sqlSearch(String field, String value) throws Exception{
 
 //needed to execute an sql statement
 Statement statement = connection.createStatement();

 //store result of statement
 ResultSet resultSet = statement.executeQuery("SELECT * FROM " + dbtable + " WHERE "+ field+" =  '"+value+"'");

 StringBuilder tableContents = new StringBuilder("");
 
 ResultSetMetaData metaData = resultSet.getMetaData();//get result set data types
 int noOfColumns = metaData.getColumnCount();

 //format column headers etc.
 //-------------------------------------
 for (int i = 1; i <= noOfColumns; i++) {
  tableContents.append(metaData.getColumnName(i) + " \t ");
 }
 tableContents.append("\n");
 int sbLength = tableContents.length();
 for (int i = 0; i < sbLength; i++)
  tableContents.append("-");
 tableContents.append("\n");
 int headerLength = tableContents.length();
 //-------------------------------------

 //add each table entry column-by-column
 
 while (resultSet.next()) {
  for (int i = 1; i <= noOfColumns; i++) {
   
   tableContents.append(resultSet.getString(i) + " \t ");
  }
  tableContents.append("\n");
 }
 
 //check that data exists
 if (tableContents.length() == headerLength)
  tableContents.append("No data found");
 
 
 return tableContents.toString();
}

public String showTable() throws Exception{
 
 //needed to execute an sql statement
 Statement statement = connection.createStatement();

 //store result of statement
 ResultSet resultSet = statement.executeQuery("SELECT * FROM " + dbtable);

 StringBuilder tableContents = new StringBuilder("");
 
 ResultSetMetaData metaData = resultSet.getMetaData();//get result set data types
 int noOfColumns = metaData.getColumnCount();

 //format column headers etc.
 //-------------------------------------
 for (int i = 1; i <= noOfColumns; i++) {
  tableContents.append(metaData.getColumnName(i) + " \t ");
 }
 tableContents.append("\n");
 int sbLength = tableContents.length();
 for (int i = 0; i < sbLength; i++){
  tableContents.append("-");
 }
 tableContents.append("\n");
 int headerLength = tableContents.length();
 //-------------------------------------

 //add each table entry column-by-column
 
 while (resultSet.next()) {
  for (int i = 1; i <= noOfColumns; i++) {
   
   tableContents.append(resultSet.getString(i) + " \t ");
  }
  tableContents.append("\n");
 }
 
 //check that data exists
 if (tableContents.length() == headerLength){
  tableContents.append("No data found");
 }
 
 return tableContents.toString();
}
public void upDate(String callNum, int x) throws Exception{
 String sql =
   "UPDATE BOOK " +
   " SET STOCK = ?" +
   "WHERE CALL# = ?";
 PreparedStatement pstmt = connection.prepareStatement(sql);
 if(x>0){
  pstmt.setString(1, ""+1);
  pstmt.setString(2, (callNum));
  pstmt.executeUpdate();
 }

 if(x<0){
  pstmt.setString(1, ""+0);
  pstmt.setString(2, (callNum));
  pstmt.executeUpdate();
 }  
 
 
}




}


Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class appW implements ActionListener{
String me ="";
protected JPanel container;

protected JPanel searchArea;
protected JButton button1;
protected JTextField field1;
protected JComboBox box1;

protected JPanel displayArea;
protected JTextPane textPane1;
protected JScrollPane scrollPane1;

protected JPanel checkArea;
protected JTextField field2;
protected JButton in;
protected JButton out;

public appW(){
 this.container = new JPanel();
 container.setLayout(new BorderLayout());
 
 this.searchArea = new JPanel();
 searchArea.setLayout(new BorderLayout());
 button1 = new JButton("Search");
 button1.addActionListener(this);//actionevent
 field1 = new JTextField();
 String[] box1Fields = {"AUTHOR","TITLE","CALL#", "GENRE"};
 JComboBox box1 = new JComboBox(box1Fields);
 box1.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent ae){
   JComboBox cb = (JComboBox)ae.getSource();
   me = (String)cb.getSelectedItem();
   textPane1.setText("Search book by "+me);
  }
 });
 //box1.addActionListener(this);
 searchArea.add(button1, BorderLayout.LINE_END);
 searchArea.add(field1,BorderLayout.CENTER);
 searchArea.add(box1,BorderLayout.LINE_START);
 //add the searchArea panel to the top of container
 container.add(searchArea,BorderLayout.PAGE_START);
 
 
 displayArea = new JPanel();
 displayArea.setLayout(new BorderLayout());
 textPane1 = new JTextPane();
 textPane1.setEditable(false);
 textPane1.setContentType("text");
 textPane1.setText("Search books by ANY CRITIERIA (show all books in database)");
 scrollPane1 = new JScrollPane(textPane1);
 displayArea.add(scrollPane1, BorderLayout.CENTER);
 //add the display pane to the middle of container
 container.add(displayArea, BorderLayout.CENTER);
 
 checkArea = new JPanel();
 checkArea.setLayout(new BorderLayout());
 field2 = new JTextField();
 in = new JButton("Return");
 in.addActionListener(this);
 out = new JButton("Check Out");
 out.addActionListener(this);
 checkArea.add(in,BorderLayout.LINE_START);
 checkArea.add(out,BorderLayout.LINE_END);
 checkArea.add(field2, BorderLayout.CENTER);
 container.add(checkArea,BorderLayout.PAGE_END);
 
 
}

public void actionPerformed(ActionEvent ae){
 String currentSelection = "";
 
 try{
 
 
 if(ae.getSource()==button1){
  libCatalog table = new libCatalog();
  if(field1.getText().length() == 0){
   textPane1.setText(table.showTable());
  }
  else {
   textPane1.setText(table.sqlSearch(me,field1.getText()));
  }
 }
 if(ae.getSource()== in){
  libCatalog table = new libCatalog();
  if(field2.getText().length() ==0){
   JOptionPane.showMessageDialog(null,"Error:  You didn't enter a Call#");
  }
  else{
   table.upDate(field2.getText(), 5);
   JOptionPane.showMessageDialog(null,"Book returned!");
  }
 }
 
 if(ae.getSource()== out){
  libCatalog table = new libCatalog();
  if(field2.getText().length() ==0){
   JOptionPane.showMessageDialog(null,"Error:  You didn't enter a Call#");
  }
  else{
   table.upDate(field2.getText(), -5);
   JOptionPane.showMessageDialog(null,"Book borrowed!");
  }
 }
 /*
 JComboBox cb = (JComboBox)ae.getSource();
 currentSelection = (String)cb.getSelectedItem();
 textPane1.setText((String)cb.getSelectedItem());
 */
 }catch(Exception e){
  JOptionPane.showMessageDialog(null,"Error: " + e);
 }
}


}
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Apr 19 2013 01:45am
311 SWDA1

Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;


public class tour implements ActionListener {
protected JPanel CONTAINER;
protected JPanel container;//top level container

protected JPanel inputArea;
protected JPanel inputAreaA;
protected JTextField input1;
protected JTextField input2;
protected JLabel label1;
protected JLabel label2;
protected JButton button1;
protected JTextField input3;
protected JLabel label3;//starting time label

protected JPanel listArea;
protected DefaultListModel listM;
protected JList list;
protected JLabel pickDes;
protected JScrollPane scroll;
protected JButton button2;

protected JPanel displayArea;
protected JTextPane display;
protected JScrollPane result;
protected JScrollPane scroll2;



public tour(){
 container = new JPanel();
 container.setLayout(new BorderLayout());
 
 //code for inputArea-----------------------------------------
 inputArea = new JPanel();
 inputArea.setLayout(new BoxLayout(inputArea, BoxLayout.Y_AXIS));
 inputAreaA = new JPanel();
 inputAreaA.setLayout(new BorderLayout());
 input1 = new JTextField();
 input1.setText("http://pearl.ics.hawaii.edu/~sugihara/courses/ics311s13/assign_p1_test_data/digraph01.txt");
 input1.addActionListener(this);
 input2 = new JTextField();
 input2.setText("http://pearl.ics.hawaii.edu/~sugihara/courses/ics311s13/assign_p1_test_data/attractions01.txt");
 input2.addActionListener(this);
 input3 = new JTextField();
 input3.setText("9:45:00");
 label1 = new JLabel("Please enter graph url here.                    ");
 label2 = new JLabel("Please enter attraction url here.               ");
 label3 = new JLabel("Start Time");
 button1 = new JButton("Show Destinations");
 //button1.setEnabled(false);
 button1.addActionListener(this);
 inputArea.add(label1);  
 inputArea.add(input1);
 inputArea.add(label2);
 inputArea.add(input2);
 
 inputAreaA.add(button1,BorderLayout.LINE_START);
 inputAreaA.add(input3, BorderLayout.CENTER);
 inputAreaA.add(label3, BorderLayout.LINE_END);
 
 inputArea.add(inputAreaA);
 //add inputArea to container
 container.add(inputArea, BorderLayout.PAGE_START);
 
 //code for checkbox area-------------------------------------
 listArea = new JPanel();
 listArea.setLayout(new BorderLayout());
 listM = new DefaultListModel();
 list = new JList(listM);
 list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
 scroll = new JScrollPane(list);
 pickDes = new JLabel();//Should say pick destination from below after link enter'd
 button2 = new JButton("Get my schedule!");
 button2.addActionListener(this);
 //button2.setEnabled(false);
 listArea.add(pickDes, BorderLayout.PAGE_START);
 listArea.add(scroll, BorderLayout.CENTER);
 listArea.add(button2,BorderLayout.PAGE_END);
 container.add(listArea, BorderLayout.CENTER);
 
 //code for result area--------------------------------------
 displayArea = new JPanel();
 displayArea.setLayout(new BorderLayout());
 display = new JTextPane();
 scroll2 = new JScrollPane(display);
 displayArea.add(scroll2, BorderLayout.CENTER);
 //container.add(displayArea, BorderLayout.PAGE_END);
 CONTAINER = new JPanel();
 CONTAINER.setLayout(new BorderLayout());
 CONTAINER.add(container, BorderLayout.LINE_START);
 CONTAINER.add(displayArea, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent ae){

 try{
  ArrayList<Destination> destinations =  new ArrayList<Destination>();;
 //----------------action event handler when "Enter" is clicked--------------
 if((ae.getSource() == input1) || (ae.getSource() == input2) ){
  button1.setEnabled(true);
 }
 if (ae.getSource() == button1){
  display.setText("");
  listM.clear();
  urlValidate url1v = new urlValidate(input1.getText());
  urlValidate url2v = new urlValidate(input2.getText());
  if(!url1v.isVal() || !url2v.isVal()){
   JOptionPane.showMessageDialog(null, "You've entered an invalid url, please try again.");
  }
  else{
   //first sanitize the 2 urls then extract destination strings from url2
   url1v.sanitize();
   url2v.sanitize();
   
   
   ArrayList<String> data = new ArrayList<String>();
   data = url2v.getData();
   //get the destination string from data and add to destinations
   for(int x = 1; x<data.size(); x++){
    Destination des = new Destination(data.get(x));
    destinations.add(des);
   
   }
   //populate list with destination
   for(int x = 0; x<destinations.size(); x++){
    listM.addElement(destinations.get(x));
   }
   
   
  }
 }
 //If Get my Schedule button is clicked...
 if(ae.getSource() == button2){
 
  urlValidate url1v = new urlValidate(input1.getText());
  urlValidate url2v = new urlValidate(input2.getText());
  if(!url1v.isVal() || !url2v.isVal()){
   JOptionPane.showMessageDialog(null, "Error: Invalid URL(s)");
  }
  else{
   url1v.sanitize();
   url2v.sanitize();
   ArrayList<String> data = new ArrayList<String>();
   data = url2v.getData();
   
   for(int x = 1; x<data.size(); x++){
    Destination des = new Destination(data.get(x));
    destinations.add(des);
   }
   
   ArrayList<Destination> DSelection = new ArrayList<Destination>();
   int[] index;
   index = list.getSelectedIndices();
   if(index.length ==0){
    return;
   }
   for(int x = 0;x<index.length; x++){
    Destination d = destinations.get(index[x]);
    System.out.println(index[x]);
    DSelection.add(d);
   }
   
   RoadMap map = new RoadMap(url1v.toString());
   BruteForce alg = new BruteForce(map, url2v.toString(), input3.getText(), DSelection);
   alg.Optimize();
   alg.CalcBestRoute();
   if(DSelection.size()>1){
    if((alg.TourDuration(alg.bestroute, false)) > 24*3600){
     display.setText("Sorry, you can not schedule all the destination you selected into one day."
       +"\nPlease reduce the number of selections, try a different combination of" +
       " \ndestinations, or set an earlier starting time.");
    }
    else{
     display.setText(alg.content.toString());
    }
   }
   else{
    display.setText(alg.content.toString());
   }
  }
 }
 
 }catch(Exception e){
  JOptionPane.showMessageDialog(null, "Error: " + e);
 }
}

}

Code
import java.util.*;


public class RoadMap{

private int numVertex;
private int[][] matrix;
protected ArrayList<String> data;
protected String[] tokens;
/*
 * Constructor for RoadMap that creates a 2d array and loads it with the
 * edge values given in the page.
 */
public RoadMap(String url)throws Exception
{
 urlValidate val = new urlValidate(url);
 val.sanitize();
 data = new ArrayList<String>();
 data = val.getData();
 /*
  * After data has the string representation of the page, each line of the page is processed
  * by looping through data
  */

 for(int x =0; x<data.size();x++){
  String delim = "\\t{1,}";
  //reads the number of vertices in the first line and makes appropriate sized array.
  if(x == 0){
   tokens = ((String) data.get(x)).split(delim);
   matrix = new int[Integer.parseInt(tokens[0])][Integer.parseInt(tokens[0])];
   numVertex = Integer.parseInt(tokens[0]);
   for(int i=0;i<Integer.parseInt(tokens[0]);i++){
    for(int j=0;j<Integer.parseInt(tokens[0]);j++){
     if(j == i){
      matrix[i][j] = 0;
     }
     else{
      matrix[i][j] = 99999;
     }
    }
   }
   
  }
  else{
   //
   String[] tokens2 = ((String) data.get(x)).split(delim);
   //takes the value of first/second number as the value of matrix being referenced, insert third number
   matrix[Integer.parseInt(tokens2[0])-1][Integer.parseInt(tokens2[1])-1] = convertTime(tokens2[2]);
  }
 }
 
 
}

public void Print()
{
 for(int x = 0; x < Integer.parseInt(tokens[0]);x++){
  for(int y = 0;y < Integer.parseInt(tokens[0]); y++){
   if(this.matrix[x][y] <10){
    System.out.print("0000" + this.matrix[x][y] + " ");
   }
   
   else if(this.matrix[x][y] <100){
    System.out.print("000" + this.matrix[x][y] + " ");
   }
   
   else if(this.matrix[x][y] <1000){
    System.out.print("00" + this.matrix[x][y] + " ");
   }
   else if(this.matrix[x][y] <10000){
    System.out.print("0" + this.matrix[x][y] + " ");
   }
   else{
    System.out.print(this.matrix[x][y] + " ");
   }
  }
  System.out.println();
 }
 
}

 
public int GetDistanceFrom(int start, int finish)
{
 return this.matrix[start][finish];
}

public int[][] getMatrix(){
 return this.matrix;
}
public static int convertTime(String input){
 String delim = ":";
 String[] timeToken = input.split(delim);
 return 3600 * Integer.parseInt(timeToken[0]) + 60 * Integer.parseInt(timeToken[1]) + Integer.parseInt(timeToken[2]);
}



}

Code
import org.apache.commons.validator.UrlValidator;

import java.net.*;
import java.util.*;
import java.io.*;


public class urlValidate {

private String url;
private ArrayList<String> data;
/*
 * Constructor method that takes a url string as parameter
 */
public urlValidate(String input){
 this.url = input;
}
/*
 * checks if this.url is valid using apache validator
 */
@SuppressWarnings("deprecation")
public boolean isVal(){
 UrlValidator urlValidator = new UrlValidator();
 if(urlValidator.isValid(url)){
  return true;
 }
 else{
  return false;
 }
}
/*
 * Sanitizes the string this.url
 */
public void sanitize(){
 try{
  URL x = new URL(url);
  URI aURI = new URI(x.getProtocol(), x.getUserInfo(), x.getHost(), x.getPort(), x.getPath(), x.getQuery(), "");
  url = aURI.toURL().toString();
 
  }catch(MalformedURLException e){
   System.out.println("bad url");
  }catch(URISyntaxException e){
   System.out.println("bad uri");
  }

 
}
/*
 * Returns an arraylist containing the data from the website.
 */
public ArrayList<String> getData(){
 try{
 this.data = new ArrayList<String>();
 URL aUrl = new URL(this.url);
 BufferedReader in = new BufferedReader(new InputStreamReader(aUrl.openStream()));
 
 String inputLine;
 while((inputLine = in.readLine())!=null){
  data.add(inputLine);
 }
 in.close();
 
 return data;
 } catch(IOException e){
  return null;
 }
 
}

public String toString(){
 return url;
}


}

Code
import java.util.*;

public class BruteForce {

public class Road
{
 public Destination from;
 public Destination to;
};

protected RoadMap mymap;
int startTime;
ArrayList<Road> bestroute;
ArrayList<Destination> destinationList;
StringBuilder content;
/*
 * takes roadmap, destination url address, starting time as string
 */
public BruteForce(RoadMap map, String destinationURL, String tourS, ArrayList<Destination> D)throws Exception
{
 //to hold the data from destination url
 ArrayList<String> data = new ArrayList<String>();
 startTime = convertTime(tourS);
 mymap = map;
 bestroute = new ArrayList<Road>();
 
 //create a new urlValidate object with the destination url, get the data arrayList
 urlValidate desURL = new urlValidate(destinationURL);
 desURL.sanitize();
 data = desURL.getData();
 this.destinationList = D;
 //int zzz = convertTime(data.get(3));
 /*
 destinationList = new ArrayList<Destination>();
 
 for(int x = 0; x < data.size(); x++){
  if(x > 0){
   Destination des = new Destination(data.get(x));
   destinationList.add(des);
   
  }
 }
 */
 //destinationList.remove(0);
 //destinationList.remove(destinationList.size()-1);
 //destinationList.remove(destinationList.size()-2);
 //destinationList.remove(destinationList.size()-3);
 
 
}
public void Optimize(){
 //outer loop 1 iteration per line to cover whole matrix
 for(int x =0; x < mymap.getMatrix().length; x++){
 
  shortestPath me = new shortestPath(mymap.getMatrix(),x);
  me.getShortestPath();
 
  for(int i = 0; i< mymap.getMatrix().length; i++){
   for(int j = 0; j< mymap.getMatrix().length; j++){
    if(i == x){
     mymap.getMatrix()[i][j] = me.sValues[j];
    }
   }
  }
 }
}

public boolean CalcBestRoute()
{
 if(destinationList.size()<2){
  tourDuration();
 }
 else{
  ArrayList<Road> route = new ArrayList<Road>();
  TryRoutes(route);
 }
 return true;
}


public void PrintN()
{
 PrintNUM(this.bestroute);
}

public void PrintNUM(ArrayList<Road> route)
{
 if(TourDuration(bestroute, false)> 3600 * 24){
  System.out.println("Really Sorry, you can not schedual all the destination you selected into one day."
    +"\nPlease reduce the number of selections or try a different combination of destinations.");
 }
 else{
  System.out.println("Route Distance: "+TourDuration(route, false));
  System.out.println("=======================================================");
  this.TourDuration(route, true);
 
 }
}

private int TryRoutes(ArrayList<Road> route)
{
 //when route<> has number of destinations in RoadMap, check if bestroute
 if (route.size()== destinationList.size()-1)
 {
  //Print(route);
  if (IsBestRoute(route)==true)
  {
   bestroute=route;
   
  }
 }
 else
 {

  //loop from 0 to total number vertices
  for(int i=0;i< destinationList.size();i+=1)
  {
   Road nextroad = new Road();
   //set the starting location to 0 if this list of route<> is empty
   if (route.isEmpty()==true){
   
    for(int x = 0; x < destinationList.size();x++){
     nextroad.from = destinationList.get(x);
     nextroad.to = destinationList.get(i);
     //make sure we visit new cities only
   
    }
   
   
   }
   //-----------------------------
   else{
   
    Road lastroad = route.get(route.size()-1);
    nextroad.from = lastroad.to;
   
    nextroad.to = destinationList.get(i);
    //make sure we visit new cities only
   
   }
   
   if (nextroad.to == nextroad.from)
   {
    continue;
   }
   if (isOnRoute(route, nextroad.to))
   {
    continue;
   }
   
   ArrayList<Road>testroute = new ArrayList<Road>(route);
   testroute.add(nextroad);
   TryRoutes(testroute);
  }
 }
 return 0;
}

private boolean IsBestRoute(ArrayList<Road> route)
{
 if ( TourDuration(this.bestroute, false) > TourDuration(route, false) )
 {
  return true;
 }
 else
 {
  return false;
 }
}

 
public int TourDuration(ArrayList<Road> route, boolean print){
 //store the tour as string inside content
 content = new StringBuilder("");
 
 if (route.isEmpty()==true)
 {
  return java.lang.Integer.MAX_VALUE;
 }
 int currentT = startTime;
 for(int x = 0; x<route.size(); x++){
  Road road = route.get(x);
  if(x == 0){
   if(print){
    System.out.println("Starting time : " + convertTime(currentT));
   }
   content.append("Starting time : " + convertTime(currentT) + " .\n");
  }
  //For the first road, process both road.from/road.to, for rest process only road.to
  if(x == 0){
   Destination des = road.from;
   if(des.inTimeSlot(currentT, currentT + des.getDuration())){
    currentT += des.getDuration();
    if(print){
     System.out.println("Stay at " + road.from.toString() + " from "+ (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT));
    }
    content.append("Stay at " + road.from.toString() + " from "+ (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT)+ ".\n");
   }
   else{
   
    ArrayList<Integer> tSlots = des.getTimePoints();
    for(int t = 0; t < tSlots.size(); t+=2){
     if(tSlots.get(t) >= currentT){
      currentT = tSlots.get(t) + des.getDuration();
      if(print){
       System.out.println("Stay at " + road.from.toString() + " from " + (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT));
      }
      content.append("Stay at " + road.from.toString() + " from " + (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT) + ".\n");

      break;
     }
    }
   }
   
  }
  if(print){
   System.out.println(convertTime(currentT)+" is current time, " +convertTime(mymap.GetDistanceFrom(road.from.getLocation(), road.to.getLocation()))+" to travel to next des..");
  }
  content.append(convertTime(currentT)+" is current time, " +convertTime(mymap.GetDistanceFrom(road.from.getLocation(), road.to.getLocation()))+" to travel to next destination. \n");

  currentT+= mymap.GetDistanceFrom(road.from.getLocation(), road.to.getLocation());
  if(print){
   System.out.println("Arrive at " + road.to.toString()+" at " + convertTime(currentT));
  }
  content.append("Arrive at " + road.to.toString()+" at " + convertTime(currentT) + ".\n");
  Destination dest = road.to;
 
  if(dest.inTimeSlot(currentT, currentT + dest.getDuration())){
   currentT += dest.getDuration();
   if(print){
    System.out.println("Stay at " + road.to.toString() + " from " + convertTime((currentT - dest.getDuration()))+ "-"+convertTime(currentT));
   }
   content.append("Stay at " + road.to.toString() + " from " + convertTime((currentT - dest.getDuration()))+ "-"+convertTime(currentT)+".\n");
  }
  else{
   boolean mark = false;
   ArrayList<Integer> tSlots = dest.getTimePoints();
   for(int t = 0; t < tSlots.size(); t+=2){
    if(tSlots.get(t) >= currentT){
     currentT = tSlots.get(t) + dest.getDuration();
     mark = true;
     if(print){
      System.out.println("Stay at " + road.to.toString() + " from "+ convertTime(currentT - dest.getDuration())+ "-"+convertTime(currentT));
     }
     content.append("Stay at " + road.to.toString() + " from "+ convertTime(currentT - dest.getDuration())+ "-"+convertTime(currentT)+".\n");

     break;
    }
   }
   if(!mark){
    currentT += 99999;
   }
  }
 }
 if(print){
  System.out.println("ENDING TIME: " + convertTime(currentT)+".");
  //System.out.println("TOTAL TIME OF TOUR IS " + convertTime(currentT - startTime));
  System.out.println("TOTAL TIME OF TOUR IS " + currentT + ".");
 }
 content.append("ENDING TIME: " + convertTime(currentT)+"\n");
 content.append("TOTAL TIME OF TOUR IS " + convertTime(currentT - startTime)+".\n");
 return currentT;
}
public void tourDuration(){
 int currentT = startTime;
 content = new StringBuilder();
 Destination DES = destinationList.get(0);
 content.append("Starting time: " + convertTime(currentT)+"\n");
 if(DES.inTimeSlot(currentT, currentT + DES.getDuration())){
  content.append("Stay at "+DES+" from " + convertTime(currentT)+"-"+convertTime(currentT + DES.getDuration())+"\n");
  currentT+= DES.getDuration();
 }
 else{
  ArrayList<Integer> tSlots = DES.getTimePoints();
  for(int t = 0; t < tSlots.size(); t+=2){
   if(tSlots.get(t) >= currentT){
    content.append("Stay at " + DES + " from " + (convertTime(tSlots.get(t))+ "-"+convertTime(tSlots.get(t)+DES.getDuration()) + ".\n"));
    currentT = tSlots.get(t) + DES.getDuration();
    break;
   }
  }
 }
 content.append("ENDING TIME: " + convertTime(currentT)+"\n");
 content.append("TOTAL TIME OF TOUR IS " + convertTime(currentT - startTime)+".\n");
 
}
private boolean isOnRoute(ArrayList<Road> route, Destination city)
{
 for(int i=0;i<route.size();i+=1)
 {
  Road road = route.get(i);
  if (road.from==city || road.to==city)
  {
   return true;
  }
 }
 return false;
}

public static int convertTime(String input){
 String delim = ":";
 String[] timeToken = input.split(delim);
 return 3600 * Integer.parseInt(timeToken[0]) + 60 * Integer.parseInt(timeToken[1]) + Integer.parseInt(timeToken[2]);
}
public static String convertTime(int input){
 int hour;
 int minute;
 int second;
 int left;
 
 if(input > 3600){
  hour = input / 3600;
  left = input % 3600;
  minute = left / 60;
  left = left % 60;
  second = left;
 }
 else if(input > 60){
  hour = 0;
  minute = input / 60;
  second = input % 60;
 }
 else{
  hour = 0;
  minute = 0;
  second = input;
 }
 String min = Integer.toString(minute);
 String sec = Integer.toString(second);
 if(minute < 10){
  min = '0' + min;
 }
 if(second < 10){
  sec = '0' + sec;
 }
 return  "" + hour + ":" + min + ":" + sec;
}

}

Code

/*
* An implementation of Dijstra's algorithm.
*
*/
public class shortestPath {
private int[][] map;
int[] sValues;
boolean[] cChecked;
boolean[] rChecked;
private int origin;
private int x;

public shortestPath(int[][] me, int start){
 x  = 0;
 this.map = me;
 this.origin = start;

 
 sValues = new int[me.length];
 cChecked = new boolean[me.length];
 rChecked = new boolean[me.length];
 rChecked[origin] = true;
 cChecked[origin] = true;
 for(int x = 0; x < sValues.length; x++){
  if(x != start)
  sValues[x] = 99999;
 }

}
/*
 * Takes an input target, finds lowest value in target row, save that
 * value into sValues, recursively calls getShortestPath with new target rows
 *
 */
public void getShortestPath(){
 if( x > map.length){
  return;
 }
 else{
 
  int lowest = Integer.MAX_VALUE;
 
 
  //loop through the array to find the target row
  for(int x = 0; x < map.length; x++){
   for(int y = 0; y < map.length; y++){
    //if current row is marked true in rChecked
    if(rChecked[x] == true){
     //make sure it's not counting the path to itself
     if((x != y) && (cChecked[y] == false)){
      //if current item < lowest value, set it to lowest value
      if(map[x][y] + sValues[x] < lowest){
       lowest = map[x][y] + sValues[x];
      }
     }
    }
   }
  }
 
  //check all columns that have lowest value
  for(int x = 0; x < map.length; x++){
   for(int y = 0; y < map.length; y++){
    if( (lowest == map[x][y] + sValues[x]) && (cChecked[y] == false) ){
     rChecked[y] = true;
     cChecked[y] = true;
     sValues[y] = map[x][y] + sValues[x];
    }
   }
  }
  /*
  System.out.println("UPDATED cCHecked---");
  for(boolean a : cChecked){
   System.out.print(a + " ");
   
  }
  */
 
  x++;
  getShortestPath();
 
 }
}

public void Print(){
 System.out.println();
 for(int me : sValues){
  System.out.print(me + " ");
 }
}


}

Code
import java.util.*;


public class Destination {
private int location;
private String name;
private String delim = "\\t{1,}";
private String[] tokens;
private String[] timeOpen;
private ArrayList<Integer> timePoints;


int start;
int finish;
/*
 * constructor that takes line of txt file as input
 * @param line the input line to be processed
 */
public Destination(String line){
 tokens = line.split(delim);
}

public String getName(){
 this.name = tokens[1];
 return name;
}

public int getLocation(){
 this.location = Integer.parseInt(tokens[0]);
 return location - 1;
}

public int getDuration(){
 return convertTime(tokens[2]);
}
public void setTime(int s, int f){
 this.start = s;
 this.finish = f;
}
public int getStart(){
 return start;
}
public int getFinish(){
 return finish;
}
public ArrayList<Integer> getTimePoints(){
 timePoints = new ArrayList<Integer>();
 
 for(int x = 3; x < tokens.length; x++){
  timeOpen = tokens[x].split("-");
  for(int z = 0; z < timeOpen.length; z++){
   timePoints.add(convertTime(timeOpen[z]));
  }
 }
 return timePoints;
}
public boolean inTimeSlot(int sTime, int eTime){
 boolean me = false;
 this.getTimePoints();
 //System.out.println(timePoints.toString());
 for(int a = 0; a < timePoints.size(); a+=2){
  if((sTime >= timePoints.get(a))  && (eTime <= timePoints.get(a+1))){
   me = true;
  }
 }
 return me;
}
public String toString(){
 return this.getName();
}



public static int convertTime(String input){
 String delim = ":";
 String[] timeToken = input.split(delim);
 return 3600 * Integer.parseInt(timeToken[0]) + 60 * Integer.parseInt(timeToken[1]) + Integer.parseInt(timeToken[2]);
}
}

Code
import java.awt.Dimension;

import javax.swing.*;


public class SWDA1 {

/**
 * @param args
 */
public static void main(String[] args) {
 
 JFrame frame = new JFrame("Tour Schedule");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setPreferredSize(new Dimension(1000, 700));
 tour app = new tour();
 frame.setContentPane(app.CONTAINER);
 frame.pack();
 frame.setVisible(true);

 
}

}

Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Apr 23 2013 04:07pm
311 SWDA1 link:
http://www2.hawaii.edu/~yuep/SWDApp/page.html

This post was edited by bakalolo on Apr 23 2013 04:08pm
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Apr 24 2013 05:40pm
322 p1 new upDate() method
Code
public void upDate(String callNum, int x) throws Exception{
 String in = "STOCK+1";
 String sql =
   "UPDATE book " +
   "SET STOCK = ? " +
   " WHERE CALL# = ?";
 PreparedStatement pstmt = connection.prepareStatement(sql);

  int crntStock = 99;
  //needed to execute an sql statement
  Statement statement = connection.createStatement();

  //store result of statement
  ResultSet resultSet = statement.executeQuery("SELECT STOCK FROM " +
  dbtable + " WHERE CALL# = " + callNum);

  ResultSetMetaData metaData = resultSet.getMetaData();//get result set data types
  int noOfColumns = metaData.getColumnCount();
  while(resultSet.next()){
   
     crntStock = Integer.parseInt(resultSet.getString(1));
   
  }
  if(x>0){
  crntStock+=1;
  }
  else{
   
   if(crntStock <1){
    throw new IllegalArgumentException("There are no books left in stock to check out");
   }
   else{
    crntStock+=-1;
   }
  }
  pstmt.setString(1, Integer.toString(crntStock));
  pstmt.setString(2, (callNum));
  pstmt.executeUpdate();
 
}
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
Apr 29 2013 02:03pm
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
May 20 2013 04:39am
211 A10
Code
import java.util.*;

/**
* A binary search tree (BST) is a sorted ADT that uses a binary
* tree to keep all elements in sorted order.  If the tree is
* balanced, performance is very good: O(n lg n) for most operations.
* If unbalanced, it performs more like a linked list: O(n).
*
* @author Zach Tomaszewski
*/
public class BinarySearchTree<E extends Comparable<E>> implements Iterable<E>{

private TreeNode<E> root = null;
private int size = 0;
private int counter = 0;


/** Creates an empty tree. */
public BinarySearchTree() {

}
/**
 * Constructor overload
 * @param col The collection to be sorted
 */
public BinarySearchTree(Collection<E> col){
 List<E> list = new ArrayList<E>(col);
 Collections.shuffle(list);

 while(counter < list.size()){
  this.add(list.get(counter));
  counter++;
 }
}



@Override
public Iterator<E> iterator() {
 
 return new bstIterator();
}
/**
 * A implementation of BST iterator
 * @author Yue Pan
 *
 */
private class bstIterator implements java.util.Iterator<E>{
 private TreeNode<E> next;
 private TreeNode<E> last = null;

 private Stack<TreeNode> stack = new Stack<TreeNode>();


 /**
  * Constructor for bstIterator
  * next starts off at root, adds the root and all its left descendants
  * to stack.
  */
 public bstIterator(){
  this.next = root;
  while(true){
   stack.push(next);
   if(next.getLeft()!=null){
    next = next.getLeft();
   }
   else{
    break;
   }
  }
 }

 /**
  * Returns the next element in the iteration.
  */
 public E next(){

  if(stack.size() <= 0){
   throw new java.util.NoSuchElementException();
  }

  TreeNode<E> item = stack.pop();
  if(item.getRight() != null){
   stack.push(item.getRight());
   while(stack.peek().getLeft() != null){
    stack.push(stack.peek().getLeft());
   }
  }
  last = item;
  return item.getData();
 }
 /**
  * Returns true if the iteration has more elements.
  */
 public boolean hasNext(){
  return stack.size()!= 0;
 }
 /**
  * @override
  */
 public void remove(){
  if(last==null){
   throw new IllegalStateException();
  }
 
  BinarySearchTree.this.remove((last.getData()));
  last = null;
 }

}


/** Adds the given item to this BST. */
public void add(E item) {
 this.size++;
 if (this.root == null) {
  //tree is empty, so just add item
  this.root = new TreeNode<E>(item);
 }else {
  //find where to insert, with pointer to parent node
  TreeNode<E> parent = null;
  TreeNode<E> curr = this.root;
  boolean wentLeft = true;
  while (curr != null) {  //will execute at least once
   parent = curr;
   if (item.compareTo(curr.getData()) <= 0) {
    curr = curr.getLeft();
    wentLeft = true;
   }else {
    curr = curr.getRight();
    wentLeft = false;
   }
  }

  //now add new node on appropriate side of parent
  curr = new TreeNode<E>(item);
  if (wentLeft) {
   parent.setLeft(curr);
  }else {
   parent.setRight(curr);
  }
 }
}
public String toFullString(){

 return toFullString(root,"");

}
/**
 * Display the Full String version of tree.
 * @return String The String representation of tree.
 */
private String toFullString(TreeNode<E> a, String prefix){
 String str="";
 String leftP = "<";
 String rightP = ">";
 String n = "\n";
 String tempa=prefix;
 String tempb=prefix;

 if(a==null){
  return "";
 }
 else{
  str += prefix + a.getData()+n;
  if((a.getLeft()!=null)&&(a.getRight() != null)){
   tempa +=leftP;
   tempb +=rightP;
  }
  if(a.getLeft()!=null){


   if((a.getLeft()!=null)&&(a.getRight() != null)){
    str += toFullString(a.getLeft(),tempa);
   }
   else{
    prefix+= leftP;
    str += toFullString(a.getLeft(),prefix);
   }
  }
  if(a.getRight() != null){

   if((a.getLeft()!=null)&&(a.getRight() != null)){
    str += toFullString(a.getRight(),tempb);
   }
   else{
    prefix += rightP;
    str += toFullString(a.getRight(),prefix);
   }
  }
  return str;
 }

}
public String toFullTreeString(){
 
 
 return "";
}
/** Returns the greatest (earliest right-most node) of the given tree. */
private E findMax(TreeNode<E> n) {
 if (n == null) {
  return null;
 }else if (n.getRight() == null) {
  //can't go right any more, so this is max value
  return n.getData();
 }else {
  return findMax(n.getRight());
 }
}

/**
 * Returns item from tree that is equivalent (according to compareTo)
 * to the given item.  If item is not in tree, returns null.
 */
public E get(E item) {
 return get(item, this.root);
}

/** Finds it in the subtree rooted at the given node. */
private E get(E item, TreeNode<E> node) {
 if (node == null) {
  return null;
 }else if (item.compareTo(node.getData()) < 0) {
  return get(item, node.getLeft());
 }else if (item.compareTo(node.getData()) > 0) {
  return get(item, node.getRight());
 }else {
  //found it!
  return node.getData();
 }
}

/**
 * Removes the first equivalent item found in the tree.
 * If item does not exist to be removed, throws IllegalArgumentException().
 */
public void remove(E item) {
 this.root = remove(item, this.root);
}

private TreeNode<E> remove(E item, TreeNode<E> node) {
 if (node == null) {
  //didn't find item
  throw new IllegalArgumentException(item + " not found in tree.");
 }else if (item.compareTo(node.getData()) < 0) {
  //go to left, saving resulting changes made to left tree
  node.setLeft(remove(item, node.getLeft()));
  return node;
 }else if (item.compareTo(node.getData()) > 0) {
  //go to right, saving any resulting changes
  node.setRight(remove(item, node.getRight()));
  return node;
 }else {
  //found node to be removed!
  if (node.getLeft() == null && node.getRight() == null) {
   //leaf node
   return null;
  }else if (node.getRight() == null) {
   //has only a left child
   return node.getLeft();
  }else if (node.getLeft() == null) {
   //has only a right child
   return node.getRight();
  }else {
   //two children, so replace the contents of this node with max of left tree
   E max = findMax(node.getLeft());  //get max value
   node.setLeft(remove(max, node.getLeft())); //and remove its node from tree
   node.setData(max);
   return node;
  }
 }
}

/** Returns the number of elements currently in this BST. */
public int size() {
 return this.size;
}

/**
 * Returns a single-line representation of this BST's contents.
 * Specifically, this is a comma-separated list of all elements in their
 * natural Comparable ordering.  The list is surrounded by [] characters.
 */
@Override
public String toString() {
 return "[" + toString(this.root) + "]";
}

private String toString(TreeNode<E> n) {
 //would have been simpler to use Iterator... but not implemented yet.
 if (n == null) {
  return "";
 }else {
  String str = "";
  str += toString(n.getLeft());
  if (!str.isEmpty()) {
   str += ", ";
  }
  str += n.getData();
  if (n.getRight() != null) {
   str += ", ";
   str += toString(n.getRight());
  }
  return str;
 }
}


}


Code
import java.util.*;

public class Stack<TreeNode> {
 private Deque<TreeNode> data = new ArrayDeque<TreeNode>();

 public void push(TreeNode item) {
   data.addFirst(item);
 }

 public TreeNode pop() {
   return data.removeFirst();
 }

 public TreeNode peek() {
   return data.peekFirst();
 }

 public String toString() {
   return data.toString();
 }
 public int size(){
  return data.size();
 }
}

Code
/**
* A single binary tree node.
* <p>
* Each node has both a left or right child, which can be null.
*
* @author Zach Tomaszewski
*/
public class TreeNode<E> {

 private E data;
 private TreeNode<E> left;
 private TreeNode<E> right;

 /**
  * Constructs a new node with the given data and references to the
  * given left and right nodes.
  */
 public TreeNode(E data, TreeNode<E> left, TreeNode<E> right) {
   this.data = data;
   this.left = left;
   this.right = right;
 }

 /**
  * Constructs a new node containing the given data.
  * Its left and right references will be set to null.
  */
 public TreeNode(E data) {
   this(data, null, null);
 }

 /** Returns the item currently stored in this node. */
 public E getData() {
   return data;
 }

 /** Overwrites the item stored in this Node with the given data item. */
 public void setData(E data) {
   this.data = data;
 }

 /**
  * Returns this Node's left child.
  * If there is no left left, returns null.
  */
 public TreeNode<E> getLeft() {
   return left;
 }

 /** Causes this Node to point to the given left child Node. */
 public void setLeft(TreeNode<E> left) {
   this.left = left;
 }

 /**
  * Returns this nodes right child.
  * If there is no right child, returns null.
  */
 public TreeNode<E> getRight() {
   return right;
 }

 /** Causes this Node to point to the given right child Node. */
 public void setRight(TreeNode<E> right) {
   this.right = right;
 }
}

Code
import java.util.*;


public class YuepA10{
public static void main(String[] args){

 List<Integer> rList= new ArrayList<Integer>();
 Random gen = new Random();
 for(int x=0;x<5;x++){
  int a = gen.nextInt(50);
  rList.add(x);
 }
  System.out.println(rList);
  BinarySearchTree<Integer> me = new BinarySearchTree<Integer>(rList);
   
  Iterator baka = rList.iterator();
  System.out.println(baka.next());
  System.out.println(baka.next());
  System.out.println(baka.next());
  baka.remove();
  System.out.println(baka.next());
  System.out.println(baka.next());
 
  System.out.println(me.toFullString());
 
 
}

}
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
May 20 2013 04:40am
211 A9
Code
import java.util.*;

public class YuepA09 {

/**
 *
 * @param args The command line argument
 */
public static void main(String[] args) {
 try{
 for(int z = 0;z<1111;z++){
 List<Integer> me  = new ArrayList<Integer>();
 List<Integer> y  = new ArrayList<Integer>();
 
 Random pat = new Random();
 for(int x = 0; x<12;x++){
  int num = pat.nextInt(50);
  me.add(num);

 }
 System.out.println(me);


 otherSort(me);
 System.out.println(me + "quick final");
 y = me;
 mergeSort(me);
 System.out.println(me==y);
 }
 }catch(IndexOutOfBoundsException e){
  return;
 }
 
}
/**
 *
 * @param list The list to be sorted.
 */

public static <E extends Comparable<E>> void insertionSort(List<E> list){
 int size = list.size();
 int marker;
 int iMarker = 0;

 List<E> me = new ArrayList<E>();
 me = list;

 //marker marks current
 for(marker = 1; marker<size;marker++){
  //iMarker is item in sorted list being compared with current
  iMarker = 0;
  E current = me.get(marker);

  //compares current with each sorted item
  while(iMarker < marker){

   int compare = current.compareTo(me.get(iMarker));
   if(compare <= 0){

    E temp = me.remove(marker);
    if(iMarker >0){
     me.add(iMarker, temp);
    }
    else{
     me.add(0,temp);

    }
    //if location is found,break loop and compare the next element on list
    break;
   }


   iMarker++;
  }

 }

}
/**
 *Loops through the array and make every adjacent
 *group of two sorted by swapping the two when necessary.
 *Now, dealing with groups of twos
 *merge them into one group by selecting the lowest valued element from each group
   *repeatedly until all 4 elements are merged into a group of 4. Does it again
   *except this time in groups of 4.
 *This loop runs until there is only one group.
 * @param list The list to be sorted.
 */

public static <E extends Comparable<E>> void mergeSort(List<E> list){

 List<E> tempA = new ArrayList<E>();
 List<E> tempB = new ArrayList<E>();
 List<E> aux = new ArrayList<E>();
 //size of block to be merged starts at 1, doubles each run through
 int blockSize = 1;
 int marker = 0;
 boolean atEnd = false;

 
 while(blockSize<list.size()){
  atEnd = false;
  marker = 0;
  //tempA and tempB are the "blocks" to be merged
  while(atEnd == false){
   for(int x = marker; x < marker+blockSize; x++){
    try{
     tempA.add(list.get(x));
    }catch(IndexOutOfBoundsException e){
     atEnd = true;
     break;
    }
   }

   marker = marker+blockSize;
   for(int x = marker; x<marker+blockSize; x++){
    try{
     tempB.add(list.get(x));
    }catch(IndexOutOfBoundsException e){
     atEnd = true;
     break;
    }
   }
   marker = marker+blockSize;


   final int index = 0;
   //Merges tempA and tempB then add to aux<E>
   while(true){
    if(tempA.size()<=0){
     aux.addAll(tempB);
     break;
    }
    else if(tempB.size()<=0){
     aux.addAll(tempA);
     break;
    }
    else if(tempA.get(index).compareTo(tempB.get(index))<=0){
     aux.add(tempA.get(index));
     tempA.remove(index);
    }
    else if(tempB.get(index).compareTo(tempA.get(index))<=0){
     aux.add(tempB.get(index));
     tempB.remove(index);
    }

   }
   tempA.clear();
   tempB.clear();

  }
 
  list.clear();
  list.addAll(aux);
  aux.clear();
  blockSize = blockSize*2;

 }

}
/**
 * recursive implementation of quickSort
 * @param list The list to be sorted.
 */
public static <E extends Comparable<E>> void otherSort(List<E> list){
 if(list.size()<2){
  return;
 }
 E pivot;
 int small = 0;
 int big = list.size()-1;
 
 pivot = list.get(list.size()/2);
 //System.out.println(pivot + " is pivot");
 
 
 while(small < big){
  try{
  if(list.get(small)==list.get(big)){
   if(list.get(small).compareTo(pivot)<1){
    small++;
   }
   else{
    big++;
   }
  }
  while(list.get(small).compareTo(pivot)<0){
   
    small++;
   
  }
  while(list.get(big).compareTo(pivot)>0){
   
   big--;
 
  }
  E temp = list.get(small);
  list.set(small, list.get(big));
  list.set(big, temp);
  }catch(IndexOutOfBoundsException e){
   System.out.println(e);
   break;
  }
 
 
 }
 //System.out.println(list+ " sorted");
 otherSort(list.subList(0, list.lastIndexOf(pivot)));
 otherSort(list.subList(list.lastIndexOf(pivot), list.size()));
 
 
}
 

}


Code
import java.io.FileNotFoundException;
import java.io.PrintWriter;

/**
* Generates a file with a given number of random integers, one per line.
*
* @author Zach Tomaszewski
*/
public class FileGenerator {

 /**
  * Specify a number as a command line argument.  This program will then
  * output a text file named "###.txt", where ### is the given number.
  * The output file will contain the given number of random integers.
  */
 public static void main(String[] args) {
   if (args.length != 1) {
     System.out.println("Error: No command line argument given.");
     System.out.println();
     System.out.println("Usage: java FileGenerator ###");
     System.out.println("where ### is a number.");
     return; //quit
   }

   //convert arg
   int lines;
   try {
     lines = Integer.parseInt(args[0]);
   }catch (NumberFormatException e) {
     System.out.println("Error: Command line argument not an integer.");
     return; //quit
   }
   
   //write lines to file
   String output = lines + ".txt";
   try {
     PrintWriter fileout = new PrintWriter(new java.io.File(output));
     java.util.Random rand = new java.util.Random();
     for (int i = 0; i < lines; i++) {
       fileout.println(rand.nextInt());
     }
     fileout.close();
   }catch (FileNotFoundException e) {
     System.out.println("Error: Could not write to output file: " +
         e.getMessage());
   }
 }
}
Member
Posts: 20,928
Joined: Mar 18 2009
Gold: 435,910.13
May 20 2013 04:45am
211 A8

Code
import java.awt.*;

import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import java.net.*;


public class ticTacToe extends JApplet implements ActionListener{
   protected JPanel container;
   private JPanel top;
   private JPanel middle;
   private JPanel bottom;
   private JLabel whoWon, pWins, cWins;
   private JButton reset;
   private JButton[] move;
   private int dice = 2;
   private int compW = 0;
   private int playerW = 0;
   
   /**
    * constructor that creates the object
    *
    */
   
   public void init(){
   
    Container tContainer = getContentPane();
       this.container = new JPanel();
       container.setLayout(new BorderLayout());
       container.setPreferredSize(new Dimension(400,400));
       
       //adds jlabel to top then top to container
       this.top = new JPanel();
       pWins = new JLabel("SCORE you: " + playerW);
       cWins = new JLabel("comp: " + compW + "  ------");      
       whoWon = new JLabel("YOU'RE GOING FIRST THIS ROUND...");
       this.top.add(pWins);
       this.top.add(cWins);
       this.top.add(whoWon);
       container.add(top, BorderLayout.PAGE_START);
       
       
       //adds button to middle then middle to container
       this.middle = new JPanel(new GridLayout(3,3));
       move = new JButton[9];
       for(int x = 0; x<move.length; x++){
           move[x] = new JButton();
     
           move[x].setHorizontalTextPosition(JButton.CENTER);
           move[x].setVerticalTextPosition(JButton.CENTER);
           
           middle.add(move[x]);
           move[x].addActionListener(this);
       }
       this.container.add(middle, BorderLayout.CENTER);
       
       //adds bottom panel to container
       this.bottom = new JPanel();
       reset = new JButton("RESET");
       reset.setPreferredSize(new Dimension(150,35));
       reset.addActionListener(this);
       this.bottom.add(reset);
       this.container.add(bottom,BorderLayout.PAGE_END);
       
       
    tContainer.add(container);
   
   }

    /**
     *
     * (non-Javadoc)
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent event){
     
        if(event.getSource() == this.reset){
       
       
            for(int a = 0; a<move.length;a++){
             move[a].setEnabled(true);
             move[a].setText(" ");
           
             whoWon.setText("  ");
           
            }
            if(dice%2 == 0){
          compMove();
          whoWon.setText("COMPUTER GOING FIRST THIS ROUND..");
         }
            else{
             whoWon.setText("YOU'RE GOING FIRST THIS ROUND...");
            }
            dice++;
           
        }
        else{
         
            for(int y = 0;y<move.length;y++){
             //check which button clicked
                if(event.getSource() == this.move[y]){
                 //turns the button into x and pressed
                    move[y].setEnabled(false);
                    move[y].setText("<html><font size = 12>x</font></html>");
                   
                   
                    //----------------
                    if(isDone(y)==false){
                     int q = compMove();
                     System.out.println(q);
                     if(isDone(q)){
                      if(won(q)){
                       compW++;
                       cWins.setText("comp: " + compW + "  ------");
                       for(int b = 0; b<move.length;b++){
                              move[b].setEnabled(false);
                              whoWon.setText("O WINS");
                                                       
                             }
                      }
                      else{
                       whoWon.setText("IT'S A TIE");
                      }
                     }
                    }
                    else{
                     for(int a = 0; a<move.length;a++){
                         move[a].setEnabled(false);
                                                   
                        }
                     if(won(y)){
                      playerW++;
                      pWins.setText("SCORE you: " + playerW);
                     
                      whoWon.setText("X WINS");
                     }
                     else{
                        whoWon.setText("IT'S A TIE");
                         
                         
                     }
                    }
                   
                    //--------------
                }
            }
        }
       
           
    }
    /**
     * method for ai movement, will always try to go middle
     * @return the int representation of ai movement
     *
     */
   
    public int compMove(){
     //isP(isPressed) boolean value is current button is pressed
     boolean isP = true;
     int me = 999;
     Random generator = new Random();
     if(move[4].isEnabled()){
      me = 4;
      move[me].setEnabled(false);
   move[me].setText("<html><font size = 12>o</font></html>");
   
     }
     else{
     while(isP == true){
      me = generator.nextInt(9);
      if(move[me].isEnabled()==true){
       move[me].setEnabled(false);
       move[me].setText("<html><font size = 12>o</font></html>");
       isP = false;
      }
    }
     }
     return me;
   
    }
   
   
    /**
     * checks to see if game is done
     * @param input The int representation of last move
     * @return If the game is done
     */
    public boolean isDone(int input){
     boolean done = false;
     int p = 0;
     //checks if all the buttons are pressed
     for(int z = 0;z<move.length;z++){
      if(move[z].isEnabled()==true){
       p++;
      }
     
     
     }
     if(p==0){
   done = true;
  }
     if(won(input)){
      done = true;
     }
   
     return done;
    }
    /**
     * checks to see if there is a winner
     * @param me The int representation of last move
     * @return If someone won.
     */
    public boolean won(int me){
     
     String zero = move[0].getText();
     String one = move[1].getText();
     String two = move[2].getText();
     String three = move[3].getText();
     String four = move[4].getText();
     String five = move[5].getText();
     String six = move[6].getText();
     String seven = move[7].getText();
     String eight = move[8].getText();
     
     
     switch (me){
     case 0: if( ((zero.equals(one))&&(zero.equals(two)))
       || ((zero.equals(three))&&(zero.equals(six)))
       || ((zero.equals(four))&&(zero.equals(eight)))){
        return true;
       }
       break;
   case 1: if( ((one.equals(zero))&&(one.equals(two)))
       || ((one.equals(four))&&(one.equals(seven))) ){
    return true;
    }
    break;
     case 2: if( ((two.equals(zero))&&(two.equals(one)))
       || ((two.equals(five))&&(two.equals(eight)))
       ||((two.equals(four))&&(two.equals(six)))){
    return true;
    }
    break;
     case 3: if( ((three.equals(zero))&&(three.equals(six)))
       || ((three.equals(four))&&(three.equals(five))) ){
    return true;
    }
    break;
     case 4: if( ((four.equals(zero))&&(four.equals(eight)))
       || ((four.equals(one))&&(four.equals(seven)))
       || ((four.equals(two))&&(four.equals(six)))
       || ((four.equals(three))&&(four.equals(five)))
       ){
    return true;
    }
    break;
     case 5: if( ((five.equals(two))&&(five.equals(eight)))
       || ((five.equals(four))&&(five.equals(three))) ){
    return true;
    }
    break;
     case 6: if( ((six.equals(zero))&&(six.equals(three)))
       || ((six.equals(seven))&&(six.equals(eight)))
       || ((six.equals(four))&&(six.equals(two))) ){
    return true;
    }
    break;
     case 7: if( ((seven.equals(six))&&(seven.equals(eight)))
       || ((seven.equals(four))&&(seven.equals(one))) ){
    return true;
    }
    break;
     case 8: if( ((eight.equals(seven))&&(eight.equals(six)))
       || ((eight.equals(two))&&(eight.equals(five)))
       || ((eight.equals(four))&&(eight.equals(zero)))){
    return true;
    }
    break;
   
     }
     return false;
     
    }
 
}





Code
import java.awt.*;

import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
public class YuepA08 {

/**
 * EXTRA CREDITS-----
 * -alternates between player and computer going first
 * -keeps track of player/computer wins
 * -JFrame window starts off at decent size
 * -reset button works any time, not just after a game ends
 * -bigger x/y symbols when jbuttons clicked
 * ---
 * website (http://www2.hawaii.edu/~yuep/tictactoe)
 * Assignment 08 main method
 * creates a new tic tac toe gui
 * @author Yue Pan
 * @param args The command line argumentsa
 */
public static void main(String[] args) {
 JFrame window = new JFrame("Tic Tac Toe");
 window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 ticTacToe me = new ticTacToe();
 me.init();
 window.setContentPane(me.container);
 window.pack();
 window.setVisible(true);
}



}




Go Back To User Blogs Topic List
Prev123Next
Add Reply New Topic