- #71
- 10,296
- 41
Does the Keyboard.class file have to exist within a package? Do you need to use the import statement to import it? Can you provide an example of a program which successfully uses this class?
- Warren
- Warren
change = DOLLAR - amount;
numQuarters = change / QUARTER;
remQuarters = change % QUARTER;
numDimes = remQuarters / DIME;
remDimes = remQuarters % DIME;
numNickels = remDimes / NICKEL;
remNickels = remDimes % NICKEL;
numPennies = remNickels / PENNY;
Objects are passed by reference. ints are not.gnome said:The main() method has an int variable "clock",
I understood that in Java parameters are passed by reference.
There are numerous ways, some more elegant than others. A simple way is not to pass the value at all. The child threads can access the clock value by ClassName.clock, assuming that the clock variable was declared:How can I enable the child threads to see the updating of a variable that's occurring in the parent (main) thread?
I usually write this System.out.println (numQuarters + " Quarters");gnome said:System.out.println (String.valueOf(numQuarters) + " Quarters");
originally posted by prometheus:
There are numerous ways, some more elegant than others. A simple way is not to pass the value at all. The child threads can access the clock value by ClassName.clock, assuming that the clock variable was declared:
public static int clock;
Originally posted by Prometheus:
I usually write this System.out.println (numQuarters + " Quarters");
You mean the main method, not main function.gnome said:Does it need to be static? Clock is declared in the main function of the project.
The main method is static, so that all variables declared inside of it are static by context: hence, static is invalid. The main method is a method, so that all variables inside of it are local; hence, public is invalid.gnome said:I tried changing the declaration of clock but I keep getting an "illegal start of expression" error, whether I call it public static int clock; or public int clock; or static int clock;
It only let's me do int clock;
Why?
edit: Got it. I had to move the declaration outside of the main method.
// test driver for readers/writers problem
// There can be multiple readers, or a single writer, active at any time.
// This solution gives priority to writers: active readers are allowed to
// finish, but no new readers can start if there is a waiting writer.
import java.util.Random;
import java.util.Arrays;
public class testReadWrite{
public static int clock;
public static void main(String[] args){
final int trial_len = 200;
final int num_readers = 10;
final int num_writers = 10;
final int max_read_time = 10;
final int max_write_time = 4;
Random randnum = new Random();
ReaderCounter rc = new ReaderCounter();
WriterCounter wc = new WriterCounter();
BinarySemaphore writing = new BinarySemaphore();
ReaderThread r;
WriterThread w;
// int clock; // used to count iterations of the while loop (below)
clock = 0;
String s = new String();
int[] read_arrive = new int[num_readers];
int[] read_len = new int [num_readers];
int[] write_arrive = new int [num_writers];
int[] write_len = new int [num_writers];
for (int i = 0; i < num_readers; i++){
read_arrive[i] = randnum.nextInt(100);
read_len[i] = randnum.nextInt(30) + 5; // don't want any 0 durations
}
for (int i = 0; i < num_writers; i++){
write_arrive[i] = randnum.nextInt(100);
write_len[i] = randnum.nextInt(5) + 5; // don't want any 0 durations
}
Arrays.sort(read_arrive);
Arrays.sort(write_arrive);
// next 10 lines are just for evaluating the results
for (int i = 0; i<num_readers; i++){
System.out.print("reader" + String.valueOf(i) + " ");
System.out.println("arr: " + String.valueOf(read_arrive[i]) + " len: "
+ String.valueOf(read_len[i]));
}
for (int i = 0; i<num_writers; i++){
System.out.print("writer" + String.valueOf(i) + " ");
System.out.println("arr: " + String.valueOf(write_arrive[i]) + " len: "
+ String.valueOf(write_len[i]));
}
while (clock<trial_len){
System.out.println("clock = " + String.valueOf(clock));
for (int i = 0; i < num_readers; i++){
if (read_arrive[i]==clock){
// form name of new reader
s = "reader";
s = s.concat(String.valueOf(i));
// create new reader, specifying its read duration
r = new ReaderThread(s,read_len[i],rc,wc,clock);
r.start();
}
}
for (int i = 0; i < num_writers; i++){
if (write_arrive[i]==clock){
// form name of new writer
s = "writer";
s = s.concat(String.valueOf(i));
// create new reader, specifying its read duration
w = new WriterThread(s,write_len[i],rc,wc,writing,clock);
w.start();
}
}
try{
Thread.sleep(0,50);
} catch(InterruptedException e){
}
clock++;
}
}
}
// writer class for readers/writers problem
// test driver must instantiate ReaderCounter rc, WriterCounter wc
// BinarySemaphore writing, int clock
public class WriterThread extends Thread{
public WriterThread(String s, int d, ReaderCounter rctr, WriterCounter wctr,
BinarySemaphore bs, int clk){
super(s);
name = s;
duration = d;
rc = rctr;
wc = wctr;
writing = bs;
clock = clk;
System.out.println(s + "created.");
}
public void run(){
// reversed the order of the following 2 lines
wc.addWriter(); // add to count of waiting writers
rc.writerPass(); // check ReaderCounter for any active readers
writing.acquire(); // wait for semaphore to start writing
finish_time = testReadWrite.clock + duration;
while(finish_time > testReadWrite.clock) // changed from <
{
try{
System.out.println(name + ": clock = " + testReadWrite.clock +
"; finish_time = " + finish_time);
sleep(0,10); // writer is writing
} catch(InterruptedException e){
}
}
writing.release(); // finished writing
wc.delWriter();
}
private String name;
private int clock;
private int duration;
private int finish_time;
private ReaderCounter rc;
private WriterCounter wc;
private BinarySemaphore writing;
}
// reader class for readers/writers problem
// test driver must instantiate ReaderCounter rc, WriterCounter wc
// BinarySemaphore writing, int clock
public class ReaderThread extends Thread{
public ReaderThread(String s, int d, ReaderCounter rctr,
WriterCounter wctr, int clk){
super(s);
name = s;
duration = d;
rc = rctr;
wc = wctr;
clock = clk;
System.out.println(s + "created.");
}
public void run(){
wc.readerPass(); // readers not allowed to start if a writer is waiting
rc.addReader(); // makes writers wait while any readers are reading
finish_time = testReadWrite.clock + duration;
while(finish_time > testReadWrite.clock) // changed from <
{
try{
System.out.println(name + ": clock = " + testReadWrite.clock +
"; finish_time = " + finish_time);
sleep(0,10); // reader is reading
} catch(InterruptedException e) {
}
}
rc.delReader(); // finished
}
private String name;
// duration and finish_time will be used by test driver to determine when
// this thread finishes reading
private int clock;
private int duration;
private int finish_time;
private ReaderCounter rc;
private WriterCounter wc;
}
// utility class for reader/writers problem
// test driver will instantiate one ReaderCounter named "rc"
public class ReaderCounter{
public ReaderCounter(){
count = 0;
}
// used by reader starting to read
public synchronized void addReader(){
count++;
System.out.println(Thread.currentThread().getName() + " starting to read.");
notifyAll(); //in case another reader tried to start at same time
}
// used by reader finished reading
public synchronized void delReader(){
count--;
System.out.println(Thread.currentThread().getName() + " finished reading.");
notifyAll(); //in case a writer is waiting
}
// used by writer wanting to write
public synchronized void writerPass(){
while(count > 0){
try{
wait();
} catch (InterruptedException e){
}
}
System.out.println(Thread.currentThread().getName() + " checking for active readers.");
}
// unsynchronized: used by main test loop to see when to terminate
public int getCount(){
return count;
}
private int count;
}
// utility class for reader/writers problem
// test driver will instantiate one WriterCounter named "wc"
public class WriterCounter{
public WriterCounter(){
count = 0;
}
// used by writer waiting to write
public synchronized void addWriter(){
count++;
System.out.println(Thread.currentThread().getName() + " added to WriterCounter.");
notifyAll(); //in case another writer is trying
}
// used by writer finished writing
public synchronized void delWriter(){
count--;
System.out.println(Thread.currentThread().getName() + " removed from WriterCounter.");
notifyAll(); //in case other writers or readers are waiting
}
// used by reader wanting to read
public synchronized void readerPass(){
while(count > 0){
try{
wait();
} catch (InterruptedException e){
}
}
}
// unsynchronized: used by main test loop to see when to terminate
public int getCount(){
return count;
}
private int count;
}
// semaphore class for reader/writers problem
public class BinarySemaphore{
public BinarySemaphore(){
value = 1;
}
public synchronized void acquire(){
while (value == 0){
try{
wait();
} catch(InterruptedException e){
}
}
value = 0;
System.out.println(Thread.currentThread().getName() + " now writing.");
}
public synchronized void release(){
System.out.println(Thread.currentThread().getName() + " finished writing.");
value = 1;
notifyAll();
}
private int value;
}
Looks pretty good for someone new to Java. I don't have my Java JVM on this machine to load and test it, so I won't comment on it absent a question.gnome said:I believe it's now working the way I intended, but if you don't mind wading through it, I'd welcome any comments, criticisms or suggestions you may offer. Anyway, thanks for your help.
I noticed that your ReaderCounter and WriterCounter classes are 100% identical, except for slight differences in method names. I recommend that you just use the same class for both. If you were to have differences in behavior, an interface or an abstract superclass would be better than two classes that are basically identical. In this case, however, I see no difference in functionality at all.gnome said:I believe it's now working the way I intended, but if you don't mind wading through it, I'd welcome any comments, criticisms or suggestions you may offer.
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
public class Evan4 extends Applet
{
//stuff here
final int NUM_SQUARES = 64;
final int SQUARE_WIDTH = 30;
int x = 5;
int y = 5;
public void paint (Graphics g)
{
for (int count = 0; count < NUM_SQUARES; count++);
{g.setColor (Color.black);
g.fillRect(x,y,SQUARE_WIDTH,SQUARE_WIDTH);
x += SQUARE_WIDTH;
y += SQUARE_WIDTH;
}
}
}
import java.applet.Applet;
import java.awt.*;
public class Evan4 extends Applet
{
//variables and values
final int LIMIT = 8;
int x = 20;
int y = 20;
int height = 20;
int width = 20;
int ypos;
int xpos;
public void paint (Graphics g)
{
//colour of background
setBackground (Color.gray);
// initial box color
g.setColor (Color.white);
//loop for x
for (int count = 0; count < LIMIT; count++)
//y for loop
{
for (int county = 0; county < LIMIT; count++)
{
//x and y values changing
xpos = x+width*count;
ypos = y+height*county;
//if box is even count draw box black, else white
if ((count + county) % 2 ==0)
g.setColor (Color.black);
else
g.setColor (Color.white);
g.fillRect (xpos, ypos, width, height);
}
}
}
}
TenaliRaman said:You have made one small but highly annoying error ...
Look at this statement :-
for (int county = 0; county < LIMIT; count++)
Do u see something wrong here?
-- AI
You are incrementing count in a loop that tests county.ek said:No I don't. I suck at java.
chroot said:You are incrementing count in a loop that tests county.
- Warren
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
;
public class Evan4c extends Applet
{
//variables and values
final int WIDTH = 20;
final int LENGTH = 20;
final int LIMIT = 8;
int x = 20;
int y = 20;
int height = 20;
int width = 20;
int ypos;
int xpos;
int n = 150; // wait n milliseconds
int w = (int) (Math.random () * 41);
public void paint (Graphics g)
{
//colour of background
setBackground (Color.cyan);
// initial box color
g.setColor (Color.white);
//loop for x
for (int count = 0; count < LIMIT; count++)
//y for loop
{
for (int county = 0; county < LIMIT; county ++)
{
//x and y values changing
xpos = x+width*count;
ypos = y+height*county;
//if box is even count draw box black, else white
if ((count + county) % 2 ==0)
Color c = new Color;
(int)(Math.random () * 256);); // red = 0..255
(int)(Math.random () * 256), // green = 0..255
(int)(Math.random () * 256)); // blue = 0..255
g.setColor (c);
else
Color c = new Color (
(int)(Math.random () * 256), // red = 0..255
(int)(Math.random () * 256), // green = 0..255
(int)(Math.random () * 256)); // blue = 0..255
g.setColor (c);
g.fillRect (xpos, ypos, width, height);
}
}
}
}
C:\Documents and Settings\Evan\Desktop\Evan4c.java:47: '.class' expected
(int)(Math.random () * 256), // red = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:48: ')' expected
(int)(Math.random () * 256); // green = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:49: not a statement
(int)(Math.random () * 256); // blue = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:55: '.class' expected
(int)(Math.random () * 256), // red = 0..255
^
C:\Documents and Settings\Evan\Desktop\Evan4c.java:57: ')' expected
(int)(Math.random () * 256); // blue = 0..255
public class evan5ccc
{
/* the method tests whether a number is prime*/
public static boolean Primes(int input)
{
for (int x=2; x < input; x++)
if (input % x == 0)
return false;
return true;
}
/*
computes the smallest prime factor of the input number,
returns that number divided by its smallest prime factor
*/
public static int factor (int input)
{
if (input == 1)
return input;
else
{
for (int x=2; x <= input; x++)
if (input % x == 0)
{
System.out.print(" " + x );
return (input / x);
}
}
return 0;
}
public static void main(String args[])
{
int number; // number to be decomposed
for (number=432731; number > 432701; number--)
System.out.println("Prime factors of " + number + ":");
while (number != 1)
{
number = factor(number);
}
}
}
Prime factors of 123456760:
Prime factors of 123456761:
Prime factors of 123456762:
Prime factors of 123456763:
Prime factors of 123456764:
Prime factors of 123456765:
Prime factors of 123456766:
Prime factors of 123456767:
Prime factors of 123456768:
Prime factors of 123456769:
Prime factors of 123456770:
Prime factors of 123456771:
Prime factors of 123456772:
Prime factors of 123456773:
Prime factors of 123456774:
Prime factors of 123456775:
Prime factors of 123456776:
Prime factors of 123456777:
Prime factors of 123456778:
Prime factors of 123456779:
Prime factors of 123456780:
Prime factors of 123456781:
Prime factors of 123456782:
Prime factors of 123456783:
Prime factors of 123456784:
Prime factors of 123456785:
Prime factors of 123456786:
Prime factors of 123456787:
Prime factors of 123456788:
Prime factors of 123456789:
3 3 3607 3803
Prime factors of 123456760: 2 2 2 5 7 271 1627
Prime factors of 123456761: 123456761
Prime factors of 123456762: 2 3 3 11 13 47963
Prime factors of 123456763: 4021 30703
Prime factors of 123456764: 2 2 617 50023
Prime factors of 123456765: 3 5 523 15737
Prime factors of 123456766: 2 1051 58733
Prime factors of 123456767: 7 17636681
Prime factors of 123456768: 2 2 2 2 2 2 2 2 3 160751
Prime factors of 123456769: 53 283 8231
Prime factors of 123456770: 2 5 29 425713
Prime factors of 123456771: 3 3 3 17 268969
Prime factors of 123456772: 2 2 30864193
Prime factors of 123456773: 11 83 135221
Prime factors of 123456774: 2 3 7 7 419921
Prime factors of 123456775: 5 5 13 19 19993
Prime factors of 123456776: 2 2 2 79 195343
Prime factors of 123456777: 3 5779 7121
Prime factors of 123456778: 2 23 1531 1753
Prime factors of 123456779: 109 173 6547
Prime factors of 123456780: 2 2 3 3 5 47 14593
Prime factors of 123456781: 7 41 149 2887
Prime factors of 123456782: 2 61728391
Prime factors of 123456783: 3 2797 14713
Prime factors of 123456784: 2 2 2 2 11 11 43 1483
Prime factors of 123456785: 5 24691357
Prime factors of 123456786: 2 3 20576131
Prime factors of 123456787: 31 31 128467
Prime factors of 123456788: 2 2 7 13 17 71 281
Prime factors of 123456789: 3 3 3607 3803