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

function should return no values

$
0
0
Could some one help understand how can I make a function return no value::


#include<stdio.h>
int main()
{
int i =12;
printf(" value is %d\n, i++");
printf(" value is %d\n, i++");
printf(" value is %d\n, i++");
return 0;

}

RPG map in pygame?

$
0
0
How do i make a map for an rpg like game in pygame that can allow the screen to move with him where ever he goes.

java.net.BindException: Address already in use... but it's NOT in

$
0
0
I'm trying to get 2 computers in a Local network (home network) to communicate via Sockets in order for one to request an object and the other send the object to the requesting process. I had a bit of a hard time finding how to do this with objects instead of just strings, but I thought I found a solution with
ServerSocketChannel
.

However, I am receiving the following error message when I start the listener:

Quote

java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Unknown Source)
at sun.nio.ch.Net.bind(Unknown Source)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at clock.ClockListener.run(ClockListener.java:35)


I've scoured google and the only answers I've seen so far are ones that involve the port being in use already.

The problem is that I've looked at TCPView and netstat and both are reporting that the port number I am using is NOT in use. The port is FREE. I've also made sure that the Windows Firewall is allowing Java through and it is. What could be causing this? Please see my listener and client code below:

Listener
import java.awt.Toolkit;
import java.io.*;
import java.net.*;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Calendar;

public class ClockListener extends Thread{

	private ServerSocket welcomeSocket;
	private ServerSocketChannel ssChannel;
	private BufferedReader readerIn;
	private ObjectOutputStream outStream;
	private AllEmployees employeeList;
	private String inputString;
	private static final int portNumber = 9595;
	
	public ClockListener(AllEmployees eL){
		try {
			welcomeSocket = new ServerSocket(portNumber);
			welcomeSocket.setReuseAddress(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		employeeList = eL;
	}
	
	@Override
	public void run() {
		try{
		ssChannel = ServerSocketChannel.open();
		ssChannel.configureBlocking(true);
		ssChannel.socket().bind(new InetSocketAddress(portNumber));
		}catch(IOException e){
			e.printStackTrace();
		}
		
		while(true){
			try {
				Socket serverSocket;
				SocketChannel sChannel = ssChannel.accept();
				
				ObjectOutputStream oos = new ObjectOutputStream(sChannel.socket().getOutputStream());
				oos.writeObject(employeeList);
				oos.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	
}



Client Code:
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;

public class ClockConnection extends Thread{

	private AllEmployees employeeList;
	private Socket clientSocket;
	private InetSocketAddress iNetAddress;
	private static final int portNumber = 9595;
	
	public void run(){
		try {
			iNetAddress = new InetSocketAddress("192.168.1.195", portNumber);
			clientSocket = new Socket("192.168.1.195", portNumber);
			DataOutputStream sendToServer = new DataOutputStream(clientSocket.getOutputStream());
			String request = "GetEmployees";
			sendToServer.writeBytes(request);
			
			SocketChannel sChannel = SocketChannel.open();
			sChannel.configureBlocking(true);
			
			if (sChannel.connect(iNetAddress)){
				ObjectInputStream inStream = new ObjectInputStream(sChannel.socket().getInputStream());
				try {
					employeeList = (AllEmployees)inStream.readObject();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public AllEmployees getEmployeeList(){
		return employeeList;
	}
	
}



Additionally, this isn't a network issue as I am able to have the 2 computers communicate across the network when passing Strings (without using ServerSocketChannel).

Why is the bind failing? Is there a better way to do this without ServerSocketChannel and binding? Is there a way to pass objects through sockets like strings?

Question about Java packages

$
0
0
Hi there dreamincode.net members, this is my very first question so please bear with me as I am not fully accustomed to the rules and regulations applicable to this forum as of now. I have several questions and they are...

1)What is a Java package? What is it used for?
2)How do you properly declare a package?
3)After declaration, how do you define a package?
4)How is a package used and what does CLASSPATH have to do with it?
5)Simple examples if possible?

Fee Calculator

$
0
0
This is not a homework assignment anymore, just one that I am doing so that I can try to learn how to do this.
I would like create an application for an animal-fur trimming service. The business is open 15 weeks of the year, from April through July. The fee for a small animal (under 6 pounds) is $100, a medium animal (under 100 pounds) is $200, and a large animal (101 pounds and above) is $300.
What I would like to do is create a program using the Scanner class that will eventually allow me to come up with a total fee for each year, but I am stuck on the language that would calculate the fee.
import java.util.Scanner;
public class AnimalTrim
{
	public static void main(String[] args)
	{
		double animalFeeTotal;
		int animalWeight;
		int numberOfTrims;
		int year;
		final double SMALL_ANIMAL_FEE = 100;
		final double MED_ANIMAL_FEE = 200;
		final double LRG_ANIMAL_FEE = 300;
		Scanner keyboard = new Scanner(System.in);
		System.out.print("Enter the weight of the animal");
		animalWeight = keyboard.nextInt();
		if(animalWeight < 6)
			fee = SMALL_ANIMAL_FEE;
		else
			if(animalWeight > 6 && animalWeight < 101);
				fee = MED_ANIMAL_FEE;
			else
				if(animalWeight > 101)
					fee = LRG_ANIMAL_FEE;
		
	}
}
		



What I would like for my code to do is use the weight input to decide the fee, then calculate the total based on the number of animals input, while adding the fee altogether. But I am fairly new and cannot find the resources or a similar problem that can help me figure out how to write the code correctly. I have been working on this for weeks and tried looking so many places, which is why I am now asking for guidance.

Stress and Strain Program

$
0
0
Greetings everyone,

I'm new to the C Language and currently taking a course for it. I've hit an area that I can't seem to figure out though...

Below is my code so far. I don't think the numbers are right for the calculations, but I am able to get the stress and strain to print, but it's only for one calculation. I think my problem lies in the FOR loop since it isn't looping, or appears that way to me.

What I am trying to figure out how to do is get the code to print a list of loads with their associated stress and strain.

If anyone can give me some guidance it will be greatly appreciated.

Thanks.

 
#include <stdio.h>
#include <math.h>
float compute_stress();
float compute_strain(float stress);
void output_results(float stress, float strain);

int main( )
{
	float stress;
	float strain;
	stress = compute_stress();
	strain = compute_strain(stress);
	output_results(stress,strain);
	
	system("PAUSE");
	
	return(0);
}

float compute_stress()
{
	const float pi = 3.141593f;
	float stress;
	float diameter;
	float length;
	float area;
	long int p;
	stress=0;

	printf("\nEnter the diameter of the steel rod in inches: ");
	scanf("%f", &diameter);

	printf("\nEnter the length of the steel rod in inches: ");
	scanf("%f", &length);

	for(p = 10000; p <= 1000000; p += p+100000)
		{
			area = (pi * diameter *diameter) / 4;
			stress = p / area;
		}

	return stress;
}

float compute_strain(float stress)
{
	const float E=30000000;

	float strain;

	strain = stress / E;

	return strain;
}
void output_results (float stress, float strain)
{
printf("\nStress = %f \nStrain = %f\n", stress, strain);
}

Problem With Array

$
0
0
My compile time errors are this: "not a statement", and "';' missing", both in reference to line 9 a countless number of times.

Here's my class:

package Hangman;

public class Words
{
    public String word(int x)
    {
        int wordNumber = x;
        
        String words[] = {"aardvark", "abuse", "accept", "acid", "actor", "adobe", "advise", "agate", "air", "almond", "altar", "amongst", "angle", "apathy", "apple", "arch", "arsenic", "attack", "azure", "ballast", "baron", "bayonet", "beaver", "bellow", "beret", "bisect", "blight", "blister", "blunder", "bologna", "borrow", "brawn", "brisk", "buffalo", "bully", "butter", "canal", "candle", "canteen", "capital", "caribou", "cassette", "cayenne", "chaplain", "chastise", "chime", "chimney", "chivalry", "choler", "chronology", "civic", "clock", "clutch", "cohesion", "column", "combat", "commune", "compose", "conserve", "conscience", "cosmos", "crafty", "crayon", "crown", "cuff", "cyclops", "dandy", "daunt", "debt", "define", "depot", "dewy", "dilate", "discern", "dispatch", "docile", "dock", "dominion", "down", "dress", "drift", "drum", "duly", "dye", "earth", "economic", "eggnog", "ellipse", "elven", "embitter", "emu", "enrich", "escape", "ether", "eve", "evil", "ewe", "expense", "eye", "facet", "fawn", "fax", "fez", "finale", "fire", "fix", "flout", "forge", "frolic", "front", "futile", "fuzz", "gala", "gamble", "gangrene", "gargoyle", "gaze", "geode", "gizzard", "glow", "gnome", "gnu", "govern", "grasp", "grew", "gruel", "gypsy", "gym", "hanker", "hasty", "helm", "hexagon", "hygiene", "hysteria", "ibis", "immense", "imperial", "improvise", "independence", "infer", "inflict", "ink", "instep", "interfere", "intersect", "invariable", "iodize", "iritation", "isthmus", "jib", "jig", "judge", "junk", "kale", "kernel", "kimono", "knight", "koala", "kumquat", "lanyard", "larceny", "lapse", "latent", "latter", "lavish", "lazy", "lenient", "lieutenant", "lime", "line", "llama", "lozenge", "lyric", "macaque", "macron", "majestic", "magnet", "manganese", "mantle", "manipulate", "margin", "mayor", "maximum", "meddle", "midget", "military", "mingle", "misread", "mistook", "mobilize", "mountain", "murky", "myriad", "natural", "nebula", "neither", "niche", "night", "north", "noteworthy", "nutriment", "obnoxious", "obvious", "ocular", "offense", "oddity", "often", "omelette", "oodles", "oppose", "ornate", "oxbow", "ozone", "paddle", "page", "pajamas", "palace", "papyrus", "parachute", "parkway", "partake", "patron", "patter", "pavilion", "peculiar", "penicillin", "perchance", "periscope", "persimmon", "persist", "pheasant", "phlegm", "piccolo", "pigeon", "pioneer", "plaque", "pliable", "poison", "poodle", "porpoise", "powder", "precedent", "premium", "previous", "privacy", "product", "proper", "prophet", "pronounce", "public", "punctual", "pupil", "pushy", "puzzle" "pyramid", "python", "quack", "quail", "quarter", "query", "quick", "quiver", "quiz", "rabid", "radiate", "rake", "rancid", "rascle" "rattle", "reality", "receive", "recycle", "refer", "refuel" "reign", "relent", "remorse", "repent", "resist", "respect", "retrieve", "rhythm", "rifle", "roar", "rooster", "rough", "ruffian", "runway", "ruthless", "safety", "sailors", "sanguine", "sampler", "sapwood", "savage", "scalp", "schedule", "score", "scorn", "sculpture", "scuttle", "sear", "secret", "seek", "sensitive", "serial", "sever", "shave", "shore", "shortage", "shorten", "sick", "sign", "silicon", "siphon", "skill", "skunk", "slave", "sleight", "sling", "slouch", "smite", "snipe", "social", "solitude", "sonorous", "sought", "soy", "spasm", "spectrum", "spider", "spoil", "squall", "squint", "stale", "stalwart", "standard", "steeple", "stencil", "stilt", "sting", "strain", "stretcher", "stump", "sturgeon", "sunbeam", "superhero", "surplus", "sword", "system", "tackle", "tactless", "tailor", "talon", "tangible", "tawny", "tear", "temper", "tender", "tension", "terrier", "theater", "thieve", "thourough", "thrive", "thunder", "tinder", "topple", "totem", "toxic", "traffic", "transit", "trap", "trick", "triple", "trounce", "tuber", "tunic", "twelve", "typing", "umpire", "under", "unequal", "unify", "unlucky", "unrest", "untie", "uproot", "vaccine", "valid", "vary", "vend", "ventricle", "venture", "victim", "viola", "vocal", "vole", "vow", "wagon", "wander", "warp", "watch", "water", "wax", "weld", "wheedle", "whine", "whisk", "whole", "wiggle", "window", "wisp", "witless", "wonder", "wreck", "wrung", "yacht", "yoke", "yonder", "yule", "zealous", "zebra", "zeppelin", "zoom"};
         
         wordNumber = 600;
         String word = words[wordNumber];
         System.out.println(word);
         return word;
    }
}


This class serves as the dictionary to a hangman game I'm making (idea from Martyr2's idea list), with the input as the random number generated by the method that calls on it (so that its more random - with this many words, I need better randomness). I'm completely lost here, as I rarely use arrays. Could anyone provide insight on this?

edit: nevermind. posting it here highlighted my problem: a missing quotation mark.

edit: still getting the errors.

Read website's meta tag?

$
0
0
I'm trying to make it read meta tags from a certain website. Tags are keywords.

This is how it looks (website's source)
<meta name="keywords" content="xxx,yyy, zzz, rrrr etc,...">


This is what I came up so far, but it's not working and I'm a bit clueless.

Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        For Each element As HtmlElement In WebBrowser1.document.All.GetElementsByName("keywords")
            TextBox2.Text = element.GetAttribute("content")
            MsgBox("yeah")
        Next
        MsgBox("nope")
        WebBrowser1.Navigate("127.0.0.1")
    End Sub


Anyone cares to help me out a bit? Thanks!

Difference between the two code below

$
0
0
Hello Every one,

I am a confused betwwen the below 2 code.

Code 1:

while ((sCurrentLine = finput.readLine()) != null) {
System.out.println(sCurrentLine);
}

It display me the file content.

Code 2:

while ((finput.readLine()) != null) {
sCurrentLine=finput.readLine();
System.out.println(sCurrentLine);
}

Return me null value.

Could you please explain me the difference between this code.

How to update db on hosting site

$
0
0
I have a program that is access based which I have exported the information I need to publish on a web sited that is being hosted. My question is what is the best way to update the database my CF app is using updated. My hosting service can do either access or MS SQL 2008. The isn't a lot of updates that will be probable 5 - 10 a minute. I was going to just pull the data via query then do an update query to add the records. Any thoughts would be appreciated. The traffic isn't going to be very high. If I just copy the access file to the hosting service would the users get an error while the file is being over wrote. Been out of the CFworld for a while.

[Link] C++ For Cross-Platform Mobile Development

$
0
0
I came across an article advocating C++ as a cross-platform mobile solution. What are your thoughts? Do you use a different cross-platform mobile solution?

Quote

When it comes to mobile development mind share, Javascript, HTML, Objective-C, and Java reign supreme. But developers seeking a cost-effective approach to multiplatform mobile development may find an ace in the hole in an old friend: C++.

C++ can be leveraged for building native applications for Google Android, Apple iOS, Windows Phone and RT, and RIM BlackBerry 10, says John Thomas, director of product management at Embarcadero Technologies. Developers, he says, are "starting to realize that this approach of having to use the native tools for each of those environments is very expensive, and they're looking for a solution."

But can C++ grow beyond its game development niche? According to Thomas, business apps could also be a strong fit.


http://www.javaworld.com/javaworld/jw-12-2012/121210-c-for-mobile-app-dev.html

Problem creating an instance(Harder than you think)

$
0
0
I understand that creating an instance of a class is very simple which it is, but I do not understand why I am having this error. The IDE keeps saying quote, "No enclosing instance of type ClassAndAbove1 is accessible. Must qualify the allocation with an enclosing instance of type ClassAndAbove1 (e.g. x.new A() where x is an instance of ClassAndAbove1)," where ClassAndAbove1 is the project name. Attached is a file with the code so you can pick apart the error if you so choose. The problem occurs at the bottom of the code,please help!

import java.io.*;
import java.util.*;
class gvars
{
	static float debt1;
	static float income1;
	static float tax1;
	static float payofftime1;
	static float interest1;
}
        public class ClassAndAbove1 {
	    public static void main(String[] args) {
		System.out.println("Amount of debt : ");
		float debt;
		Scanner debtfile = new Scanner(System.in);
		debt = debtfile.nextFloat();
		gvars.debt1 = debt;
		System.out.println("Amount of income : ");
		float income;
		Scanner incomefile = new Scanner(System.in);
		income = incomefile.nextFloat();
		gvars.income1 = income;
		System.out.println("Tax rate paid(In PERCENT form) : ");
		float taxrate;
		Scanner taxfile = new Scanner(System.in);
		taxrate = taxfile.nextFloat();
		float rawtax = taxrate/100;
		gvars.tax1 = rawtax;
		System.out.println("Unit of time for debt to be paid of in\n1: Months\n2: Years\n: ");
		int decision;
		Scanner timefile = new Scanner(System.in);
		decision = timefile.nextInt();
		if(decision == 1)
		{
			System.out.println("Enter number of months for debt to paid off in : ");
			float month;
			Scanner monthfile = new Scanner(System.in);
			month = monthfile.nextFloat();
			float payofftime = month/12;
			gvars.payofftime1 = payofftime;
		}
		else if(decision == 2)
		{
			System.out.println("Enter number of years(YEARS ONLY) for debt to be paid off in : ");
			float years;
			Scanner yearfile = new Scanner(System.in);
			years = yearfile.nextFloat();
			System.out.println("Enter number of months in addition to the years for debt to be paid off in : ");
			float decismonth;
			Scanner monthfile = new Scanner(System.in);
			decismonth = monthfile.nextFloat();
			float rawmonth = decismonth/12;
			float payofftime = years+rawmonth;
			gvars.payofftime1 = payofftime;
			}
		System.out.println("Amount of interest paid(In PERCENT) : ");
		float interest;
		Scanner intfile = new Scanner(System.in);
		interest = intfile.nextFloat();
		float  decint = interest/100;
		gvars.interest1 = decint;
		Financials action = new Financials();
	}
	class Financials
	{
		float debt = gvars.debt1;
		float income = gvars.income1;
		float tax = gvars.tax1;
		float payofftime = gvars.payofftime1;
		float interest = gvars.interest1;
	}
	}

supermarket/grocery code.

$
0
0
can anyone help me to add a input money instead login? and if the money you input insufficient the sub total will not show instead Insufficient Money, something like that. thank you!



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

/**
 * This is the Cashier class
 */
public class Cashier extends JFrame {
		
	/**
	 * This method consist of application launch events 
	 */
	public void launchApp()	{	
		Login login = new Login();
		login.launchFrame();
	}

	/**
	 * This the driver program
	 */
	public static void main(String args[]) {
		Cashier cashier = new Cashier();
		cashier.launchApp();
	}	
}// End of Cashier class

/**
 * This is the Login class
 */
class Login extends JFrame implements KeyListener {

	// Store cashier's name
	public static String cashierName;

	// GUI components
	private JFrame loginFrame;
	private JLabel loginLabel;
	private JTextField loginText;

	/**
	 * This constructor initialize GUI components
	 */
	public Login() {
		loginFrame = new JFrame("Cashier Login");
		loginLabel = new JLabel("Cashier Name :");
		loginText = new JTextField("NewUser", 10);
		loginText.setFont(new Font("",Font.BOLD,12));
	}

	/**
	 * This method consist of frame launch events 
	 */
	public void launchFrame() {	
		loginFrame.setSize(200,350);
			
		loginFrame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
		loginFrame.getContentPane().add(loginLabel);
		loginFrame.getContentPane().add(loginText);
		loginFrame.pack();
	
		// Centering the screen on the desktop
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = loginFrame.getSize();
		loginFrame.setLocation(((screenSize.width - frameSize.width) / 2),
							((screenSize.height - frameSize.height) / 2));		

		loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		loginFrame.setVisible(true);
		
		loginText.selectAll();
		loginText.addKeyListener(this);
	}
	
	// Unused interface methods
	public void keyTyped(KeyEvent e) { }
	public void keyReleased(KeyEvent e) { }
	
	public void keyPressed(KeyEvent e) { 
		
		// Key Enter is pressed
		if (e.getKeyCode() == 10) {
			
			cashierName = loginText.getText();
			loginFrame.setVisible(false);
			
			Menu menu = new Menu();
			menu.launchFrame();
			
		}
	}
}// End of Login class

/**
 * This is the Menu class
 */
class Menu extends JFrame implements KeyListener {

	// GUI components
	private JFrame menuFrame;
	private JPanel menuNorthPanel,
				   menuSouthPanel,
				   menuCenterPanel,
				   menuTitlePanel,
				   menuDetailPanel,
				   menuChoicePanel,
				   menuHeaderPanel;
	
	private JLabel menuStoreLabel,
				   menuTitleLabel,
				   menuCashierLabel,
				   menuHeaderLabel,
				   menuDateLabel,
				   menuChoiceLabel[],
				   menuGuideLabel;
	
	/**
	 * Element listing of all the products NAMES
	 */
	public static String choice[] = {"FIESTA SPAGHETTI ",
								   	"ALASKA CONDENSADA",
					   				"ALASKA CREMA     ",
					   				"PHILIPS PEAS     ",
									"SMB FRENCH FRIES ",
					   				"CHOCOLAIT        ",
					   				"BENCH COLOGNE    ",
					   				"MASTER FACIAL OIL"};	
	
	/**
	 * Element listing of all the products PRICE
	 */
	public static double price[] = {65.00,
					  				38.00,
					  				37.00,
					  				17.00,
					  				90.00,
					  				21.00,
					  				27.00,
					  				31.00};
	
	/**
	 * To keep track of the amount of products ordered
	 */
	public static int ordered[];
				   
	String option[] = {"Sub Total",
	                   "Log Off"};
					
	/**
	 * This constructor initialize GUI components
	 */
	public Menu() {
		menuFrame = new JFrame("Cashier Menu");
		menuFrame.getContentPane().setLayout(new BorderLayout(0,0));
		
		menuNorthPanel = new JPanel();
		menuNorthPanel.setLayout(new FlowLayout());
		menuNorthPanel.setBackground(Color.blue);
		
		menuSouthPanel = new JPanel();
		//menuSouthPanel.setBackground(new Color(0,155,0));
		menuSouthPanel.setBackground(Color.blue);
				
		menuTitlePanel = new JPanel();
		menuTitlePanel.setLayout(new BorderLayout(10,10));
		menuTitlePanel.setBackground(new Color(137,195,232));
		
		menuDetailPanel = new JPanel();
		menuDetailPanel.setLayout(new GridLayout(2,1));
		menuDetailPanel.setBackground(new Color(157,217,252));
			
		menuCenterPanel = new JPanel();
		menuCenterPanel.setLayout(new BorderLayout(0,0));
		menuCenterPanel.setBackground(new Color(160,255,150));
		
		menuStoreLabel = new JLabel(" SM Bacoor Supermarket ");
		menuStoreLabel.setForeground(Color.yellow);
		menuStoreLabel.setFont(new Font("Verdana",Font.BOLD,36));

		menuTitleLabel = new JLabel(" Cashier Menu ", JLabel.CENTER);
		menuTitleLabel.setForeground(Color.blue);
		menuTitleLabel.setFont(new Font("Courier New",Font.BOLD,24));
		
		// Acquire current date information
		GregorianCalendar calendar = new GregorianCalendar();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
								DateFormat.SHORT,
								Locale.US);
		
		// Acquire current cashier logged in
		menuCashierLabel = new JLabel("   Cashier on Duty : " + Login.cashierName);
		menuCashierLabel.setForeground(Color.red);
		menuCashierLabel.setFont(new Font("Verdana",Font.BOLD,14));
		
		menuDateLabel = new JLabel("   Date/Time : " 
								   + dateFormat.format(calendar.getTime())  
								   + "  ");
		menuDateLabel.setForeground(Color.red);
		menuDateLabel.setFont(new Font("Verdana",Font.BOLD,14));
		
		// Header
		menuHeaderLabel = new JLabel("             Products"
									+"                           Price"
									+"       Ordered");
		menuHeaderLabel.setForeground(Color.white);
		menuHeaderLabel.setFont(new Font("Verdana",Font.BOLD,18));
		
		// Set the products items and menu choices
		menuChoicePanel = new JPanel();
		menuChoicePanel.setLayout(new GridLayout(choice.length+4,1,0,0));
		menuChoicePanel.setBackground(new Color(0,0,0));
		menuChoicePanel.add(menuHeaderLabel);
		
		// Extra 2 element for Quit and SubTotal options
		menuChoiceLabel = new JLabel[choice.length + 2];
		ordered = new int[choice.length];
					
		for (int i = 0; i < choice.length; i++)	{
			
			// Set default ordered amount of all products to 0	
			ordered[i] = 0;
			
			// Populating the menu table
			menuChoiceLabel[i] = new JLabel("  [" + (i+1) + "]  " + choice[i]
										   +"      "+ price[i] + "0"
										   +"       "+ ordered[i]);
			menuChoiceLabel[i].setForeground(Color.green);
			menuChoiceLabel[i].setFont(new Font("Courier New",Font.BOLD,18));
			
			menuChoicePanel.add(menuChoiceLabel[i]);
		}
		
		// Add options to menu
		menuChoiceLabel[choice.length] = new JLabel("  [0]  " + option[0]);
		menuChoiceLabel[choice.length+1] = new JLabel("  [Q]  " 
													  + option[1] + " " 
													  + Login.cashierName);
		menuChoiceLabel[choice.length].setForeground(Color.yellow);
		menuChoiceLabel[choice.length+1].setForeground(Color.yellow);
		menuChoiceLabel[choice.length].setFont(new Font("Courier New",Font.BOLD,18));
		menuChoiceLabel[choice.length+1].setFont(new Font("Courier New",Font.BOLD,18));
		menuChoicePanel.add(menuChoiceLabel[choice.length]);
		menuChoicePanel.add(menuChoiceLabel[choice.length+1]);
		
		// Simple instructions added for user cashier
		menuGuideLabel = new JLabel("   Use the keyboard and press the appropriate keys in [ ]");
		menuGuideLabel.setForeground(Color.white);
		menuGuideLabel.setFont(new Font("Verdana",Font.BOLD,14));	
	}

	/**
	 * This method consist of frame launch events 
	 */
	public void launchFrame() {	

		menuFrame.setSize(200,350);
		
		// Arranging GUI components in Panel onto Frame
		menuDetailPanel.add(menuCashierLabel);
		menuDetailPanel.add(menuDateLabel);
		menuTitlePanel.add(menuTitleLabel, BorderLayout.WEST);
		menuTitlePanel.add(menuDetailPanel, BorderLayout.EAST);
		menuNorthPanel.add(menuStoreLabel, BorderLayout.NORTH);
		menuSouthPanel.add(menuGuideLabel, BorderLayout.SOUTH);		
		menuCenterPanel.add(menuTitlePanel, BorderLayout.NORTH);
		menuCenterPanel.add(menuChoicePanel, BorderLayout.CENTER);
		menuFrame.getContentPane().add(menuNorthPanel, BorderLayout.NORTH);
		menuFrame.getContentPane().add(menuCenterPanel, BorderLayout.CENTER);
		menuFrame.getContentPane().add(menuSouthPanel, BorderLayout.SOUTH);
		
		menuFrame.pack();		
	
		// Centering the screen on the desktop
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = menuFrame.getSize();
		menuFrame.setLocation(((screenSize.width - frameSize.width) / 2),
							((screenSize.height - frameSize.height) / 2));		
		
		menuFrame.addKeyListener(this);
		
		menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		menuFrame.setVisible(true);

	}
	
	private void refresh() {
		for (int i = 0; i < choice.length; i++)	{
						
			// Populating the menu table
			menuChoiceLabel[i].setText("  [" + (i+1) + "]  " + choice[i]
										   +"      "+ price[i] + "0"
		
										   +"       "+ ordered[i]);
		}		
	}
	
	// Unused interface methods
	public void keyTyped(KeyEvent e) { }
	public void keyReleased(KeyEvent e) { }
	
	public void keyPressed(KeyEvent e) { 		
		switch(e.getKeyCode()) {
		case 49:
		case 50:
		case 51:
		case 52:
		case 53:
		case 54:
		case 55:
		case 56:
			// Accumulate products items
			ordered[e.getKeyCode() - 49]++;
			break;
		
		case 48:
			// Calculate total
			menuFrame.setVisible(false);
			SubTotal subTotal = new SubTotal();
			subTotal.launchFrame();
			break;
			
		case 81:
			// Quit program
			menuFrame.setVisible(false);
			JOptionPane.showMessageDialog(this, "User Log Off",
				"Goodbye and have a nice day!", JOptionPane.INFORMATION_MESSAGE);
			System.exit(0);
			break;
		}
	
		// Refreshes the menu;
		this.refresh();
	}
}// End of Menu class

/**
 * This is the SubTotal class
 */
class SubTotal extends JFrame implements KeyListener {
	
	// Variable to cumulate total payments
	double perItemTotal, grandTotal;

	// GUI components
	private JFrame subTotalFrame;
	private JPanel subTotalNorthPanel,
				   subTotalSouthPanel,
				   subTotalCenterPanel,
				   subTotalTitlePanel,
				   subTotalDetailPanel,
				   subTotalOrderedPanel,
				   subTotalHeaderPanel;
	
	private JLabel subTotalStoreLabel,
				   subTotalTitleLabel,
				   subTotalCashierLabel,
				   subTotalHeaderLabel,
				   subTotalDateLabel,
				   subTotalOrderedLabel[],
				   subTotalGrandTotalLabel,
				   subTotalGuideLabel;
							   					
	/**
	 * This constructor initialize GUI components
	 */
	public SubTotal() {
		subTotalFrame = new JFrame("Sub Total");
		subTotalFrame.getContentPane().setLayout(new BorderLayout(0,0));
		
		subTotalNorthPanel = new JPanel();
		subTotalNorthPanel.setLayout(new FlowLayout());
		subTotalNorthPanel.setBackground(Color.blue);
		
		subTotalSouthPanel = new JPanel();
		//subTotalSouthPanel.setBackground(new Color(0,155,0));
		subTotalSouthPanel.setBackground(Color.blue);
				
		subTotalTitlePanel = new JPanel();
		subTotalTitlePanel.setLayout(new BorderLayout(10,10));
		subTotalTitlePanel.setBackground(new Color(137,195,232));
		
		subTotalDetailPanel = new JPanel();
		subTotalDetailPanel.setLayout(new GridLayout(2,1));
		subTotalDetailPanel.setBackground(new Color(157,217,252));
			
		subTotalCenterPanel = new JPanel();
		subTotalCenterPanel.setLayout(new BorderLayout(0,0));
		subTotalCenterPanel.setBackground(new Color(160,255,150));
		
		subTotalStoreLabel = new JLabel(" SM Bacoor Supermarket ");
		subTotalStoreLabel.setForeground(Color.yellow);
		subTotalStoreLabel.setFont(new Font("Verdana",Font.BOLD,36));

		subTotalTitleLabel = new JLabel(" TOTAL ", JLabel.CENTER);
		subTotalTitleLabel.setForeground(Color.blue);
		subTotalTitleLabel.setFont(new Font("Courier New",Font.BOLD,24));
		
		// Acquire current date information
		GregorianCalendar calendar = new GregorianCalendar();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
								DateFormat.SHORT,
								Locale.US);
		
		// Acquire current cashier logged in
		subTotalCashierLabel = new JLabel("   Cashier on Duty : " + Login.cashierName);
		subTotalCashierLabel.setForeground(Color.red);
		subTotalCashierLabel.setFont(new Font("Verdana",Font.BOLD,14));
		
		subTotalDateLabel = new JLabel("   Date/Time : " 
								   	 + dateFormat.format(calendar.getTime())  
								   	 + "  ");
		subTotalDateLabel.setForeground(Color.red);
		subTotalDateLabel.setFont(new Font("Verdana",Font.BOLD,14));
		
		// Header
		subTotalHeaderLabel = new JLabel("    Product(s)"
										+"                Price/Unit"
										+"    Ordered"
										+"    Total(RM)   ");
		subTotalHeaderLabel.setForeground(Color.white);
		subTotalHeaderLabel.setFont(new Font("Verdana",Font.BOLD,18));
		
		// Display the products items ordered on the menu
		subTotalOrderedPanel = new JPanel();
		subTotalOrderedPanel.setBackground(new Color(0,0,0));
		subTotalOrderedPanel.add(subTotalHeaderLabel);
		
		// Extra 2 element for Quit and SubTotal options
		subTotalOrderedLabel = new JLabel[Menu.choice.length];
		perItemTotal = 0;
		grandTotal = 0;
		int count = 0;
					
		for (int i = 0; i < Menu.choice.length; i++)	{
			
			if (Menu.ordered[i] > 0) {
			
			perItemTotal = Menu.ordered[i] * Menu.price[i];
			grandTotal+= perItemTotal;
			count++;
			
			// Populating the menu table
			subTotalOrderedLabel[i] = new JLabel("  " + Menu.choice[i]
										   	   +"    " + Menu.price[i] + "0"
										       +"        " + Menu.ordered[i]
										       +"       " + perItemTotal + "0");
			subTotalOrderedLabel[i].setForeground(Color.green);
			subTotalOrderedLabel[i].setFont(new Font("Courier New",Font.BOLD,18));
			
			subTotalOrderedPanel.add(subTotalOrderedLabel[i]);
			
			// Reset the ordered amount of all products type ordered to 0	
			Menu.ordered[i] = 0;
			}
		}
		
		// Show grand total figure
		subTotalGrandTotalLabel = new JLabel(" Sub Total : RM " + grandTotal + "0");
		subTotalGrandTotalLabel.setForeground(Color.yellow);
		subTotalGrandTotalLabel.setFont(new Font("Courier New",Font.BOLD,30));			
		
		subTotalOrderedPanel.add(subTotalGrandTotalLabel);
				
		// Simple instructions added for user cashier
		subTotalGuideLabel = new JLabel("   Press [ Esc ] to return to menu");
		subTotalGuideLabel.setForeground(Color.white);
		subTotalGuideLabel.setFont(new Font("Verdana",Font.BOLD,14));	
		
		subTotalOrderedPanel.setLayout(new GridLayout(count+2,1,0,0));
	}

	/**
	 * This method consist of frame launch events 
	 */
	public void launchFrame() {	

		subTotalFrame.setSize(200,350);
		
		// Arranging GUI components in Panel onto Frame
		subTotalDetailPanel.add(subTotalCashierLabel);
		subTotalDetailPanel.add(subTotalDateLabel);
		subTotalTitlePanel.add(subTotalTitleLabel, BorderLayout.WEST);
		subTotalTitlePanel.add(subTotalDetailPanel, BorderLayout.EAST);
		subTotalNorthPanel.add(subTotalStoreLabel, BorderLayout.NORTH);
		subTotalSouthPanel.add(subTotalGuideLabel, BorderLayout.SOUTH);		
		subTotalCenterPanel.add(subTotalTitlePanel, BorderLayout.NORTH);
		subTotalCenterPanel.add(subTotalOrderedPanel, BorderLayout.CENTER);
		subTotalFrame.getContentPane().add(subTotalNorthPanel, BorderLayout.NORTH);
		subTotalFrame.getContentPane().add(subTotalCenterPanel, BorderLayout.CENTER);
		subTotalFrame.getContentPane().add(subTotalSouthPanel, BorderLayout.SOUTH);
		
		subTotalFrame.pack();		
	
		// Centering the screen on the desktop
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = subTotalFrame.getSize();
		subTotalFrame.setLocation(((screenSize.width - frameSize.width) / 2),
							((screenSize.height - frameSize.height) / 2));		
		
		subTotalFrame.addKeyListener(this);
		
		subTotalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		subTotalFrame.setVisible(true);
	}

	// Unused interface methods
	public void keyTyped(KeyEvent e) { }
	public void keyReleased(KeyEvent e) { }
	
	public void keyPressed(KeyEvent e) { 
		
		// [Escape] key is pressed
		if (e.getKeyCode() == 27) {
			subTotalFrame.setVisible(false);
			Menu menu = new Menu();
			menu.launchFrame();
		}
	}
}// End of SubTotal class ...



Windows Form Deployment with SQL Database

$
0
0
I need to know :
How to include a SQL database with my Windows Form application after deployment ?

how to assign address of int variable to an entry in array of pointers

$
0
0
Hi,

Why would this not work? And what is the right thing to do.
        int x,y,z;

	printf("Enter three integers: ");
	scanf("%d %d %d",&x,&y,&z);
        
	p[0]=&x; //syntax error here
	p[1]=&y; //and here
	p[2]=&z; //and here



Senior Project Computer Science Ideas

$
0
0
So I looked through the senior project threads and I need some more relevant information that applies to what i'm looking for. I need some help coming up with an idea for my senior project for my last year of a computer science degree. I want to do something that is fun, yet fits in the time period of about 3 months to complete.

I'm currently doing some small applications for my work in C#. Since I have 3 years experience with Java and C# is similar enough, writing an application in either language is a possibility.

A lot of the advice I found recommended doing a project that is interesting to me. I'm interesting in gaming, biking, reading, so I decided to explore those options. Most of the projects I found were too big for the time period like advanced games, or too short like solving a simple algorithm.

I would like to do a project that represents skills I can show off to a future employer. I have a little experience building websites, so one of the ideas I had was to do some website with html/PhP or javascript(would have to learn) to increase my experience.

Another idea I had was to create a 2D game of some sort. I could do a clone of pacman, bomberman, load runner or some older game. The issue with this is getting the graphics and copyright issues. If I did do a game, AI interests me so I could include something with that.

Error: Cannot Find or Load Main Class

$
0
0
I'm getting the error that this topic is titled whenever I try to run something. I tried searching D.I.C, and I none of the results helped. It is even giving me this error with things that do not have packages and were compiled and run by BlueJ before. Can anyone help?

Application Not Working After Target Framework Change

$
0
0
I changed the target framework for my project from 4.5 to 3.5. I had a few errorr messages about the Microsoft.CSharp reference so I changed the framework back to 4.5. Now when I run the application the first form is just dead and doesn't seem to do anything. My first form has a progess bar which is updated using a timer but it doesn't update just stays as it is and nothing happens.

Any ideas?

Regards
Matt

PLEASE READ! Java, do-while loop

$
0
0
Hello. :surrender:/>/>

I was wondering whether anyone could tell me, whether I have written the below program correctly: :?:/>

import java.util.*;
public class Task5bDW
{
	public static void main(String[] args)
	{
		
	int d = 0;
	int i = 0;
	int n = 10;

	do {
		d++;
   		n /= 10;
	   } while ((d == 0) && (n != 0));

	System.out.println(d);

	}
}



Because 'n' is currently set to 10, the program is supposed to output the result:
0
1
(It should start at 0 and count up 1 for every digit in the value of 'n'.)

But at the moment, it only outputs 1, no matter what I set 'n' to.

Any help/assistance would be greatly appreciated.

Question About Vectors

$
0
0
Hi all,

The following line gives me a "Debug Assertion Failed!" error with "Expression: Vector subscript out of range". This means that I must be using my vector incorrectly. However I cannot use breakpoints and step through my code to find out the problem due to the way the project has been set, but I have managed to narrow it down to a certain method and a couple of lines.

int Minimax::SearchMethod(Node* node, int depth)
{
	node->GenerateChildren();
	vector<Node*> children = node->GetChildren();

	if(depth == 0 || !node->HasChildren())
	{
		return node->GetBoard()->getBoardValue();
	}

	int value = 0;

	if(node->IsPlayerOneTurn())
	{
		value = -100000;	

		for (int i = 0; i < children.size(); i++)
		{
			value = max(value, SearchMethod(children[i], depth - 1));
		}
	} 
	else
	{
		value = 100000;

		for (int i = 0; i < children.size(); i++)
		{
			value = min(value, SearchMethod(children[i], depth - 1));
		}
	}

	return value;
}



The second line of the method is the line that's throwing the error.
I cant find out why, I've tried initializing the children vector before passing "GetChildren()" but it still doesn't like it.

The method GetChildren() returns a "vector<Node*>" so that is also not the problem.

Any Ideas ?
Viewing all 51036 articles
Browse latest View live


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