Organize methods for each primitives in Java - java

I'm trying to structure a bunch of static methods I have coded such that they are easy to follow in groups. (I still have to read from and write in the console.)
In a "console" package, I have a Java class called "Read", which contains nested classes "Number", "NumberMinimum", "NumberMaximum"... that all contain methods to interpret each data types (Byte, Short, Int...) since generics don't apply.
Console
Read
Number
NumberMinimum
NumerMaximum
...
That way, I just import console.Read in my project class, and call my methods using Read.Number.getInt() for instance.
Is there a better way to organize my methods than using nested classes?

I think you should work with java.lang.Number class. It contains all method you want.
Take a look in this example:
public class Tests {
public static void main(String[] args) {
float number = 12;
Read.setNumber(number);
byte byteValue = Read.getNumber().byteValue();
System.out.println(byteValue);
}
public static class Read{
private static Number number;
private static Number numberMinimum;
private static Number numberMaximum;
public static Number getNumber(){
return number;
}
public static void setNumber(Number number){
Read.number = number;
}
public static Number getNumberMinimum() {
return numberMinimum;
}
public static void setNumberMinimum(Number numberMinimum) {
Read.numberMinimum = numberMinimum;
}
public static Number getNumberMaximum() {
return numberMaximum;
}
public static void setNumberMaximum(Number numberMaximum) {
Read.numberMaximum = numberMaximum;
}
}
}

Related

Accessing multiple nested static objects

I want to create a set of classes that allows me to write records
What I want to achieve is this
Record.write.field1();
Record.write.field2();
My understanding is that I can create multiple static nested objects but I'm struggling with it
I created the following
public abstract class Record{
public Write write;
}
public abstract class Write{
public static void field1();
}
The approach above hasn't helped me achieve that.
The questions I have is
Can I write a set of classes in a way so I can achieve the following pattern
Record.write.field1();
Record.write.field2();
This is so that I can scale it up when needing to add additional field
If I can, is this a good approach?
If I can't, what's the best approach?
Thank you
UPDATE: I can do Record.write but can't do Record.write.field15();
public class Record {
public static Write write;
}
public class Write {
public static void field15(){
System.out.println("Hello");
}
}
This allows you to write the code the way you want:
class Record {
public static Write write = new Write();
}
class Write {
public void field15(){
System.out.println("Hello");
}
}
public class Main {
public static void main(String[] args) {
Record.write.field15(); // prints "Hello"
}
}
Note that static methods are invoked on the class name, and instance methods are invoked on a specific instance value.

How can I avoid having to rely on an object of another class to make the methods in a different class work?

Maybe the title was confusing, so here's a snippet of what I'm trying to avoid:
public class Generator{
private static GUI userInterface;
public static boolean specialValidator(String specialEntryText)
{
if(entryValidator(specialEntryText))
{
int specialChars = Integer.parseInt(specialEntryText);
int maxPossible = Integer.parseInt(userInterface.getLength())-3;
if(specialChars < 1 || specialChars > maxPossible)
{
return false;
}
return true;
}
return false;
}
public static void main(String[] args) {
userInterface = new GUI();
}
}
My program runs and functions as intended (keep in mind there is more to it than this), but I don't know if what I've done here is considered bad practice or what the downsides of doing it this way are. If my main method was not in the Generator class, this would not work, which seems like a problem to me.
Also, is there a specific name for what I did here, too?
The main method is the entry point of the program, and it needs to be in a class. It does not need to be in the Generator class.
As long as there is access to the class that you want to use, you can call it from another class. In you case it is public so it should be OK.
If it is in another class it could be something like
package yourPackage;
public class Main {
public static void main (String[] args) {
Generator gen = new Generator ();
//
gen.specialValidator(..);
}
}
Many things jump out at me.
There seems to be a dependency on GUI in specialValidator which is producing a "tight coupling" - you can't use the method without GUI.
This doesn't seem to make sense to me. You want to focus on reducing this coupling/dependency by passing all the required information into the method directly, for example...
public class Generator {
public static boolean specialValidator(String specialEntryText, int length) {
if (entryValidator(specialEntryText)) {
int specialChars = Integer.parseInt(specialEntryText);
// Any resason we're not using the specialEntryText length?
int maxPossible = length - 3;
if (specialChars < 1 || specialChars > maxPossible) {
return false;
}
return true;
}
return false;
}
}
Now specialValidator doesn't care "how" the information is generated, only that the information is made available to it. This "decouples" the method and makes it more independent, meaning you can call it any way you like (it also supports "dependence injection" making it more testable 😝)
And now you can call it anyway you like, for example...
public class Main {
public static void main(String[] args) {
Generator.specialValidator("some text", 8);
}
}

Return a Reference to a Class with Static Methods and Static Fields Without Instantiation

I want to create a wrapper class that calls static methods and member fields from a class that is provided by a library I am unable to view the code.
This is to avoid boilerplate setting code of the global member fields when I need to use a static method in a specific context.
I want to try to avoid creating wrapper methods for each static method.
My question:
Is it possible to return a class with static methods from a method to access just the static methods without instantiating it?
Code is below with comments in-line.
The code is used to demonstrate a change in a static value when the method getMath() is invoked.
I want to avoid the setting of the value before calling the static method.
StaticMath.setFirstNumber(1);
StaticMath.calc(1);
StaticMath.setFirstNumber(2);
StaticMath.calc(1);
I am using the Eclipse IDE and it comes up with Warnings, which I understand, but want to avoid.
I tried searching for something on this subject, so if anyone can provide a link I can close this.
public class Demo {
// Static Methods in a class library I don't have access to.
static class StaticMath {
private static int firstNum;
private StaticMath() {
}
public static int calc(int secondNum) {
return firstNum + secondNum;
}
public static void setFirstNumber(int firstNum) {
StaticMath.firstNum = firstNum;
}
}
// Concrete Class
static class MathBook {
private int firstNum;
public MathBook(int firstNum) {
this.firstNum = firstNum;
}
// Non-static method that gets the class with the static methods.
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
// I don't want to instantiate the class.
return new StaticMath();
}
}
public static void main(String... args) {
MathBook m1 = new MathBook(1);
MathBook m2 = new MathBook(2);
// I want to avoid the "static-access" warning.
// Answer is 2
System.out.println(String.valueOf(m1.getMath().calc(1)));
// Answer is 3
System.out.println(String.valueOf(m2.getMath().calc(1)));
}
}
I'd just wrap it to make for an atomic operation:
public static class MyMath{
public static synchronized int myCalc( int num1 , int num2 ){
StaticMath.setFirstNum(num1);
return StaticMath.calc(num2);
}
}
Drawback: You'll have to make sure, StaticMath is not used avoiding this "bridging" class.
Usage:
int result1 = MyMath.myCalc( 1, 1 );
int result1 = MyMath.myCalc( 2, 1 );
You shouldnt call a static method through an object reference. You should directly use class reference to call a static method like this:
StaticMath.calc(1)
But if you still need it for some reason, you can return null in getMath method, but you will still get warning in Eclipse:
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
return null;
}
I infer that question is not properly asked if the answer is not
StaticMath.calc(1)
Other issue you may be facing due to package visibility to static inner classes. Which is a design choice by the writer of Demo class. If you can mark your classes MathBook and StaticMath public then you can access them like below:
Demo.StaticMath.calc(1);

Code seems out-of-scope, How to fix? (Simple Queue-ADT program)

Im not sure how to exactly explain this problem, but Im pretty sure Im making a very simple mistake that can be corrected quite quickly.
Also, I thought it would be more convenient if this was shown off as a screenshot. The first two tabs are my interface and error catching classes.
As you can see, the code for methods to use in my Queue ADT seems to be out of scope. So I can move on and complete this bit of coursework, can someone explain to me why it is out of scope?
Thanks for any help!
You declare those variables in main method, so only main local scope know them. Move the declaration to class level
public class QueueProgram {
private static int queuesize = 10;
public static void main(String[] args) {
}
}
Note I declared queuesize as static since the main uses it. Another option is to create getters and setters and call them with an instance of QueueProgram
public class QueueProgram {
private int queuesize = 10;
public int getQueuesize() {
return queuesize;
}
public void setQueuesize(int size) {
queuesize = size;
}
public static void main(String[] args) {
QueueProgram program = new QueueProgram();
program.getQueuesize(); // return 10;
program.setQueuesize(5);
program.getQueuesize(); // now it is 5;
}
}

Making a static duplicate of non-static integer

For my programming class in first year engineering I have to make a D-game in Java, with only very little knowledge of Java.
In one class I am generating a random integer via
public int rbug = (int)(Math.random() * 18);
every so many ticks. I have to use this integer in another class (in the requirements for an if-loop), and apparently it needs to be static. But when I change the variable to public int static, the value doesn't change any more.
Is there an easy way to solve this problem?
Edit: part of code added:
public int rbug = (int)(Math.random() * 18);
which is used in
public void render(Graphics g){
g.drawImage(bugs.get(rbug), (int)x, (int)y, null);
And in another class:
if(Physics.Collision(this, game.eb, i, BadBug.rbug)){
}
As error for BadBug.rbug I get the message
Cannot make a static reference to a non-static field
Using static to make things easier to access is not a very good ideal for design. You would want to make variables have a "getter" to access them from another class' instance, and possibly even a "setter". An example of this:
public class Test {
String sample = 1337;
public Test(int value) {
this.sample = value;
}
public Test(){}
public int getSample() {
return this.sample;
}
public void setSample(int setter) {
this.sample = setter;
}
}
An example of how these are used:
Test example = new Test();
System.out.println(example.getSample()); // Prints: 1337
example = new Test(-1);
System.out.println(example.getSample()); // Prints: -1
example.setSample(12345);
System.out.println(example.getSample()); // Prints: 12345
Now you might be thinking "How do I get a string from the class that made the instance variable within the class?". That's simple as well, when you construct a class, you can pass a value of the class instance itself to the constructor of the class:
public class Project {
private TestTwo example;
public void onEnable() {
this.example = new TestTwo(this);
this.example.printFromProject();
}
public int getSample() {
return 1337;
}
}
public class TestTwo {
private final Project project;
public TestTwo(Project project) {
this.project = project;
}
public void printFromProject() {
System.out.println(this.project.getSample());
}
}
This allows you to keep single instances of classes by passing around your main class instance.
To answer the question about the "static accessor", that can also be done like this:
public class Test {
public static int someGlobal = /* default value */;
}
Which allows setting and getting values through Test.someGlobal. Note however that I would still say that this is a horrible practice.
Do you want to get a new number every time that you want BadBug.rbug? Then convert it from a variable to a method.

Categories

Resources