I have a class called pixel. I am making a constructor which takes in the red,green,blue,alpha values of a single pixel. How can I have it so that the program only take in valid values for these (e.g. 0 to 255) without using if statements?
Here is my class below:
public class Pixel {
public int redPix;
public int bluePix;
public int greenPix;
public int alpha;
public Pixel(int redPix , int bluePix , int greenPix , int alpha) {
this.redPix = redPix;
this.bluePix = bluePix;
this.greenPix = greenPix;
this.alpha = alpha;
}
public void setRed(int redPix) {
this.redPix = redPix;
}
public int getRed() {
return(redPix);
}
public void setBlue(int bluePix) {
this.bluePix = bluePix;
}
public int getBlue() {
return(bluePix);
}
public void setGreen(int greenPix) {
this.greenPix = greenPix;
}
public int getGreen() {
return(greenPix);
}
public void setAlpha(int alpha) {
this.alpha = alpha;
}
public int getAlpha() {
return(alpha);
}
public static void main(String[] args){
}
}
You can use assertions to specify class invariants. It is actually recommended for private methods.
assert x >= 0 && x <= 255;
Likely, best you can do is to write method-helper like this:
private void checkArg(int arg) {
if (arg < 0 || arg > 255) {
throw new IllegalArgumentException("Wrong argument: " + arg);
}
}
And then use it in the beginning of all your methods.
Related
I am trying to write a public instance method names move()
It takes two integer arguments which showing the amount that the objects needs to change the values of xPos and yPos.
I don't want the method the return a value.
I have done this below but I get the following error message?
Compilation failed (18/01/2020 15:16:31)
Error: line 1 - method move in class StickFigure cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
Could I get some guidance where I am going wrong.
/*Instance variables*/
private int xPos;
private int yPos;
private Circle head;
private Triangle body;
private Rectangle leg;
public person()
{
super();
this.head = new Circle(30, OUColour.PINK);
this.body = new Triangle (50, 50, OUColour.RED);
this.leg = new Rectangle (6, 50, OUColour.PINK);
this.setXPos(25);
this.setYPos(220);
this.alignAll();
}
public void setXPos(int newPos)
{
this.xPos = newPos;
this.body.setXPos(newPos);//part (b)(iii)
}
public int getXPos()
{
return this.xPos;
}
public void setYPos(int newPos)
{
this.yPos = newPos;
this.body.setYPos(newPos);//part (b)(iii)
}
public int getYPos()
{
return this.yPos;
}
public Circle getHead()
{
return this.head;
}
public Triangle getBody()
{
return this.body;
}
public Rectangle getLeg()
{
return this.leg;
}
public void alignHead()
{
this.head.setXPos(this.body.getXPos() + (this.body.getWidth() - this.head.getDiameter())/2);
this.head.setYPos(this.body.getYPos() - this.head.getDiameter());
}
public void alignBody()
{
this.body.setXPos(25);
this.body.setYPos(220);
}
public void alignLeg()
{
this.leg.setXPos(this.body.getXPos() + (this.body.getWidth() - this.leg.getWidth())/2);
this.leg.setYPos(this.body.getYPos() + this.leg.getHeight());
}
public void alignAll()
{
this.alignBody();
this.alignHead();
this.alignLeg();
}
public void move(int newxPos, int newyPos)
{
this.body.setXPos(xPos + newxPos);
this.body.setYPos(yPos + newyPos);
this.alignAll();
this.delay(20);
}
If you want method move to take arguments, you have to declare it:
public void move(int xPos, int yPos)
instead of
public void move()
I'm learning the concept of neural networks. I decided to try making the neuron class by myself. What is the best way to implement different activation functions in my code? Now it uses only the binary step function.
It's my first try in coding neural networks so if you have any suggestions about my code, or it is completely dumb, please let me know.
Here is my code:
public class Neuron {
// properties
private ArrayList<Neuron> input;
private ArrayList<Float> weight;
private float pot, bias, sense, out;
private boolean checked;
// methods
public float fire(){
pot = 0f;
if (input != null) {
for (Neuron n : input){
if (!n.getChecked()){
pot += n.fire()*weight.get(input.indexOf(n));
} else {
pot += n.getOut()*weight.get(input.indexOf(n));
} // end of condition (checked)
} // end of loop (for input)
} // end of condition (input exists)
checked = true;
pot -= bias;
pot += sense;
out = actFunc(pot);
return out;
} // end of fire()
// getting properties
public float getPot(){return pot;}
public boolean getChecked(){return checked;}
public float getOut(){return out;}
// setting properties
public void stimulate(float f){sense = f;}
public void setBias(float b){bias = b;}
public void setChecked(boolean c){checked = c;}
public void setOut(float o){out = o;}
// connection
public void connect(Neuron n, float w){
input.add(n);
weight.add(w);
}
public void deconnect(Neuron n){
weight.remove(input.indexOf(n));
input.remove(n);
}
// activation function
private float actFunc(float x){
if (x < 0) {
return 0f;
} else {
return 1f;
}
}
// constructor
public Neuron(Neuron[] ns, float[] ws, float b, float o){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < ws.length; i++) weight.add(ws[i]);
} else {
input = null;
weight = null;
}
bias = b;
out = o;
}
public Neuron(Neuron[] ns){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < input.size(); i++) weight.add((float)Math.random()*2f-1f);
} else {
input = null;
weight = null;
}
bias = (float)Math.random();
out = (float)Math.random();
}
}
First, define interface of any activation function:
public interface ActivationFunction {
float get(float f);
}
Then write some implementations:
public class StepFunction implements ActivationFunction {
#Override
public float get() {return (x < 0) ? 0f : 1f;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get() {return StrictMath.tanh(h);}
}
Finally, set some implementation to your Neuron:
public class Neuron {
private final ActivationFunction actFunc;
// other fields...
public Neuron(ActivationFunction actFunc) {
this.actFunc = actFunc;
}
public float fire(){
// ...
out = actFunc.get(pot);
return out;
}
}
as following:
Neuron n = new Neuron(new SigmoidFunction());
Note, neural netoworks are using signal propagation through neurons, where weights are produced. Computing of weight depends also on first derivative of an activation function. Therefore, I would extend ActivationFunction by method, which will return first derivative at specified point x:
public interface ActivationFunction {
float get(float f);
float firstDerivative(float x);
}
So the implemenations will look like:
public class StepFunction implements ActivationFunction {
#Override
public float get(float x) {return (x < 0) ? 0f : 1f;}
#Override
public float firstDerivative(float x) {return 1;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get(float x) {return StrictMath.tanh(x);}
// derivative_of tanh(x) = (4*e^(2x))/(e^(2x) + 1)^2 == 1-tanh(x)^2
#Override
public float firstDerivative(float x) {return 1 - Math.pow(StrictMath.tanh(x), 2);}
}
Then, use actFunction.firstDerivative(x); in fire() method where weight is being computed.
I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}
I've got this custom class and I want to sort it by saturation and brightness.
I've tried a custom comperator class, but it doesn't work.
Now I've tried to implement Comparable. The program runs through the code but doesn't sort the list at the end.
Here is my code.
Part of the testing class:
ArrayList<HSBColor> colorList = new ArrayList<HSBColor>(colors.values());
Collections.sort(colorList);
for(HSBColor co : colorList){
System.out.println(co.toString());
}
Custom Class HSBColor
public class HSBColor implements Comparable<HSBColor>{
private float H;
private float S;
private float B;
public HSBColor(float h, float s, float b) {
H = h;
S = s;
B = b;
}
public float getH() {
return H;
}
#Override
public String toString() {
return String.format("%.2f %.2f %.2f", H,S,B);
}
public void setH(float h) {
H = h;
}
public float getS() {
return S;
}
public void setS(float s) {
S = s;
}
public float getB() {
return B;
}
public void setB(float b) {
B = b;
}
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS() && this.getB() > o.getB()){
return 1;
}
else{
return -1;
}
}
}
Thanks in advance!
EDIT: Extra code
This are the colors before the sort:
Color HSB H:28.60465 S:71.07438 B:47.45098
Color HSB H:4.4999995 S:73.059364 B:85.882355 >> This is the one i need
Color HSB H:64.18605 S:79.62963 B:21.176472
Color HSB H:65.714294 S:39.873417 B:61.960785
Color HSB H:23.333332 S:40.0 B:70.588234
This are the colors after the sort
28,60 71,07 47,45
65,71 39,87 61,96
23,33 40,00 70,59
4,50 73,06 85,88
64,19 79,63 21,18
**EDIT new Algorithm **
This one compares it right, but doesn't sort them right..
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS()) {
if(this.getB() >o.getB()){
return 1;
}
else{
return 0;
}
}
else{
if(this.getB() < o.getB()){
return -1;
}
else{
return 0;
}
}
}
Your compareTo method doesn't define a proper ordering.
Suppose that this.getS() > o.getS() but this.getB() < o.getB().
this.compareTo(o) would return -1, but o.compareTo(this) would also return -1.
If A < B and B < A this is not a proper ordering.
A proper ordering would first compare by the more important property, and then, in case of equality, by the less important property.
For example :
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS()){
return 1;
} else if (this.getS() < o.getS()) {
return -1;
} else {
if (this.getB() > o.getB()) {
return 1;
} else if (this.getB() < o.getB()) {
return -1;
} else {
return 0;
}
}
}
There is an issue around compareTo method. You should use it like:
#Override
public int compareTo(HSBColor o) {//if saturation is equal then compare brightness.
if (this.S == o.getS()) {
return Float.compare(B, o.getB());
}
return Float.compare(S, o.getS());
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm creating a Slick2D game. Right now, I'm creating a Video class, which contains inner classes (FrameSize, FPS, FullScreen..). So I had an OOD idea to crate in way, like we call System.out.println(). That means that I will have public Video class and public static instances of his inner clasess, but netbeans IDE throws me a hint with "Exporting non-public type through public API ". So, should I just ignore that and keep doing the way I was doing or it would be great if you could suggest me your idea?
VIDEO
public class Video {
public static FrameSize frameSize;
public static FullScreen fullScreen;
public static FPS fps;
private Video() {}
public static void loadArguments(Scanner loadInput) {
boolean isVideo = false;
String readLine;
while (loadInput.hasNext()) {
readLine = loadInput.next();
if (readLine.equalsIgnoreCase("video")) {
isVideo = true;
break;
}
}
while (isVideo && loadInput.hasNext()) {
readLine = loadInput.next();
if (readLine.equalsIgnoreCase("end")) {
break;
}
String[] line = readLine.split("=");
String key = line[0];
String value = line[1];
switch (key) {
case "width":
frameSize.setWidth(Integer.parseInt(value));
break;
case "height":
frameSize.setHeight(Integer.parseInt(value));
break;
case "fullscreen":
break;
case "fps":
break;
default:
System.err.println("Unknown video key: " + key);
break;
}
}
}
public static void saveArguments(String filePath) {
Scanner saveInput;
try {
saveInput = new Scanner(new File(filePath));
} catch (FileNotFoundException fne) {
System.err.println("Invalid settings-file.");
return;
}
// TO DO: save function
saveInput.close();
}
class FrameSize {
public final int[][] SIZE_VALUES = {
{800, 600},
{1000, 700},
{1200, 800},
{1400, 900}
};
private int index;
private int width, height;
private FrameSize() {}
public void setSize(int width, int height) {
this.width = width;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
#Override
public String toString() {
return this.width + " x " + this.height;
}
}
class FullScreen {
private boolean fullScreen;
private FullScreen() {}
public boolean isFullScreen() {
return fullScreen;
}
public void setFullScreen(boolean fullScreen) {
this.fullScreen = fullScreen;
}
#Override
public String toString() {
return "" + fullScreen;
}
}
class FPS {
private boolean FPS;
private FPS() {}
public boolean isFPS() {
return FPS;
}
public void setFPS(boolean FPS) {
this.FPS = FPS;
}
#Override
public String toString() {
return "" + fps;
}
}
}
AUDIO
public class Audio {
private static Sound sound;
private static Volume volume;
private Audio() {}
public void loadArguments(Scanner loadInput) {
boolean isAudio = false;
String readLine;
while (loadInput.hasNext()) {
readLine = loadInput.next();
if (readLine.equalsIgnoreCase("audio")) {
isAudio = true;
break;
}
}
while (isAudio && loadInput.hasNext()) {
readLine = loadInput.next();
if (readLine.equalsIgnoreCase("end")) {
break;
}
String[] line = readLine.split("=");
String key = line[0];
String value = line[1];
switch (key) {
case "sound":
break;
case "volume":
break;
default:
System.err.println("Unknown audio key: " + key);
break;
}
}
}
public void saveArguments(String filePath) {
Scanner saveInput;
try {
saveInput = new Scanner(new File(filePath));
} catch (FileNotFoundException fne) {
System.err.println("Invalid settings-file.");
return;
}
// TO DO: save function
saveInput.close();
}
class Sound {
private boolean sound;
private Sound() {}
public boolean isSound() {
return sound;
}
public void setSound(boolean sound) {
this.sound = sound;
}
#Override
public String toString() {
return "" + sound;
}
}
class Volume {
private static final double PITCH = 0.1d;
private double volume;
private Volume() {}
public double getVolume() {
return volume;
}
public void setVolume(double volume) {
this.volume = volume;
}
public void increaseVolume() {
if (!isVolumeRange(this.volume)) {
return;
}
this.volume = this.volume + PITCH;
}
public void decreaseVolume() {
if (!isVolumeRange(this.volume)) {
return;
}
this.volume = this.volume - PITCH;
}
public boolean isVolumeRange(double volume) {
return volume >= 0.0 && volume <= 10.0;
}
}
}
Video class contains a declaration of a public class variable frameSize of type FrameSize.
A public modifier means, that frameSize variable is visible to all.
package package1;
public class Video {
public static FrameSize frameSize;
}
// private class
class FrameSize {
}
However FrameSize is a local class - it is visible only to members of the same package. In the above example, only members of package package1 can see that class, and below code compiles fine:
package package1;
public class Test {
void test(){
FrameSize x = Video.frameSize;
}
}
however this code (different package) gives a compilation error:
package package2;
import package1.*;
public class Test {
void test(){
// this line won't compile - FrameSize class is unknown
FrameSize x = Video.frameSize;
// but this line compiles fine - Object class is public
Object y = Video.frameSize;
}
}
NetBeans warns you about this, because most likely it is unintentional error - why do you want to make some field value accessible to all without publishing the type of this field, that in effect prevents them from using that field ?
If you want make the variable accessible only to other classes within the same package, declare it as protected, not public.
But if it is an intentional declaration - then ignore the warning and leave it as is.