Creating a static factory - java

I am making an application to control a serial attached printer and I want to provide a static factory method PrinterLocator.FindPrinters() that will return an array of the available printers connected to my system.
As an example, the Serial library provides Serial.list() which is a static method returning an array of strings corresponding to the ports available in my system. I am trying to create something similar, but I am getting an error "No enclosing instance of type SLPDriver is accessible. Must qualify the allocation with an enclosing instance of type SLPDriver"
What is the correct way to implement this design pattern?
SLPDriver:
SerialPrinter myPrinter;
void setup()
{
SerialPrinter[] availablePrinters = PrinterLocator.FindPrinters();
if(availablePrinters.length > 0)
{
myPrinter = availablePrinters[0];
}
}
void draw()
{
}
SerialPrinter:
import processing.serial.*;
static class PrinterLocator
{
static final int baudRates[] = {2400, 4800, 9600, 19200, 38400, 57600, 115200};
static final int baudCount = baudRates.length;
static SerialPrinter[] FindPrinters()
{
SerialPrinter[] foundPrinters, tempPrinters;
foundPrinters = new SerialPrinter[0];
String[] foundPorts = Serial.list();
int numPorts = foundPorts.length;
int numPrintersFound = 0;
if(numPorts <= 0) return foundPrinters;
SerialPrinter testPrinter;
tempPrinters = new SerialPrinter[numPorts];
for(int i = 0; i < numPorts; i++)
{
for(int b = 0; b < baudCount; b++)
{
testPrinter = new SerialPrinter("test", foundPorts[i], baudRates[b]);
if(testPrinter.IsValid())
{
tempPrinters[numPrintersFound] = testPrinter;
numPrintersFound++;
break;
}
}
}
if(numPrintersFound > 0)
{
foundPrinters = new SerialPrinter[numPrintersFound];
for(int i = 0; i < numPrintersFound; i++)
{
foundPrinters[i] = tempPrinters[i];
}
}
return foundPrinters;
}
}
class SerialPrinter
{
//Members
private Serial myPort;
private String printerName;
private boolean valid;
private String portName;
private int baudRate;
public SerialPrinter()
{
this("","",0);
}
public SerialPrinter(String name, String port, int baud)
{
printerName = name;
Configure(port, baud);
}
public boolean IsValid()
{
return valid;
}
public boolean Configure(String port, int baud)
{
print("Configuring Printer ");
print(port);
print("#");
print(baud);
print(": ");
try
{
myPort.stop();
myPort = null;
}
catch (Exception e) {}
portName = port;
baudRate = baud;
try
{
myPort = new Serial(this, port, baud);
myPort.clear();
myPort.write(0xA5);
int timeout = millis() + 1000;
while((millis() < timeout) && (myPort.available() == 0)) { }
if(myPort.available() > 0)
{
int inByte = myPort.read();
if(inByte == 0xC9)
{
valid = true;
}
else
{
valid = false;
}
}
else
{
valid = false;
}
}
catch (Exception e)
{
valid = false;
}
if(valid)
{
println("[OK]");
}
else
{
println("[ERR]");
}
return valid;
}
}

No enclosing instance of type SLPDriver is accessible. Must qualify the allocation with an enclosing instance of type SLPDriver
The error indicates that SerialPrinter is an inner class of SLPDriver.
You either need to change the class declaration to static:
static class SerialPrinter
{
...
Or if it's supposed to be inner, you need to use an SLPDriver instance to create a SerialPrinter:
someSLPDriver.new SerialPrinter(...)
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
The Serial constructor appears to need an instance of PApplet. The instantiation expression should really give you an error too because this refers to the SerialPrinter, not the PApplet.
Something you could try is like the following:
...
static class PrinterLocator {
...
static SerialPrinter[] FindPrinters(SLPDriver context) {
...
... = context.new SerialPrinter(...);
}
}
class SerialPrinter {
...
public boolean Configure(...) {
...
... = new Serial(PApplet.this, ...);
}
}
When you call FindPrinters within the context of the applet, you need to call it like
... = PrinterLocator.FindPrinters(this);

Related

Combination of counter and user input using Thread in Java?

I am a student and am studying threads recently. What I am trying to do is to implement MVC pattern that manages functionalities such as start counting, stop counting, reverse counting and etc...
My final goal is that, I need to get an user input whilst the counter is counting from 1, and if I input 2 (assuming that option 2 is stopping the counter), the counter should stops counting.
For example:
Counting...
1
2
3
(If I press 2 here)
Counter stopped running!
Because this is the homework from my college, I cannot upload here the code I implemented.
What I did was,
MVC pattern:
Controller class= gets model and view with Controller constructor. This class also provides service() method that uses switch case to make user to input to select the options to run the functionality for counting (eg) case1: startCounting() case2: stopCounting(), and etc...)
View class = provides options using System.out.println and displayMenu() function.
Model class = implements the functionalities such as startCounting(), stopCounting and etc...
I now need to add threads for this implementation in order to interact the user input with this counting process.
Can I please get any hints? For example, which class should I extend the Thread and in what way should I implement run() menthod?
Skeleton code:
CountController class
public class CounterController {
private Counter model;
private CounterView view;
public CounterController(Counter model, CounterView view) {
this.model = model;
this.view = view;
}
}
Model Class
public class Counter {
private int count = 0;
private boolean counting = false;
private Integer ceiling = null;
private Integer floor = null;
private boolean reverse = false;
public void startCounting() {
counting = true;
while (counting && checkLimits()) {
try {
Thread.sleep(1000);
count = reverse ? count - 1 : count + 1;
// You should replace this print with something observable so the View can handle it
System.err.println(count);
} catch (InterruptedException ignored) {}
}
}
public void stopCounting() {
counting = false;
}
public void setReverse(boolean reverse) {
this.reverse = reverse;
}
public void setCeiling(Integer ceiling) {
this.ceiling = ceiling;
}
public void setFloor(Integer floor) {
this.floor = floor;
}
public int getCount() {
return count;
}
public void resetCount() {
count = 0;
}
private boolean checkLimits() {
if (null != ceiling && count >= ceiling) {
return false;
}
if (null != floor && count <= floor) {
return false;
}
return true;
}
}
View Class
public class CounterView {
private Counter model;
public CounterView(Counter model) {
this.model = model;
}
public void launch() {
}
}
ViewUntil Class
class ViewUtils {
static int displayMenu(String header, String[] options, String prompt) {
System.out.println("\n" + header);
for (int i = 0; i < options.length; i++) {
System.out.println((i+1) + ". " + options[i]);
}
while (true) {
Integer response = getInt(prompt, true);
int selection = response != null ? response : -1;
if (selection > 0 && selection <= options.length) {
return selection;
} else {
System.out.println("Invalid menu selection");
}
}
}
static String getString(String prompt, boolean allowBlank) {
Scanner s = new Scanner(System.in);
String response;
do {
System.out.println(prompt);
response = s.nextLine();
if (!allowBlank && "".equals(response)) {
response = null;
System.out.println("Blank entry is not allowed here.");
}
} while (null == response);
return response;
}
static Integer getInt(String prompt, boolean allowBlank) {
int response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
try {
response = Integer.parseInt(str);
return response;
} catch (NumberFormatException e) {
System.out.println("Invalid input - number required");
}
} while (true);
}
static Boolean getBoolean(String prompt, boolean allowBlank) {
prompt = prompt + "(y/n) ";
Boolean response;
do {
String str = getString(prompt, allowBlank);
if ("".equals(str)) {
return null;
}
if ("y".equals(str.toLowerCase())) {
return true;
}
if ("n".equals((str.toLowerCase()))) {
return false;
}
System.out.println("Invalid input - must be y or n");
} while (true);
}
}
Main Class
public class MainDriver {
public static void main(String[] args) {
Counter model = new Counter();
CounterView view = new CounterView(model);
CounterController controller = new CounterController(model, view);
controller.service();
}
}
Using "volatile" to coerce the thread Counter to check for the newest setting values in memory and not in its "cache".
public class Counter {
private int count = 0;
private volatile boolean counting = false;
private volatile Integer ceiling = null;
private volatile Integer floor = null;
private boolean reverse = false;
...
}

How can I perform add to a Particular number in a linked list?

Am writing this Java networking program with linked list. The program adds the details of every node that contacts it and then prints it out. During the printing i want 1 to be added to Infor every time as I would be printing the details 10 times using a for loop.
error is occurring at this part:
list.get(lastPostion).getInfor()+1;
Below is my code.
public class Linked {
public static void main(String[] args) {
workPls oks = new workPls();
try {
DatagramSocket socket = new DatagramSocket(Integer.parseInt(args[0]));
socket.setSoTimeout(0);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
int data = 0;
PlsWork ok = new PlsWork(packet.getAddress(), "pc1", data);
oks.addNode(ok);
oks.print();
}
} catch (Exception error) {
error.printStackTrace();
}
}
}
public class PlsWork {
private InetAddress IP;
private String PC;
private int Infor;
public PlsWork(InetAddress IP, String PC, int Infor) {
this.IP = IP;
this.PC = PC;
this.Infor = Infor;
}
public InetAddress getIP() {
return IP;
}
public String getPC() {
return PC;
}
#Override
public String toString() {
return IP + " " + PC;
}
public int getInfor() {
return Infor;
}
}
public class workPls {
private LinkedList<PlsWork> list = new LinkedList<>();
private InetAddress ip;
private int lastPostion = 0;
public void addNode(PlsWork st) {
list.add(st);
}
public LinkedList getList() {
return list;
}
public void print() {
for (int i = 0; i > 10; i++) {
System.out.println(list);
System.out.println(list.get(lastPostion).getIP());
list.get(lastPostion).getInfor() + 1;
lastPostion+=1;
}
}
public InetAddress getip() {
return ip;
}
}
list.get(lastPostion).getInfor() + 1 adds two ints and does nothing with the result. In order to modify the Infor instance variable of a PlsWork instance, you must call another method.
Either add a void setInfor(int newValue) method to PlsWork and call:
PlsWork current = list.get(lastPostion);
current.setInfor(current.getInfor() + 1);
Or add a void incrementInfor() method to PlsWork and call:
list.get(lastPostion).incrementInfor();
Also note that you have an unrelated typo in your for loop:
for (int i = 0; i > 10; i++)
should be
for (int i = 0; i < 10; i++)

IPRange Sorter in Java [duplicate]

This question already has answers here:
How to sort ip address in ascending order
(10 answers)
Closed 6 years ago.
How do i sort the ipranges in java
For Example:
My input is a string of IpRange Address i.e
9.9.9.9/12
100.0.0.0/12
8.8.8.8/12
1.2.3.4/32
1.2.2.2/12
12.3.1.45/12
My Output Should be
1.2.2.2/12
1.2.3.4/32
8.8.8.8/12
9.9.9.9/12
12.3.1.45/12
100.0.0.0/12
TIA
You can write your own comparator. Looks to be an easy task. This is also shared in one the blogs. Following is very bare implementation of the same (only indicative),
public class TestIPSorter {
#Test
public void test() {
String[] input = {"9.9.9.9/12" ,"100.0.0.0/12" ,"8.8.8.8/12" ,"1.2.3.4/32" ,"1.2.2.2/12", "12.3.1.45/12"};
String[] expectedOutput = {"1.2.2.2/12" ,"1.2.3.4/32", "8.8.8.8/12" ,"9.9.9.9/12" ,"12.3.1.45/12", "100.0.0.0/12"};
String[] sortedIp = IPSorter.sort(input);
Assert.assertArrayEquals(expectedOutput, sortedIp);
}
}
public class IPSorter {
public static String[] sort(String[] input) {
IpAddress[] array = Arrays.stream(input).map(i -> IpAddress.valueOf(i)).toArray(IpAddress[]::new);
Arrays.sort(array);
return Arrays.stream(array).map(ipAd -> ipAd.getAddress()).toArray(String[]::new);
}
private static class IpAddress implements Comparable<IpAddress> {
private final String original;
private final String ipStart;
private final int to;
private IpAddress(String address) {
int forwardSlash = address.lastIndexOf("/");
ipStart = address.substring(0, forwardSlash);
to = Integer.parseInt(address.substring(forwardSlash + 1));
original = address;
}
static IpAddress valueOf(String address) {
return new IpAddress(address);
}
String getAddress() {
return original;
}
#Override
public int compareTo(IpAddress o) {
try {
byte[] ba1 = InetAddress.getByName(this.ipStart).getAddress();
byte[] ba2 = InetAddress.getByName(o.ipStart).getAddress();
// general ordering: ipv4 before ipv6
if (ba1.length < ba2.length)
return -1;
if (ba1.length > ba2.length)
return 1;
// we have 2 ips of the same type, so we have to compare each byte
for (int i = 0; i < ba1.length; i++) {
int b1 = unsignedByteToInt(ba1[i]);
int b2 = unsignedByteToInt(ba2[i]);
if (b1 == b2)
continue;
if (b1 < b2) {
return -1;
} else {
return 1;
}
}
return compareRange(to, o.to);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
private int compareRange(int range1, int range2) {
return Integer.compare(range1, range2);
}
private int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
}

Confusion on using instanceof along with other inherited data

I have already made a posting about this program once, but I am once again stuck on a new concept that I am learning (Also as a side note; I am a CS student so please DO NOT simply hand me a solution, for my University has strict code copying rules, thank you.). There are a couple of difficulties I am having with this concept, the main one being that I am having a hard time implementing it to my purposes, despite the textbook examples making perfect sense. So just a quick explanation of what I'm doing:
I have an entity class that takes a Scanner from a driver. My other class then hands off the scanner to a superclass and its two subclasses then inherit that scanner. Each class has different data from the .txt the Scanner read through. Then those three classes send off their data to the entity to do final calculations. And that is where my problem lies, after all the data has been read. I have a method that displays a new output along with a few methods that add data from the super along with its derived classes.EDIT: I simply cannot figure out how to call the instance variable of my subclasses through the super so I can add and calculate the data.
Here are my four classes in the order; Driver, Entity, Super, Subs:
public static final String INPUT_FILE = "baseballTeam.txt";
public static void main(String[] args) {
BaseballTeam team = new BaseballTeam();
Scanner inFile = null;
try {
inFile = new Scanner(new File(INPUT_FILE));
team.loadTeam(inFile);
team.outputTeam();
} catch (FileNotFoundException e) {
System.out.println("File " + INPUT_FILE + " Not Found.");
System.exit(1);
}
}
}
public class BaseballTeam {
private String name;
private Player[] roster = new Player[25];
Player pitcher = new Pitcher();
Player batter = new Batter();
BaseballTeam() {
name = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public void loadTeam(Scanner input) {
name = input.nextLine();
for (int i = 0; i < roster.length; i++) {
if (i <= 9) {
roster[i] = new Pitcher();
}
else if ((i > 9) && (i <= 19)) {
roster[i] = new Batter();
}
else if (i > 19) {
roster[i] = new Player();
}
roster[i].loadData(input);
roster[i].generateDisplayString();
//System.out.println(roster[i].generateDisplayString()); //used sout to test for correct data
}
}
public void outputTeam() {
if ((pitcher instanceof Player) && (batter instanceof Player)) {
for (int i = 0; i < roster.length; i++) {
System.out.println(roster[i].generateDisplayString());
}
}
//How do I go about doing calculates?
public int calculateTeamWins() {
if ((pitcher instanceof ) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamSaves() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamERA() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamWHIP() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamBattingAverage() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamHomeRuns() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamRBI() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateStolenBases() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
}
public class Player {
protected String name;
protected String position;
Player(){
name = "";
position = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getPosition() {
return position;
}
public void setPosition(String aPosition) {
position = aPosition;
}
public void loadData(Scanner input){
do {
name = input.nextLine();
} while (name.equals(""));
position = input.next();
//System.out.println(generateDisplayString());
}
public String generateDisplayString(){
return "Name: " + name + ", Position:" + position;
}
}
public class Pitcher extends Player {
private int wins;
private int saves;
private int inningsPitched;
private int earnedRuns;
private int hits;
private int walks;
private double ERA;
private double WHIP;
Pitcher() {
super();
wins = 0;
saves = 0;
inningsPitched = 0;
earnedRuns = 0;
hits = 0;
walks = 0;
}
public int getWins() {
return wins;
}
public void setWins(int aWins) {
wins = aWins;
}
public int getSaves() {
return saves;
}
public void setSaves(int aSaves) {
saves = aSaves;
}
public int getInningsPitched() {
return inningsPitched;
}
public void setInningsPitched(int aInningsPitched) {
inningsPitched = aInningsPitched;
}
public int getEarnedRuns() {
return earnedRuns;
}
public void setEarnedRuns(int aEarnedRuns) {
earnedRuns = aEarnedRuns;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getWalks() {
return walks;
}
public void setWalks(int aWalks) {
walks = aWalks;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
wins = input.nextInt();
saves = input.nextInt();
inningsPitched = input.nextInt();
earnedRuns = input.nextInt();
hits = input.nextInt();
walks = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateERA();
calculateWHIP();
return String.format(super.generateDisplayString() + ", Wins:%1d, Saves:%1d,"
+ " ERA:%1.2f, WHIP:%1.3f ", wins, saves, ERA, WHIP);
}
public double calculateERA() {
try {
ERA = ((double)(earnedRuns * 9) / inningsPitched);
} catch (ArithmeticException e) {
ERA = 0;
}
return ERA;
}
public double calculateWHIP() {
try {
WHIP = ((double)(walks + hits) / inningsPitched);
} catch (ArithmeticException e) {
WHIP = 0;
}
return WHIP;
}
}
public class Batter extends Player {
private int atBats;
private int hits;
private int homeRuns;
private int rbi;
private int stolenBases;
private double batAvg;
Batter() {
super();
atBats = 0;
hits = 0;
homeRuns = 0;
rbi = 0;
stolenBases = 0;
}
public int getAtBats() {
return atBats;
}
public void setAtBats(int aAtBats) {
atBats = aAtBats;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getHomeRuns() {
return homeRuns;
}
public void setHomeRuns(int aHomeRuns) {
homeRuns = aHomeRuns;
}
public int getRbi() {
return rbi;
}
public void setRbi(int aRbi) {
rbi = aRbi;
}
public int getStolenBases() {
return stolenBases;
}
public void setStolenBases(int aStolenBases) {
stolenBases = aStolenBases;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
atBats = input.nextInt();
hits = input.nextInt();
homeRuns = input.nextInt();
rbi = input.nextInt();
stolenBases = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateBattingAverage();
return String.format(super.generateDisplayString() +
", Batting Average:%1.3f, Home Runs:%1d, RBI:%1d, Stolen Bases:%1d"
, batAvg, homeRuns, rbi, stolenBases);
}
public double calculateBattingAverage() {
try{
batAvg = ((double)hits/atBats);
} catch (ArithmeticException e){
batAvg = 0;
}
return batAvg;
}
}
Also, its probably easy to tell I'm still fairly new here, because I just ran all my classes together in with the code sample and I can't figure out to add the gaps, so feel free to edit if need be.
The typical usage of instanceof in the type of scenario you're describing would be
if (foo instanceof FooSubclass) {
FooSubclass fooSub = (FooSubclass) foo;
//foo and fooSub now are references to the same object, and you can use fooSub to call methods on the subclass
} else if (foo instanceof OtherSubclass) {
OtherSubclass otherSub = (OtherSubclass) foo;
//you can now use otherSub to call subclass-specific methods on foo
}
This is called "casting" or "explicitly casting" foo to FooSubclass.
the concept to call the methods of your subclasses is called polymorphism.
In your runtime the most specific available method is called provided that the method names are the same.
so you can
Superclass class = new Subclass();
class.method();
and the method provided that overwrites the method in Superclass will be called, even if it's defined in the Subclass.
Sorry for my english, I hope that helps a little bit ;-)

java.lang.NoSuchFieldException

Our professor assigns us exercises through the jarpeb sytsem (Java Randomised and Personalised Exercise Builder). So the variables names are random.
public class Eczema extends Thread {
private int aurite;
private int[] serlvulate;
public Eczema(int[] serlvulate) {
this.serlvulate = serlvulate;
}
public int getAurite () {
return aurite;
}
#Override
public void run () {
try {
aurite = Integer.MAX_VALUE;
for (int i = 0; i < serlvulate.length; i++) {
if (i < this.aurite) {
this.aurite = i;
sleep (1000);
}
}
} catch (InterruptedException e) {
System.out.println("Found an Exception!");
return;
}
}
}
public class Stub {
public static int polytoky (int[]a, int[]b) throws InterruptedException {
Eczema Eczema1 = new Eczema (a);
Eczema Eczema2 = new Eczema (b);
Eczema1.start();
Eczema1.join();
Eczema2.start();
Eczema2.join();
return Math.min (Eczema1.getAurite(), Eczema2.getAurite());
}
}
I followed the instructions of the exercise but when I chech it on the cmd the following error occurs:
Field servulate not found: java.lang.NoSuchFieldException: servulate.
Any ideas how I fix it?
You appear to be accessing a field named servulate while the proper field name is serlvulate. Find the line where this happens and fix the spelling.

Categories

Resources