Quantcast
Channel: Programming Forums
Viewing all 51036 articles
Browse latest View live

Shopping Cart Using an Array of Items

$
0
0
I need help with a project that I am working on. It is a shopping cart java program that should be setup with an array size of 5 and increased at increments of 3 if you go over 5 items. When I go over 5 items in increases however it changes the item names to null. See output below.

Here is the actual assignment:

In this exercise you will complete a class that implements a shopping cart as an array of items. The file Item.java contains the definition of a class named Item that models an item one would purchase. An item has a name, price, and quantity (the quantity purchased). The file ShoppingCart.java implements the shopping cart as an array of Item objects.

1. Complete the ShoppingCart class by doing the following:
a. Declare an instance variable cart to be an array of Items and instantiate cart in the constructor to be an array holding 5 Items.
b. Fill in the code for the increaseSize method. Your code should be similar to that in the CDCollection class handout but instead of doubling the size just increase it by 3 elements.
c. Fill in the code for the addToCart method. This method should add the item to the cart and update the totalPrice instance variable (note this variable takes into account the quantity).
d. Add a getTotalPrice() method to return the totalPrice.
e.. Compile your class.

2. Write a program that simulates shopping. The program should have a loop that continues as long as the user wants to shop. Each time through the loop read in the name, price, and quantity of the item the user wants to add to the cart. After adding an item to the cart, the cart contents should be printed along with a subtotal. After the loop, print a "Please pay ..." message with the total price of the items in the cart. Compile and run this class.


OUTPUT

Enter the name of the item: Apples
Enter the unit price: .5
Enter the quantity: 1

Shopping Cart

Item Unit Price Quantity Total
Apples $0.50 1 $0.50

Total Price: $0.50

Continue shoppping (y/n)?
y
Enter the name of the item: Oranges
Enter the unit price: .5
Enter the quantity: 1

Shopping Cart

Item Unit Price Quantity Total
Apples $0.50 1 $0.50
Oranges $0.50 1 $0.50

Total Price: $1.00

Continue shoppping (y/n)?
y
Enter the name of the item: Milk
Enter the unit price: 4
Enter the quantity: 1

Shopping Cart

Item Unit Price Quantity Total
Apples $0.50 1 $0.50
Oranges $0.50 1 $0.50
Milk $4.00 1 $4.00

Total Price: $5.00

Continue shoppping (y/n)?
y
Enter the name of the item: Bread
Enter the unit price: 2
Enter the quantity: 1

Shopping Cart

Item Unit Price Quantity Total
Apples $0.50 1 $0.50
Oranges $0.50 1 $0.50
Milk $4.00 1 $4.00
Bread $2.00 1 $2.00

Total Price: $7.00

Continue shoppping (y/n)?
y
Enter the name of the item: Eggs
Enter the unit price: 2
Enter the quantity: 1

Shopping Cart

Item Unit Price Quantity Total
Apples $0.50 1 $0.50
Oranges $0.50 1 $0.50
Milk $4.00 1 $4.00
Bread $2.00 1 $2.00
Eggs $2.00 1 $2.00

Total Price: $9.00

Continue shoppping (y/n)?
y
Enter the name of the item: Bacon
Enter the unit price: 6
Enter the quantity: 1

Shopping Cart

Item Unit Price Quantity Total
Apples $0.50 1 $0.50
null
null
null
null
Bacon $6.00 1 $6.00

Total Price: $15.00

Continue shoppping (y/n)?
n
Please pay $15.0

Shop

import java.util.Scanner;

public class Shop
{
   public static void main (String[] args)
   {
      ShoppingCart cart = new ShoppingCart();
      
      Item item;
      String itemName;
      double itemPrice;
      double totalPrice = 0;
      int quantity;
      
      Scanner scan = new Scanner(System.in);
      
      String keepShopping = "y";
      
      do
         {
           System.out.print("Enter the name of the item: ");
           itemName = scan.next();
           
           System.out.print("Enter the unit price: ");
           itemPrice = scan.nextDouble();
           
           System.out.print("Enter the quantity: ");
           quantity = scan.nextInt();
           
           totalPrice +=(quantity*itemPrice);
           cart.addToCart(itemName, itemPrice, quantity);
           
           System.out.println(cart.toString());
           
           System.out.println("Continue shoppping (y/n)?");
           keepShopping = scan.next();
          }
      while (keepShopping.equals("y"));
      
      System.out.println("Please pay $"+ totalPrice);
   }
}




Shopping Cart
import java.text.NumberFormat;

public class ShoppingCart
{
    private int itemCount;      // total number of items in the cart
    private double totalPrice;  // total price of items in the cart
    private Item cart[];

    
    // -----------------------------------------------------------
    //  Creates an empty shopping cart with a capacity of 5 items.
    // -----------------------------------------------------------
    public ShoppingCart()
    {
        cart = new Item[5];
        itemCount = 0;
        totalPrice = 0.0;
    }

    // -------------------------------------------------------
    //  Adds an item to the shopping cart.
    //  Check to make sure there is room in the car first
    // -------------------------------------------------------
 

    public void addToCart(String itemName, double itemPrice, int quantity)
    {
        if (itemCount == cart.length)
        {
            increaseSize();
         }
            cart[itemCount] = new Item(itemName, itemPrice, quantity);
            totalPrice += (itemPrice * quantity);
            itemCount++;
        
    } 

    // -------------------------------------------------------
    //  Returns the contents of the cart together with
    //  summary information.
    // -------------------------------------------------------
    public String toString()
    {
        NumberFormat fmt = NumberFormat.getCurrencyInstance();

        String contents = "\nShopping Cart\n";
        contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";

        for (int i = 0; i < itemCount; i++)
            contents += cart[i] + "\n";

        contents += "\nTotal Price: " + fmt.format(totalPrice);
        contents += "\n";

        return contents;
    }

    // ---------------------------------------------------------
    //  Increases the capacity of the shopping cart by 3
    // ---------------------------------------------------------

    private void increaseSize ()
    {
        Item[] temp = new Item[cart.length + 3];

        for (int num = 0; num < cart.length; num++)
        {
            temp[num] = cart[num];
            cart = temp;
        }
    }
}




Item
import java.text.NumberFormat;

public class Item
{
    private String name;
    private double price;
    private int quantity;

    // -------------------------------------------------------
    //  Create a new item with the given attributes.
    // -------------------------------------------------------
    public Item (String itemName, double itemPrice, int numPurchased)
    {
        name = itemName;
        price = itemPrice;
        quantity = numPurchased;
    }

    // -------------------------------------------------------
    //   Return a string with the information about the item
    // -------------------------------------------------------
    public String toString ()
    {
        NumberFormat fmt = NumberFormat.getCurrencyInstance();

        return (name + "\t" + fmt.format(price) + "\t" + quantity + "\t"
            + fmt.format(price*quantity));
    }

    // -------------------------------------------------
    //   Returns the unit price of the item
    // -------------------------------------------------
    public double getPrice()
    {
        return price;
    }

    // -------------------------------------------------
    //   Returns the name of the item
    // -------------------------------------------------
    public String getName()
    {
        return name;
    }

    // -------------------------------------------------
    //   Returns the quantity of the item
    // -------------------------------------------------
    public int getQuantity()
    {
        return quantity;
    }
} 



Cinema seating class - Arrays (java)

$
0
0
Hi there,
I'm still new to Java and I'm sorry if I suck. I just need some help designing a cinema ticketing program that takes a user's input and either sell tickets, shows the current seating plan and available seats they can purchase, or show hints.

This is my main code (separate methods below but not shown here)
public static void main(String[] args) {

   displayWelcome();

        do {
            displayChoiceMenu();

            confirmInput = scan.nextLine();

            if (confirmInput.equalsIgnoreCase("PURCHASE")) {
                displayCategoryMenu();

                int userTicketCategory = scan.nextInt();
                String finalTicketCategory = getTicketCat(userTicketCategory);

                displayTypeMenu();

                int ticketChoiceType = scan.nextInt();
                String finalTicketType = getTicketType(ticketChoiceType);

                printOutput("You would like " + finalTicketCategory + " at the  " + finalTicketType + " price. Is this correct? (Y/N) ");
                String answer = scan.next();
                System.out.print(answer + "\r\n");

                if (answer.equalsIgnoreCase("Y")) {
                 printOutput("Would you like to purchase more tickets?");
                 
                    if (answer.equalsIgnoreCase("Y")){
                        
                        //would you like to list available seats?
                        
                        
                    } else if(answer.equalsIgnoreCase("N")){
                        PrintOutput("Here is where you will be seated, and the cost is:" + cost);
                       // add cost for the tickets they purchased
                        
                    }
                    
                }

            }
            
            if (confirmInput.equalsIgnoreCase("List")) {
            //show the available tickets seating plan
                
                
            }
        } while (!confirmInput.equalsIgnoreCase("Quit"));

    }



This code seems to work fine except for the bit where it asks for price or show seating because I haven't done that yet.

However I'm trying to create a separate class the shows the number of seats available and it's meant to look like the image attached.
I'm not sure how to use arrays and a class to create this seat arrangement could anyone help me?

Also does anyone know how to if they reserve a seat and enter the seat number say 'A5', it registers that seat as taken and shows an 'X' to shows it's been reserved and also how to register what category the seat is in - for example if seat A5 is located in gold silver or bronze etc.

Code printing memory location, need help

$
0
0
Hello, I am currently taking a data structures class, and we have been tasked to implement a stack. We have been given a choice to either use the stack methods that are built in to java, or to create our own. I messed around with the built-in methods and I understand them. For my assignment, however, I chose to create my own methods for pop and push and such. My issue, is that when i print my stack, it prints out the memory location of the stack, instead of the contents of the stack. Any hints to push me in the right direction would be appreciated, I'm sure it's something small but I can't seem to locate the problem.

Here is my code:

public class myStack
{

private int maxsize;
private long[] stackarray;
private int top;

   public myStack(int s)
   {
   maxsize = s;
   stackarray = new long[maxsize];
   top = -1;
   }

   public void push(long j)
   {
      if(top+1 < stackarray.length)
         stackarray[++top] = j;
   }

   public long pop()
   {
      if(isEmpty())
         return 0;
      return stackarray[top--];
   }

   /*public long top()
   {
   }*/
   
   public boolean isEmpty()
   {
      return top == -1;
   }

 /*  public boolean isfull()
   {
   return top == 
   }
   */
   
   public static void main(String[] args)
   {
   myStack yeastStack = new myStack(10);
   
   yeastStack.push(44);
   yeastStack.push(76);
   System.out.println(yeastStack);
   yeastStack.push(55);
   System.out.println(yeastStack);

   }



}


I have commented parts out that aren't finished yet, I don't believe that they are relevant to my problem.

The output is myStack@9fa8988

I have tried looking up solutions, but I haven't been able to find what I need.

C++ Trying to get my code to sum a string of numbers input from a file

$
0
0
Hello Dreamers,
This program gets input from a file and output to the screen and to a file. The difficulty I am having is summing the number I retrieve from the file for the individual numbers of sightings. It is a homework problem so any hints would be appreciated. I re-read my text and looked at practice programs. I sure hope someone here can help.

#include <fstream> // enables us to read and write files
#include <iostream> // for cin and cout
#include <cstdlib> 
#include <string>    // enables us to hold strings of characters
#include <cctype>  
using namespace std;

/*****************************************************
  main()
 *****************************************************/

int main( )
{

  int year;  
  int numberOfSpecies;
  string nameOfSpecies; 
  int numberOfRegions;
  int numberOfSightings;
  int grandTotal = 0;
  int individualTotal = 0;
  ifstream in_stream;
  ofstream out_stream;
  char next;
  int sum;
  char in_file_name[50], out_file_name[50];
  int count;

 	 	 	 
	cout << "Endangered Species Report Program\n";
	cout << "Enter the input file name: ";
	cin  >> in_file_name;
	cout << "Enter the output file name:";
	cin  >> out_file_name;
	cout << "I will read information from the file "
        << in_file_name << " and\n"
        << "summarize the report in the file "
        << out_file_name << endl;

   in_stream.open(in_file_name);
  
    if (in_stream.fail( ))
    {
     cout << "Input file opening failed.\n";
     exit(1);
    }

   out_stream.open(out_file_name);
    
	 if (out_stream.fail( ))
    {
     cout << "Output file opening failed.\n";
     exit(1);
    }
   in_stream >> year;
	cout << "Year of report " << year <<endl;
	out_stream << "Year of report " << year <<endl;
	
   in_stream >> numberOfSpecies;
   cout << "Number of species in this report " << numberOfSpecies <<endl;
   out_stream << "Number of species in this report " << numberOfSpecies <<endl;
	
		for(int i = 0; i < numberOfSpecies; i++)
		{
		
		in_stream >> nameOfSpecies;
		cout << "Species: " << nameOfSpecies;
		out_stream << "Species: " << nameOfSpecies;
			do
			{
			in_stream.get(next);//member get function
			cout << next;
			} while (next != '\n');
				
		in_stream >> numberOfRegions; 	
   	cout << "was sighted in " << numberOfRegions << " regions " <<endl;   
   	out_stream << "was sighted in " << numberOfRegions << "regions " <<endl; 			
	 		 				 
		in_stream >> numberOfSightings;
		cout << "The number of sightings is: " << numberOfSightings;
		out_stream << "The number of sightings is: " << numberOfSightings; 			
			do
			{
			in_stream.get(next);//member get function
			cout << next;
			} while (next != '\n');
			individualTotal = individualTotal + next;								     		 
  	} 
	 grandTotal = grandTotal + individualTotal;	
	 cout << "Total all species sighted = " << grandTotal << endl;
    out_stream << "Total all species sighted = " << grandTotal << endl;
  	 
	 cout << "End of Program.\n";
    in_stream.close( );
    out_stream.close( );

  return 0;
}

Help with Arrays in stat. I dont understand how to do methods.

$
0
0
Hello ,

I am having trouble understanding what i have to write in the methods area to make the program work. I have read my book and everything but i cant get my head around it. or maybe i am just confusing my self. so i would like some help of what i have to write in the methods.
here is what i have got so far.


// ArrayStatistics.java
// Written by Paul
// Completed by: 
// CS1181
// Perform statistical analysis of exam scores

import java.util.Arrays;
import java.util.Scanner;
import java.io.File;

public class ArrayStatistics 
{

	public static void main(String[] args) throws Exception
	{
		// Array to be used for statistics
		
		int[] examScores;
                int mode;
                double average;
                double standardDeviation;
		
		examScores = fillArray();
                
                    
                
                if(examScores == null)
                {
                    System.out.println("Error using exam file data");
                }
		else
                {
                    System.out.println("There are " + examScores.length + " exam scores");
                    frequencyChart(examScores);
		
                    mode = getMode(examScores);
                    System.out.println("\nMode " + mode);
		
                    average = getAverage(examScores);
                    System.out.println("Average " + average);
		
                    standardDeviation = getStandardDeviation(examScores, average);		
                    System.out.printf("Standard Deviation %.2f\n",  standardDeviation);
                    
                    displayGrades(examScores);
                }				
	}
        public static int[] fillArray(){
            File examfile = new File ("ExamScores.txt");
            Scanner input = new Scanner(examfile);
            if(examfile.exists()){
                while (input.hasNext()){
               int[] fillArray = new int [32];
               for(int a=1;a<fillArray.length;a++){
                   
                   }
                }
            }
            return
        }
        public static void frequencyChart(int[] examScores){
        
        }
        public static int getMode (int[] examScores){
            return 0;
        }
        public static double getAverage(int[] examScores){
            return 0.0;
        }
        public static double getStandardDeviation(int[]examScores, double average){
            return 0.0;
        }
        public static void displayGrades(int[] examsScores){
            
        }
}

Hashing/ Linear Probing

$
0
0
My code is supposed to read data from a file, then use a hash function and linear probing to place it into an array. The hashing works fine, but the program crashes when it hits the linear probing at line 48. Thanks in advance.

//Purpose:  This program creates a hashed list
//			(an array of size 13) using a modulo-division 
//			hash function with a linear probe to resolve 
//			collisions. It then searches the list for 
//			numbers listed in an external file.
//---------------------------------------------------

#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;

const int HTSIZE = 13;
int hashFunction(string , int );
int main() {
	
	string hashTable[HTSIZE];
	string line;
	fstream dataIn;
	int sub = 0;
	int index = 0;
	bool found;
	int collision = 0;
	
	dataIn.open("lab6.dat");
	cout << "HASH METHOD: modulo-division" << endl
		 << "COLLISION RESOLUTION: linear probe" << endl
		 << "HASHED LIST" << endl << endl
		 << "SUB" << setw(5) << "KEY" << endl;
		 
	while(dataIn)
	{
		getline(dataIn, line);
		index = hashFunction(line, line.length());
		hashTable[index] = line;
	}
	for(index = 0; index < HTSIZE; index++)
	{
		if(hashTable[index] == "")
		{
			hashTable[index] = "-1";
		}
		cout << left << setw(5) << index << hashTable[index] << endl;
	}
	dataIn.close();
	
	dataIn.open("lab6srch.dat");
	while(dataIn)
	{
		getline(dataIn, line);
		sub = hashFunction(line, line.length());
		found = false;
		
		while(hashTable[sub] != "-1" && !found)
		{
			
			if(hashTable[sub] == line)
			{
				found = true;
			}
			else
				sub = (sub + 1) % HTSIZE;
		}
		if(found)
		{
			cout <<"Yes" << endl;
		}
		else
		{
			hashTable[sub] = line;
		}
	}
		
	dataIn.close();
	for( index = 0; index < HTSIZE; index++)
	{
		cout << setw(5) << hashTable[index] << endl;
	}

	return 0;
}

int hashFunction(string insertKey, int keyLength)
{
	int sum = 0;
	
	for (int index = 0; index < keyLength; index++)
		sum = sum + static_cast<int>(insertKey[index]);
	return (sum % HTSIZE);
}

Linear search of arraylist by last name

$
0
0
I am having some trouble with linear search of a customers last name. I can't seem to get it to work. I have looked up examples but cant find many with Array Lists. Any help or insight would be appreciated. Here is my code.

import java.util.ArrayList;
import java.util.Scanner;

public class AccountDriver {

    public static void main(String[] args) {
        ArrayList<Account> al = new ArrayList<Account>();
        ArrayList<Customer> cust = new ArrayList<Customer>();
        Scanner scan = new Scanner(System.in);
        int ans=0;
        while (true)
        {
            menu();
            System.out.println("CHOICE:");
            ans = scan.nextInt(); 
            if (ans==1)
            {
            	al = loadData();
            	
            }
               
            if (ans==2)
            {
            	printData(al);
               
            }
            if (ans==3)
            {
            	// you fill this in
                
                System.out.println(linearSearch(cust,"Perez"));
            	
            }
            
            if (ans == 4)
            {
            	// you fill this in           	
            }
            
            if (ans == 5)
            {
            	// you fill this in
            }
            
            if (ans==6)
            {
            	// you fill this in
            }
            if (ans==7)
            {
            	// you fill this in
            }
            if (ans==8) {
                //you fill this in
            }
                        
            
            if (ans==9)
            {
            	System.out.println("See you later!");
            	System.exit(0);
            }
                 
        }
	}

	
	
	public static void menu()
    {
        System.out.println("\n1.  Prime the data");
        System.out.println("2.  print out the data");
        System.out.println("3.  Do a linear search for customer last name");
        System.out.println("4.  Do a recursion based binary search for balance");
        System.out.println("5.  Merge sort by account number");
        System.out.println("6.  Quick sort by customer number");
        System.out.println("7.  Selection sort by customer name");
        System.out.println("8.  Randomly shuffle the data in the list");
        System.out.println("9.  exit\n"); 
    }

    

    public static ArrayList<Account> loadData() {
        ArrayList<Account> acct = new ArrayList<Account>();
        acct.add(new Account(5000, new Customer("Smith", "Mike")));
        Customer ct = new Customer("Jones", "Hank");
        acct.add(new Account(45000, ct));
        Customer ct2 = new Customer("Overstreet", "Sam");
        acct.add(new Account(45000, ct2));
        acct.add(new Account(48000, ct));
        acct.add(new Account(23000, ct2));
        acct.add(new Account(1200, ct));
        acct.add(new Account(5000, new Customer("Blow", "Joe")));
        acct.add(new Account(800, new Customer("Miller", "Mike")));
        acct.add(new Account(1250, new Customer("Gordon", "Alex")));
        acct.add(new Account(8000, new Customer("Perez", "Sally")));
        acct.add(new Account(6540, new Customer("Hosmer", "Eric")));
        acct.add(new Account(1250, new Customer("Wade", "Dave")));
        
        return acct;
        
    }
    
    public static void printData(ArrayList<Account> al) {
        for (int i=0;i<al.size(); i++){
            System.out.println(al.get(i).toString());
        }
    }

    private static int linearSearch(ArrayList<Customer> c, String toFind) {
        int i = 0;
		for (Customer val : c) {
			if (val.getLast().equalsIgnoreCase(toFind)) {
				return i;
			}
			i++;
		}
		return -1;
    }
 


}

how to fetch required content only using strip_tags function in php

$
0
0
I'am using strip_tags function to fetch only required content but it fetches the whole data from a link see the example code below i m using to fetch content from a link:
<?php

$a=fopen("http://example.com/","r");
$contents=stream_get_contents($a);
fclose($a);
$contents1=strtolower($contents);

$start='<div id="content">';

$start_pos=strpos($contents1,$start);
$first_trim=substr($contents1,$start_pos);

$stop='</div>&lt!-- content -->';
$stop_pos=strpos($first_trim,$stop);

$second_trim=substr($first_trim,0,$stop_pos+6);
$second_trim = strip_tags($second_trim, '<div><table><tbody><tr><td><a><h2><h4>');
echo "<div>$second_trim</div>";
?>


here is the html code fetched in $second_trim:

<div><div id="content">
<div id="issuedescription"></div>
    <h2 class="wsite-content-title" style="text-align:center;">download content<br /><font     color="#f30519">table of content</font><br /> <font color="#f80117"> content </font></h2>

    <h2>table of contents</h2>   
<h4 class="tocsectiontitle">editorial</h4>
<h2 class="wsite-content-title" style="text-align:left;">technical note</h2>        
<table class="tocarticle" width="100%">
<tr valign="top">           
<td class="toctitle" width="95%" align="left"><a     href="http://example.com/">where are we at and where are we heading to?</a>            </td>
    <td class="tocgalleys" width="5%" align="left">
                                <a href="http://example.com/"     class="file">pdf</a>                                          
</td>
</tr>
<tr>
<td class="tocauthors" width="95%" align="left">
                                sergio eduardo de paiva gonã§alves                      </td>
    <td class="tocpages" width="5%" align="left">1-2</td>
</tr>
</table>
<div class="separator"></div>
h4 class="tocsectiontitle">some text here</h4>

<table class="tocarticle" width="100%">
<tr valign="top">

    <td class="toctitle" width="95%" align="left"><a     href="http://example.com/">some text here</a></td>
    <td class="tocgalleys" width="5%" align="left">
                                <a href="http://example.com/"     class="file">pdf</a>

            </td>
</tr>
    <tr>
<td class="tocauthors" width="95%" align="left">
                                some text here,                         some text here,                         some text here,                         some text here,                         some text here,                         some text here                      </td>
    <td class="tocpages" width="5%" align="left">3-10</td>
</tr>
</table>
    <a target="_blank" rel="license" href="http://example.com/">    
    </a>
    some text here<a rel="license" target="_blank" href="http://example.com/">example</a>.
    </div></div>


Now my problem is i want to fetch a particular tag only, from the whole content like 2nd anchor from two of given below using strip_tag function
<a href="http://example.com/" class="file">pdf</a>
<a href="http://example.com/">some text here</a>


and 2nd header tag from two of given below:

<h2 class="wsite-content-title" style="text-align:center;">download content<br /><font color="#f30519">table of content</font><br /> <font color="#f80117"> content </font></h2>

<h2>table of contents</h2>



but strip tag function is either fetching all of them or none of them , So how can i make them identify to fetch the tag I want instead of fetching all the similar tags.Is their any better way to do this please share your ideas here !!

Changing JLIst that is already displayed

$
0
0
I have a empty JList in which I hit a button LOAD DATA which should load all the data. but once I load data i try to fill in the List but i keep getting errors.

		String[] aos = new String[itrList.size()];
		itrList.toArray(aos);
//		JList listFAIL = new JList(aos);
		
//		list = new JList(itrList.toArray());
//		list.removeAll();
		list.setListData(aos);
		JScrollPane s = new JScrollPane(list);



i have tried doing setListData and i get a error;

And if i do new Jlist it doesn't change the data.

The List does fill as i have a checker for that.

Flowchart control

$
0
0
Hi Everyone. Im doing a project where can user create a flowchart by draging shapes.currently i can now add shapes(rectangles and circles) and able to draw a line.now, my problem is on how to save the chart created. surely i can save location of every position of each controls created but is there another an simplest way to do it?..im not required to make my own flowchart control so any suggestions on any freeware that i can use along with my project will be appreciated.. i dont ask for codes but a pseudo code will also be a great help hehe ..thank you.. sorry for my english ..

HELP on Play Framework connecting to Eclipse

$
0
0
I only have a few knowledge about programming and
i'm trying to help my brother finish his activity

Question 1:
Upon importing the Play Framework content in Eclipse
there's a default codes as localhost:9000 is immediately routed to
play framework website

controllers, checked and running fine
test, checked and running fine
conf, checked and running fine

the problem is the views under app

on all youtube tutorials and other websites, the contents of views
is editable but when my brother tried to, he cant edit it

screenshots on views are located in attachments
as you see, the text editor cant be re-written and we're currently stuck on this problem

----------------------------------------------------------------------------------------------------------

Question 2:
Is there an easy tutorial on POST, PUT, GET, and DELETE for eclipse-playframework

Question 3:
my brother is using POSTMAN - RESTCLIENT to test his HTTP METHODS (post, put, get, and delete)
and is there a tutorial where they also test the HTTP METHODS using POSTMAN?

Please help :) i'd be a really active member as I too have took interest in web programming
and will help in anyway i can

thanks in advance

Plotting data from while loop

$
0
0
Hey :-)
I´m all new to Python, but I see a lot of opportunities in it. So I decided to use it in the first project at my university.
I made an while loop for an iteration of an difference equation (The Cobweb model).

And now I want to make one plot showing all the point calculated in the while loop, with C as x values and F as y values. But if I try to make a plot inside the loop, I get a new plot for every iteration which also makes sense. But I can make the plot after the iteration either since it will only show a plot with one point.

Any ideas how to make the plot work. Any help will be greatly appreciated :-) Here is my script so far
import numpy as np
import matplotlib.pyplot as plt
import random

print 'Cobweb model simulation'
gamma = 0.8
beta = 1
C = 1 # Initial value in the difference equation
while 0 < C:
    u = random.uniform(-1,-2)
    F = -1*(gamma/beta)*C - u/beta 
    print C, F, u 
    C = F 
print 'Jubiiii' 
plt.plot(C, F, 'r-')
plt.show()



Thanks :-)

looping over a list

$
0
0
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

Note: this is only sample list. The list is user defined.

Suppose I've to split the list using user defined number, say N for the given list.

Say N = 4; So,

for N = 4 [1,2,3,4]
for N-1 = 3 [5,6,7]
for N -2 = 2 [8,9]
for N-3 = 1 [10]

Say N = 5; So,

for N = 5 [1,2,3,4,5]
for N-1 = 4 [6,7,8,9]
for N-2 = 3 [10,11,12]
for N-3 = 2 [13,14]
for N -4 = 1 [15]

How to create the loop to get this output? Please can anyone provide me some idea.

Fraction calculator help?

$
0
0
Im supposed to make a code which can handle fractions as a calculator in the form of 1_1/2 + 1 = 2_1/2
This is what ive done so far and now im just lost. Im not sure what im doing tbh and if im even in the right direction? can you tell me what methods would be easiest (but obviously not give me the code lol) and explain how? Im sorry i thought i understood what i was doing but now im just lost.

Heres my code:

import java.util.Scanner;
import java.util.StringTokenizer;
	
public class FracCalc {
	
    public static void main(String[] args ){
    	// read in the first expression
        Scanner scanner = new Scanner(System.in);
        String expression = readLine(scanner);

        // loop until user enters 'quit'
        while (!expression.equals("quit"))
        {
            System.out.println(produceAnswer(expression));
            expression = readLine(scanner);
        }

        System.out.println("Goodbye!");
        scanner.close();
    	


        }
    public static String produceAnswer(String input)
    {
        String firstOperand = getFirstOperand(input);
        String secondOperand = getSecondOperand(input);
        String operator = getOperator(input);
        
        return "First operand = " + firstOperand + "; second operand = " + secondOperand + "; operator = " + operator;
    }

    private static String getFirstOperand(String input)
    {
        // The first operand is the substring before the first space 
        return input.substring(0, input.indexOf(" "));
    }

    private static String getSecondOperand(String input)
    {
        // The second operand is the substring after the second (i.e., last) space 
        return input.substring(input.lastIndexOf(" ") + 1);
    }

    private static String getOperator(String input)
    {
        // The operator is the character after the first space
        return input.substring(input.indexOf(" ") + 1, input.indexOf(" ") + 2);
    }

    private static String readLine(Scanner scanner)
    {
        System.out.println("Enter an expression: ");
        return scanner.nextLine().trim().toLowerCase();
    }


    	// TODO: Implement this function to produce the solution to the input
        System.out.println( "The Answer is: " );
        System.out.println( fraction1 + operator + fraction2 + " = " + result );
    }

    // TODO: Fill in the space below with any helper methods that you think you will need
    
  
    private FracCalc produceAnswer(FracCalc fraction2) {
    	String input;
		String firstOperand = getFirstOperand(input);
    	String secondOperand = getSecondOperand(input);
    	String operator = getOperator(input);
    	
    	int int1 = getLeadingInterger(firstOperand);
    	int int2 = getLeadingInterger(secondOperand);
    	
    	int num1 = getNumerator(firstOperand);
    	int num2 = getNumerator(secondOperand);
    	
    	int denom1 = getDenominator(firstOperand);
    	int denom2 = getDenominator(secondOperand);
    	
    	//convert leading intergers to improper fractions
    	num1 = convertToImproperFraction(int1, num1, denom1);
    	num2 = convertToImproperFraction(int2, num2, denom2);
    	
    	return calculate(num1, denom1, num2, denom2, operator);
    }
    private static String getLeadingInterger(String Input){
    }
    	
    	public static void parse(String fraction)
    	{
    		if (fraction.contains("_")) {
    			StringTokenizer mixed = new StringTokenizer(fraction, "_");
    			int wholeNumber = Integer.parseInt(mixed.nextToken());
    			System.out.println(wholeNumber);
    			String frac = mixed.nextToken();
    			System.out.println(frac);
    			StringTokenizer parseFraction = new StringTokenizer(frac, "/");
    			
    			int num = Integer.parseInt(parseFraction.nextToken());
    			System.out.println(num);
    			int denom = Integer.parseInt(parseFraction.nextToken());
    			System.out.println(denom);
    			
	}
    		else if (!fraction.contains("_") && fraction.contains("/")) {
    			StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); 
                                                                   
    			int num = Integer.parseInt(parseFraction.nextToken());
    			System.out.println(num1);
    			int denom = Integer.parseInt(parseFraction.nextToken());
    			int denom;
				System.out.println(denom);
    }
    		else {
    			StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
    	int num = Integer.parseInt(whiteSpace.nextToken());
    	System.out.println(num);
}
  }
    }

Creating a generator using VB6 and Macro Excel

$
0
0
Hi everybody!

I am new to VB6. Currently, I'm creating a report generator in PDF using Macro Excel. The format is created as well as the database all in Excel. The report is obtained from a raw data, sorted and placed according to the format made and published in PDF format. Now, I have to change into creating it using VB6.

My idea is, I just want to develop one click button which could run my report generator in Macro Excel "underground" which doesn't need to be popped out. As I said, I'm not used to VB6 before. Are there any possibilities that I can make it so? If yes, could you guys help and guide me?

Thank you for your time.

Using the c++ list library to aid in linked-list program

$
0
0
Hey guys. I'm working on a program that is supposed to use linked lists to create a hypercard stack (the specifications are attached). I'm extremely new to C++ and have never worked with linked lists before. I've done some reading about working with them, but it's way over my head.

Here is the file that we are supposed to use:

i 27 Mary had a little lamb
i 15 Today is a good day
i 35 Now is the time!
i 9 This lab is easy and fun
p
d 35
t
i 37 Better Now.
f
p
h
p
d 27
d 15
d 37
d 9
i 44 This should be it!
t
p



And here is what code I've been able to come up with.
My .h file:

//program6.h
#include <iostream>
#include <fstream>
#include <list>
using namespace std;

class Node {
public:
	Node();
	Node(char code, int num, string data);
	Node(Node & node);
	~Node();
	
	bool readFile();
	void setNext(Node* next);
	void print();
	
private:
	char Code;
	int Num;
	string Data;
	Node *Next;
};



My implementation file:

//program6.cpp
#include "program6.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;

class Node {
public:
	Node();
	Node(char code, int num, string data);
	Node(Node & node);
	~Node();
	
	bool readFile();
	void setNext(Node* next);
	void print();
	
private:
	char Code;
	int Num;
	string Data;
	Node *Next;
};

Node::Node() {
	Code = '\0';
	Num = 0;
	Data = "";
	Next = NULL;
}

Node::Node(char code, int num, string data) {
	char Code = code;
	int Num = num;
	string Data = data;
	Next = NULL;
}

Node::Node(Node & node) {
	Code = node.Code;
	Num = node.Num;
	Data = node.Data;
	Next = NULL;
}

Node::~Node() {
}

bool Node::readFile() {
	char code = '\0';
	int num = 0;
	string data = "";
	
	ifstream inputFile;
	inputFile.open("prog6.dat");
	
	if(!inputFile) {
		cerr << "Open Faiulre" << endl;
		exit(1);
		return false;
	}
	
	Node *head = NULL;
	while(!inputFile.eof()) {
		inputFile >> code >> num >> data;
		
		Node *temp = new Node(code, num, data);
		temp->setNext(head);
		head = temp;
	}
	
	inputFile.close();
	head->print();
	return true;
}

void Node::setNext(Node* next) {
	Next = next;
}

void Node::print() {
	cout << Code << " " << Num << " " << Data;
	if(Next != NULL) 
		Next->print();
}



And my main/test file:

//program6test.cpp
#include "program6.h"
#include <iostream>
#include <fstream>
#include <list>
using namespace std;

int main() {
	Node list;
	if(list.readFile()) 
		cout << "Success" << endl;
	else
		cout << "Failure" << endl;
		
	return 0;
}



I've asked this question in a few different places but seem to keep getting the same responses such as, "you need to separate reading the file and doing the list", but I don't actually know how to do that. I'm extremely new to programming and am not good at it at all which is why I've changed majors and am just trying to pass this class.

I've been told there's a list function (not sure on the right wording) in the c++ standard library that would make this easier, but I've never worked with the standard libraries so have no idea how to make this work. Please take a look at the document I've attached which includes the "directions" for this program (if you can call them that) and let me know if you can help me out.

RSA encryption and decryption question

$
0
0
This piece of code is for a class im taking in college. I am currently stuck on the calculations being performed. The output is not what I am expecting. This program is suppose to take in a message to be encrypted(it will be the first variable(66) in the encrypt method call. But the decrypt method doesn't output 66 which it should. Also just FYI I am limited to using these methods and not aloud to import any tools. If anyone can help me understand where I went wrong I would greatly appreciate it. Im not looking for an answer just a bit of guidance. Thanks in advance.

def gcd(a, b ):
    x = a
    y = b
    
    while(y != 0):
        r = x % y
        x = y
        y = r
    return x

def modInv(a, b ):
    mod = b
    x,y, u,v = 0,1, 1,0

    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n

    modInverse = x + mod
    return modInverse

def generateRSAKeys(p, q):
    n = p * q
    r = (p - 1) * (q - 1)
    e = 3
    
    while(gcd(r, e) != 1):
        e += 2
    
    d = modInv(e, r)
    return n, e, d

def encrypt(m, e, n):
    return pow(m, e, n)    

def decrypt(cipher, d, n):
    return pow(cipher, d, n)
    
p = 5
q = 3

print("Keys format: n, e, d")
print(generateRSAKeys(p, q))
print(encrypt(66, 3, 15))
print(decrypt(6, 11, 15))

Help with Functions

$
0
0
Hello. Any help as in leads or advice would be appreciated. This is homework.
My assignment is a c program to help a prospective borrower calculate the monthly payment for a loan. The program also prints the amortization (payoff) table to show the balance of the loan after monthly payment.

Prompt user for input;

1)Amount of the loan:
2)Interest rate per year:
3)Number of years:

Formula;

number_months=(number_years *12)
interest_month =(interest_year/12)
power=(1+interest_month)number_months
power_adjusted =(power/(power-1))
payment_monthly=(principal*interest_month*power_adjusted)

where
number_years= Scheduled number of years to amortize the loan
number_months=Scheduled number of months for the loan
interest_year=Interest rate per year(as a percentage)
interest_month=Interest rate/month (decimal)
principal=Principal (the amount of the loan)
power= The value of (1+interest_month)number_months
power_adjusted= The value of power/(power-1)
monthly_payment= Monthly payment

main must call min three functions: getData, monthly payment (basically my calc), and print_amortization_table.

Professor wants rate per month calc as rate in annual percentage / 1200.
. The monthly payment, while being the same throughout the payment period,
consists of two parts: principal payment, and interest payment.
. The interest payment for each month is calculated as interest for one month on
the current balance.
. The principal paid is the monthly payment minus the interest paid.
. The new balance is current balance minus the principal paid. This balance is always the principal balance that is yet to be paid.
/*
    Creates an information summary and amortization table to help
    a prospective borrower calculate the monthly payment on a loan
    by prompting user and calculating values input at keyboard.
    Written by:
    Date:       11/03/14
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

// Function Declarations
void getData(double* principal, double* interest_year, int* number_years); //take in address parameters so values entered from keyboard picked up
void monthly_payment (double principal, double interest_year,int number_years,
                      double* number_months, double* interest_month, double* power,
                      double* power_adjusted, double* payment_monthly, double* previous_balance,
                      int* month, double* interest_paid, double* tot_paid, double* new_balance),;
                      double* new_balance, double* interest_month);
void print_amortization_table (double principal, double interest_year, double interest_month,
                               int number_years, int month, int payment_monthly, double power,
                               double previous_balance, double interest_paid, double principal_paid,
                               double new_balance, double tot_payment, double number_months)

int main (void)
{
// Local Declarations
    int number_years; //User-input integer
    int number_months; //User-input integer
    double interest_year; // User-input yearly input rate (percentage).
    double interest_month; //Calculated as interest for one month on the current balance.
    double interest_paid; //
    double principal; // User-input amount of loan.
    double principal_paid; // Monthly payment minus the principal paid.
    double previous_balance; //
    double new_balance; // Current balance minus the principal paid.
    double power; // Power function.
    double power_adjusted; // Power
    double tot_payment;
    double payment_monthly;
    int month;

// Read the input data from the user.
    getData (&principal, &interest_year, &number_years);

// Calculate the results.
    monthly_payment (principal, interest_year, number_years, previous_balance, power, power adjusted, tot_payment
                     &new_balance, &interest_month, &interest_paid, &payment_monthly);

//Print the table of the input values and the results.
    print_amortization_table (month, previous_balance, monthly_payment, interest_paid,
                              principal, new_balance, principal_paid, interest_year
                              interest_month, number_years, number_months, tot_payment);

    return 0;

} //main

/*
================================getData====================================
  Prompts the user for one integer and two floats and reads
  the values into memory locations pointed to by the  parameters.
  Checks the values entered and if any are invalid prints an error
  message describing valid range and exits program.
*/
void getData(double* principal, double* interest_year, int* number_years)
{
// Statements
    printf("Amount of the loan (Principal)? ");
    scanf("%lf", principal); // read a single integer value input
    printf ("Interest rate per year (percent)?");
    scanf ("%lf", interest_year)
    printf ("Number of years?");
    scanf ("%d", number_years);

// Input check
    if ((*principal <.01) || (*interest_year < .001) || (*number_years < 1))
    {
        printf ("\n");
        if(*principal <.01)printf ("Starting amount must be at least one cent.\n");
        if(*interest_year < .001)printf ("Interest rate must be at least .1%%.\n");
        if(*number_years < 1000 || (*number_years >9999))printf ("Year must be four digits\n");
        printf ("Exiting\n");
        system ("pause");
        exit (100);
    }

    return;

}// getData


/*================================monthly_payment====================================
  Perform calculations to calculate the monthly payment for a loan and stores results.
*/
void monthly_payment (double principal, double interest_year,int number_years,
                      double* number_months, double* interest_month, double* power,
                      double* power_adjusted, double* payment_monthly, double* previous_balance,
                      int* month, double* interest_paid, double* tot_paid, double* new_balance,)
{
    number_months = (number_years * 12);
    interest_month = (interest_year /12) /100;
    power = pow((1 + interest_month), number_months);
    power_adjusted = power/(power-1);
    payment_monthly = (principal * interest_monthly * power_adjusted);

    previous_balance = principal;

    for (month =1;month<=number_months; month++)
    {
        interest_paid = previous_balance * interest_month;
        tot_paid = payment_monthly - interest_paid;
        new_balance = previous_balance - tot_payment;
        previous_balance = new_balance;
    }

    return;

}// monthly_payment

/*================================print_amortization_table====================================
  Prints a table showing the input values and results.
*/

void print_amortization_table (double principal, double interest_year, double interest_month,
                               int number_years, int month, int payment_monthly, double power,
                               double previous_balance, double interest_paid, double principal_paid,
                               double new_balance, double tot_payment, double number_months)
{
    printf("\nThe amount of the loan (principal):\t%10.2lf\n",principal);
    printf("Interest rate/year (percent):\t\t%10.2lf\n",interest_year);
    printf("Interest rate/month (decimal):\t\t%14f\n",interest_month);
    printf("Number of years:\t\t\t%7d\n",number_years);
    printf("Number of months:\t\t\t%7d\n",number_months);
    printf("Monthly payment:\t\t\t%10.2lf\n\n",payment_monthly);

    printf("Month    Old     Monthly     Interest    Principal   New\n");
    printf("    Balance     Payment     Paid    Paid Balance\n\n");



    return;
}//print_amortization_table

Console SQL Query app not working correctly

$
0
0
Hi Guys, my console SQL Query app is not giving me the desired output.I am sure its might have something to do with my SQL Query.Its missing the description of the stock items and it prints a new line for each user as per number of stocks an repeats the user details and then prints the stock listed by that user(only want the user listed once with all its stocks). I will add my files and current output and desired out put below.

Thanks in advanced for all and any assistance!

MakeDB.java:

import java.sql.*;
import java.io.*;

public class MakeDB
{
	public static void main(String[]args) throws Exception
	{
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		String url="jdbc:odbc:StockTracker";

		Connection con = DriverManager.getConnection(url);
		Statement stmt = con.createStatement();
		//if index exsists  will be deleted
		//if not exdsists ddisplay mesage continue execution!
			System.out.println("Dropping indexes & Tables");
		try{
					stmt.executeUpdate("DROP INDEX PK_UserStocks on UserStocks");
			}
			catch(Exception e)
			{
				System.out.println("Could not drop primary key on UserStocks table:" + e.getMessage());
			}
			try
			{
				stmt.executeUpdate("DROP TABLE UserStocks");
			}
			catch(Exception e)
			{
				System.out.println("Could not drop UserStocks table: " + e.getMessage());
			}
			try
			{
				stmt.executeUpdate("DROP TABLE Users");
			}
				catch(Exception e)
			{
				System.out.println("Could not drop Users table: " + e.getMessage());
			}
			try
			{
				stmt.executeUpdate("DROP TABLE Stocks");
			}
			catch(Exception e)
			{
				System.out.println("Could not drop Stocks table: " + e.getMessage());

			}


			//////////Create the data base tables//////////
			System.out.println("\nCreating tables...............");

			///Create Stock table with primary key index
			try
			{
				System.out.println("Creating Stocks table with primary key index...");
				stmt.executeUpdate("CREATE TABLE Stocks ( symbol TEXT(8)NOT NULL CONSTRAINT PK_Stocks PRIMARY KEY, name TEXT(50) )");
			}
			catch(Exception e)
			{
				System.out.println("Exception creating the Stocks Table: " + e.getMessage());
			}
			///create Users table with primary index key
			try
			{
				System.out.println("Creating Users table with primary key index...");
				stmt.executeUpdate("CREATE TABLE Users (userID TEXT(20)NOT NULL CONSTRAINT PK_Users PRIMARY KEY, lastName TEXT(30)NOT NULL,firstName TEXT(30)NOT NULL,pswd LONGBINARY,admin BIT )");
			}
			catch(Exception e)
			{
				System.out.println("Exception  creating the Users Table: " + e.getMessage());
			}
			///create table with foreign keys to users and stocks table
			try
			{
				System.out.println("Creating UserStocks table with primary key index...");
				stmt.executeUpdate("CREATE TABLE UserStocks (userID TEXT(20) CONSTRAINT FK1_UserStocks REFERENCES Users (userID),symbol TEXT(8), CONSTRAINT FK2_UserStocks FOREIGN KEY (symbol) REFERENCES Stocks(symbol))");

			}
			catch(Exception e)
			{
				System.out.println("Exception  creating the UserStocks Table: " + e.getMessage());
			}
			///create userStocks table primary key
			try
			{
				System.out.println("Creating UserStocks table primary key index...");
				stmt.executeUpdate("CREATE UNIQUE INDEX PK_UserStocks ON UserStocks(userID,Symbol) WITH PRIMARY DISALLOW NULL");
			}
			catch(Exception e)
			{
				System.out.println("Exception  creating the UserStocks index: " + e.getMessage());
			}
			// Create 1 administrative user with password as initial data

			String userID= "admin01";
			String firstName="Default";
			String lastName = "Admin";
			String initialPswd="admin01";
			Password pswd = new Password(initialPswd);
			Boolean admin = true;

			PreparedStatement pStmt =
				con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?)");

			try
			{
				pStmt.setString(1, userID);
				pStmt.setString(2, lastName);
				pStmt.setString(3, firstName);
				pStmt.setBytes(4, serializeObj(pswd));
				pStmt.setBoolean(5, admin);
				pStmt.executeUpdate();
			}
			catch(Exception e)
			{
				System.out.println("Exception inserting user test: " +e.getMessage());
			}
			pStmt.close();

			//readand display all user datain the data base.
			ResultSet rs = stmt.executeQuery("SELECT * FROM Users");

			System.out.println("Datebase Created.\n");
			System.out.println("Displaying Data form Database....\n");
			System.out.println("User table Contains : ");

			Password pswdFromDB;
			byte[] buf=null;
			while (rs.next())
			{
				System.out.println("Logon ID = "+ rs.getString("userId"));
				System.out.println("First name = "+ rs.getString("firstName"));
				System.out.println("Last name = "+ rs.getString("lastName"));
				System.out.println("Administrative = "+ rs.getBoolean("admin"));
				System.out.println("Inital password = "+ initialPswd);


			///SQL NULL data value is not handled correctly
			buf = rs.getBytes("pswd");
			if (buf!=null)
			{
				System.out.println("Password Object = " + (pswdFromDB=(Password)deserializeObj(buf)));
				System.out.println ("autoExpires = " + pswdFromDB.getAutoExpires());
				System.out.println("Expireing now = " + pswdFromDB.isExpiring());
				System.out.println("Remaing uses = " + pswdFromDB.getRemainingUses()+ "\n");


			}
			else
				System.out.println("Password Object = NULL!");

			}
			rs = stmt.executeQuery("SELECT * FROM Stocks");
			if(!rs.next())
				System.out.println("Stocks table contains no records.");
			else
				System.out.println("Stocks still contains records!");

			rs = stmt.executeQuery("SELECT * FROM UserStocks");
			if(!rs.next())
				System.out.println("UserStocks table contains no records.");
			else
				System.out.println("UserStocks still contains records!");

			stmt.close();//closeing statement also close ResultSet


	}//end of main

	//Method to  write object to byte array and then insert into preoared statment
	public static byte[] serializeObj(Object obj) throws IOException
	{
		ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
		ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

		objOStream.writeObject(obj);//obect must be serializeable
		objOStream.flush();
		objOStream.close();
		return baOStream.toByteArray();//Returns stream as string
	}

	public static Object deserializeObj(byte[]buf)throws IOException, ClassNotFoundException
	{
		Object obj = null;
		if (buf!=null)
		{
			ObjectInputStream objIStream= new ObjectInputStream(new ByteArrayInputStream(buf));

			obj = objIStream.readObject();//throws IOException, ClassNotFoundException
		}
		return obj;
	}
}//end of class





QueryDatabase.java:

import java.sql.*;
import java.io.*;

public class MakeDB
{
	public static void main(String[]args) throws Exception
	{
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		String url="jdbc:odbc:StockTracker";

		Connection con = DriverManager.getConnection(url);
		Statement stmt = con.createStatement();
		//if index exsists  will be deleted
		//if not exdsists ddisplay mesage continue execution!
			System.out.println("Dropping indexes & Tables");
		try{
					stmt.executeUpdate("DROP INDEX PK_UserStocks on UserStocks");
			}
			catch(Exception e)
			{
				System.out.println("Could not drop primary key on UserStocks table:" + e.getMessage());
			}
			try
			{
				stmt.executeUpdate("DROP TABLE UserStocks");
			}
			catch(Exception e)
			{
				System.out.println("Could not drop UserStocks table: " + e.getMessage());
			}
			try
			{
				stmt.executeUpdate("DROP TABLE Users");
			}
				catch(Exception e)
			{
				System.out.println("Could not drop Users table: " + e.getMessage());
			}
			try
			{
				stmt.executeUpdate("DROP TABLE Stocks");
			}
			catch(Exception e)
			{
				System.out.println("Could not drop Stocks table: " + e.getMessage());

			}


			//////////Create the data base tables//////////
			System.out.println("\nCreating tables...............");

			///Create Stock table with primary key index
			try
			{
				System.out.println("Creating Stocks table with primary key index...");
				stmt.executeUpdate("CREATE TABLE Stocks ( symbol TEXT(8)NOT NULL CONSTRAINT PK_Stocks PRIMARY KEY, name TEXT(50) )");
			}
			catch(Exception e)
			{
				System.out.println("Exception creating the Stocks Table: " + e.getMessage());
			}
			///create Users table with primary index key
			try
			{
				System.out.println("Creating Users table with primary key index...");
				stmt.executeUpdate("CREATE TABLE Users (userID TEXT(20)NOT NULL CONSTRAINT PK_Users PRIMARY KEY, lastName TEXT(30)NOT NULL,firstName TEXT(30)NOT NULL,pswd LONGBINARY,admin BIT )");
			}
			catch(Exception e)
			{
				System.out.println("Exception  creating the Users Table: " + e.getMessage());
			}
			///create table with foreign keys to users and stocks table
			try
			{
				System.out.println("Creating UserStocks table with primary key index...");
				stmt.executeUpdate("CREATE TABLE UserStocks (userID TEXT(20) CONSTRAINT FK1_UserStocks REFERENCES Users (userID),symbol TEXT(8), CONSTRAINT FK2_UserStocks FOREIGN KEY (symbol) REFERENCES Stocks(symbol))");

			}
			catch(Exception e)
			{
				System.out.println("Exception  creating the UserStocks Table: " + e.getMessage());
			}
			///create userStocks table primary key
			try
			{
				System.out.println("Creating UserStocks table primary key index...");
				stmt.executeUpdate("CREATE UNIQUE INDEX PK_UserStocks ON UserStocks(userID,Symbol) WITH PRIMARY DISALLOW NULL");
			}
			catch(Exception e)
			{
				System.out.println("Exception  creating the UserStocks index: " + e.getMessage());
			}
			// Create 1 administrative user with password as initial data

			String userID= "admin01";
			String firstName="Default";
			String lastName = "Admin";
			String initialPswd="admin01";
			Password pswd = new Password(initialPswd);
			Boolean admin = true;

			PreparedStatement pStmt =
				con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?)");

			try
			{
				pStmt.setString(1, userID);
				pStmt.setString(2, lastName);
				pStmt.setString(3, firstName);
				pStmt.setBytes(4, serializeObj(pswd));
				pStmt.setBoolean(5, admin);
				pStmt.executeUpdate();
			}
			catch(Exception e)
			{
				System.out.println("Exception inserting user test: " +e.getMessage());
			}
			pStmt.close();

			//readand display all user datain the data base.
			ResultSet rs = stmt.executeQuery("SELECT * FROM Users");

			System.out.println("Datebase Created.\n");
			System.out.println("Displaying Data form Database....\n");
			System.out.println("User table Contains : ");

			Password pswdFromDB;
			byte[] buf=null;
			while (rs.next())
			{
				System.out.println("Logon ID = "+ rs.getString("userId"));
				System.out.println("First name = "+ rs.getString("firstName"));
				System.out.println("Last name = "+ rs.getString("lastName"));
				System.out.println("Administrative = "+ rs.getBoolean("admin"));
				System.out.println("Inital password = "+ initialPswd);


			///SQL NULL data value is not handled correctly
			buf = rs.getBytes("pswd");
			if (buf!=null)
			{
				System.out.println("Password Object = " + (pswdFromDB=(Password)deserializeObj(buf)));
				System.out.println ("autoExpires = " + pswdFromDB.getAutoExpires());
				System.out.println("Expireing now = " + pswdFromDB.isExpiring());
				System.out.println("Remaing uses = " + pswdFromDB.getRemainingUses()+ "\n");


			}
			else
				System.out.println("Password Object = NULL!");

			}
			rs = stmt.executeQuery("SELECT * FROM Stocks");
			if(!rs.next())
				System.out.println("Stocks table contains no records.");
			else
				System.out.println("Stocks still contains records!");

			rs = stmt.executeQuery("SELECT * FROM UserStocks");
			if(!rs.next())
				System.out.println("UserStocks table contains no records.");
			else
				System.out.println("UserStocks still contains records!");

			stmt.close();//closeing statement also close ResultSet


	}//end of main

	//Method to  write object to byte array and then insert into preoared statment
	public static byte[] serializeObj(Object obj) throws IOException
	{
		ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
		ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

		objOStream.writeObject(obj);//obect must be serializeable
		objOStream.flush();
		objOStream.close();
		return baOStream.toByteArray();//Returns stream as string
	}

	public static Object deserializeObj(byte[]buf)throws IOException, ClassNotFoundException
	{
		Object obj = null;
		if (buf!=null)
		{
			ObjectInputStream objIStream= new ObjectInputStream(new ByteArrayInputStream(buf));

			obj = objIStream.readObject();//throws IOException, ClassNotFoundException
		}
		return obj;
	}
}//end of class





Output:
Stock holdings by User

User ID User Name
Stock - Description
-------------------------------------------
admin01 Default Admin
DELL
admin01 Default Admin
MSFT
admin01 Default Admin
ORCL
user01 Bill Buyout
DELL
user01 Bill Buyout
MSFT
user02 Fran Futures
MSFT
user02 Fran Futures
ORCL

Press any key to continue . . .

I would like the output as follows :

Stock holdings by User

User ID User Name
Stock - Description
-------------------------------------------
admin01 Default Admin
DELL Dell Computer Corporation
MSFT Microsoft Corporation
ORCL Oracle Corporation

user01 Bill Buyout
DELL Dell Computer Corporation
MSFT Microsoft Corporation

user02 Fran Futures
MSFT Microsoft Corporation
ORCL Oracle Corporation

Press any key to continue . . .

Any help would be awesome ..

develop a Guessing Game application

$
0
0
Here is my instangable class

The application should generate a random number between 1 and 10 and then ask the user to enter one single number between 1 and 10 to guess what the secret number is

public class Guess{

	//Variables
	private int Num;
	private int rNo;
	private String message;

	//Constructors
	public Guess(){
		rNo = 0;
		message = "";
		}

	//Set

	public void setRNo(int rNo){
		this.rNo = rNo;
		}

	//Compute
	public void compute(){

	
	if (num = rNo){
	message = ("Congratulations, you guessed correctly!");
	}

	else if (num >=rNo){
	message = ("You guessed too high, sorry!");
	}

	else if (num <=rNo){
	message = ("You guessed too low, sorry!");
	}

	//Get
	public String getMessage(){
		return message;
		}











}
}




Two errors are

Guess.java:43: error: illegal start of expression
public String getMessage(){


uess.java:43: error: ';' expected
public String getMessage(){

Thanks
Viewing all 51036 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>