Writing a Java class with instance parameters, retrieve parameters and print results - java

Basically, I need to create a new simple Java class which retrieves values from my forms (that I have designed as my process and is deployed as a web application), once the method in the Java class is invoked then the Java class should just simply print out the values (e.g. system.println.out...) it got from the form in a console or text file.
Create a class with some instance parameters. Print a line stating the initial values of these parameter(s).
I am new to Java and have just started few days ago but have this requirement as part of a project.
Please someone help to write this Java class.

I recommend you to read some java beginners books (or the javadoc) in order to understand the Class constructor concept in java before trying to do write something wrong.
A rough class may be like this :
public class myClass{
int param1;
int param2;
public myClass(int firstparam, int secondparam){
this.param1 = firstparam;
this.param2 = secondparam;
}
}
public static void main(){
myClass c = new myClass(1,2);
System.out.println(c.param1 + c.param2);
}
If you don't understand this, please learn the java basis..

You can simply create a class and its constructer like:
public class Test {
//a string representation that we will initialize soon
private String text;
//Firstly you have to instantiate your Test object and initialize your "text"
public Test(String text) {
this.text = text;
//System.out.println(text);
//You can print out this text directly using this constructor which also
//has System.out.println()
}
//You can just use this simple method to print out your text instead of using the
//constructor with "System.out.println"
public void printText() {
System.out.println(this.text);//"this" points what our Test class has
}
}
While using this class is like:
public class TestApp {
public static void main(String[] args) {
Test testObject = new Test("My Text");
/*if you used the constructor with System.out.println, it directly prints out
"My Text"*/
/*if your constructor doesn't have System.out.println, you can use our
printText() method //like:*/
testObject.printText();
}
}

Related

How do you pass an updated global class variable from one method into another?

I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:
public class Game{
private int randomIndexX;
protected String spawn(){
randomIndexX = randomGenerator.nextInt(10);
return null;
}
protected String test(){
System.out.println(this.randomIndexX);
return null;
}
}
public class Player extends Game{
protected String getNextAction(String command) {
switch(command){
case "test":
test();
break;
}
}
}
public static void main(String[] args) {
Game game = new Game();
Player player = new Player();
game.spawn();
player.getInputFromConsole();
}
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().
So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:
private static in randomIndexX;
As it's value won't change depending on an object instance.
So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):
public static int getRandomIndex(){
return randomIndexX;
}
So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:
System.out.println(Game.getRandomIndex());
The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:
public static void setRandomIndex(int n){
randomIndexX = n;
}
And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.
For example, the code below will set value of randomIndexX to 5 and then print it in the console:
Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
The first problem I can see is that you don't have a constructor.(Optional)
(If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.
The second problem I can see is that you missing the end bracket.
Fix shown below.
public class Game
{
private int randomIndexX;
protected String spawn()
{
randomIndexX = 0;
return null;
}
protected String test()
{
System.out.println(randomIndexX);
return null;
}
}
You can construct it and trigger any methods you wish:
Game game = new Game();
game.spawn();
game.test()

Putting a Method in an array

So I want to make an array that has methods in it. For example:
public static void givePointBoost(){
points += 30};
or
public static void giveSword(){
Actions.giveItems(Items.diamond_sword);
Actions.givePotion(Potions.slowness);};
As you can see, both of these methods are voids. What I want to do is have an array that has all these voids in it so that I can pick a random method out of it later on. But I can't put it into an array because It says that I can't have an array of voids. When I try to make it an array of objects, It says that it can't switch from object to void. So my question is:
How do you get methods inside of Arrays?
In Java, you do not have delegates or function pointers, which you can store in collections or arrays like objects, so you have to employ the Command Pattern to achieve this. Basically, you wrap a method in an object that you pass on. The receiver can then access the method via the object.
Create a command interface:
interface ICommand {
public void execute();
}
Wrap a method (or multiple) in a class via inheritance...
class SpecificCommand implements ICommand {
public void execute() {
// Do something...
}
}
...or wrap existing methods directly in an anonymous class:
class SomeClass {
private void someMethod(int someValue) {
// Some stuff...
}
public static void main(String[] args) {
List<ICommand> commands = new ArrayList<>();
// Do something...
// Add command directly
ICommand command = new ICommand() {
#Override
public void execute() {
someMethod(42);
}
}
// Do something....
}
}
Call the commands from the list in a loop (or single):
for (ICommand command : commands) {
command.execute();
}
Let's sort things out.
Arrays in Java can only contain objects or primitives.
Collections in Java can only contain objects.
What you're looking for is called a Command Pattern.
https://www.tutorialspoint.com/design_pattern/command_pattern.htm
You'll have a list of objects, each of them with single method, let's say "execute". With polymorphism, each of this objects will do something different.
Here's an example:
import java.util.ArrayList;
import java.util.List;
public class CommandPatternExample {
public static void main(String[] args) {
List<Command> commands = new ArrayList<>();
commands.add(new GiveBoostCmmand("knight"));
commands.add(new GiveItemCommand("sword", "knight"));
for (int i = 0; i < 3; i++) {
commands.get((int)(Math.random() * commands.size())).execute();
}
}
public interface Command {
void execute();
}
static class GiveBoostCmmand implements Command {
private String targetName;
public GiveBoostCmmand(String targetName) {
this.targetName = targetName;
}
public void execute() {
System.out.println("Boosting " + this.targetName);
}
}
static class GiveItemCommand implements Command {
private String itemName;
private String targetName;
public GiveItemCommand(String itemName, String targetName) {
this.itemName = itemName;
this.targetName= targetName;
}
public void execute() {
System.out.println("Giving " + this.itemName + " to " + this.targetName);
}
}
}
Are you trying to say you want the result of the method to be added to the array?
As far as i know, i don't think you can put a method inside an array.
What you could do is create an interface, and provide implementations and then add those objects to an array. That way you could pick a random object and call the method defined in the interface.
The main question is Why do you need methods in an array?
The other solutions using the Command pattern are a great solution. But seeing your code I believe that you also should put that pattern in a specialized class whose purpose will be to initialize the pool of possible actions and select one at random when you need to.
Which would translate to the following UML
|RandomActionCaller |
|------------------------|
|- List<Command> commands|
|------------------------|
|+ selectRandomEffect() |
In the constructor you prepare the basic list of possible outcome, please refer to the other answers about the Command pattern. Maybe also add a method to add more commands to the list of commands from the outside of the class, this can be usefull.
The select random effect method would only select a random number between 0 and commands.size()-1, get the command instance and execute it. If you need to execute it somewhere else in your code just return it from the select random effect method.

java - Object cannot be resolved to variable

I'm trying to write a very simple, little java program but I'm already stuck at setting the object name.
I have 2 classes, first is Starter:
public class Starter {
public static void main(String args[]) {
Family tester = new Family();
tester.setName(testers);
}
}
If i'm right I create a Family object called tester, then I use the setName method for giving the family a name.
The Family class lookes like this:
public class Family{
String Name;
public void setName(String name){
Name = name;
}
}
But in the starter class at the tester.setName I get this error: tester cannot be resolved to a variable.
Thanks in advance for the answers!
Replace
tester.setName(testers);
with
tester.setName("testers");
As your Family class's setName() method takes a String object and String needs to be created either as above example or as below example:
String testers = new String("testers");
//and then you can use above String object as in your code snippet (as follows)
tester.setName(testers);
Unlike some other programming languages, in Java Strings must be enclosed in double quotes.
Single quotes are used for chars, a primitive data type.
You can change your code within;
tester.setName("testers");
You have some mistake in the setName():
public class Starter {
public static void main(String args[]) {
Family tester = new Family();
// tester.setName(testers);
// variable testers is not defined, you means set the name to "testers"? Try this:
tester.setName("testers");
}
}

Multiple classes basics, putting a print class into the main method

I am trying to see the basics for what is required to call in a second class, because tutorials and the book I am using are over-complicating it by using user input right now.
So here is what I tried. First is my main class and the second is the class I tried to call into the main method portraying just a simple text.
public class deck {
public static void main(String[] args) {
edward test = new edward();
System.out.print(test);
}
}
Other class:
public class edward {
public void message(int number) {
System.out.print("hello, this is text!");
}
}
How come this doesn't work?
If you could try to explain what I am doing or how this works a bit in detail that would be nice. I'm having a hard time with this part and getting a bit discouraged.
This does not work because you are printing a wrong thing: rather than printing test, you should call a method on it, like this:
public class deck {
public static void main(String[] args){
edward test = new edward();
test.message(123);
}
}
message(int) is a method (more specifically, an instance method). You call instance methods by specifying an instance on which the method is to be called (in your case, that is test), the name of the method, and its parameters.
The other kind of methods is static - i.e. like main. These methods do not require an instance, but they cannot access instance properties either.
Just an additional hint.
Every class in Java is derived from the java built in class "Object".
This common class offers some common methods.
In your case the method
public String toString()
is from interest.
You can override this method in your class edward and return the String you want.
public class edward {
#override
public String toString() {
return "hello, this is text!"
}
}
If you now use an object of class edward (test)t within the main method like you did it in your sample code
public static void main(String[] args) {
edward test = new edward();
System.out.println(test);
}
Then the text returnrd by the overriden toString() method would be printed out.
You use in this case the possibility to override methods from a super class (Object) and a subclass (edward).
Generally you would use the toString nethod to output the values of the fields (properties) of an object to show its current state.
If you not override the toString method you would get a String like eg this #ae23da which represents the current adress of the object test in memory.
public class deck
{
public static void main(String[] args)
{
edward test = new edward(); //1
System.out.print(test); //2
}
}
In line 1, you create a new edward object called test.
In line 2, you print the object itself. According to the Java API, print(Object)
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
I'm guessing that the output looked something like: edward#672563. That is because String.valueOf(obj) returns the type of obj (edward), followed by the character #, followed by the location in memory of obj (672563).
Here is some code that should do what you are attempting:
public class Deck //all class names should be capitalized
{
public static void main(String[] args)
{
Edward test = new Edward();
test.message(); //1
}
}
public class Edward
{
public void message() //`message` doesn't need a parameter
{
System.out.print("hello, this is text!");
}
}
In line 1, you call test's method message(). Calling a method executes the code that is in that method, so test.message() executes the line
System.out.print("hello, this is text!");
Here is a different way of doing the same thing:
public class Deck
{
public static void main(String[] args)
{
Edward test = new Edward();
System.out.println(test.message); //1
}
}
public class Edward
{
public String message = "hello, this is text!"; //2
}
In line 2, you create a new String "field" with the value of "hello, this is text!".
In line 1, you print the value of the field message contained in the object test.
If there are other parts of this code that you don't understand, feel free to comment on this answer!

Changing behavior of method at run time?

I have following code.
1st Class
package com.test;
public class CustomizeHere
{
private CustomizeMe customizeMe = new CustomizeMe();
public void setDescription()
{
customizeMe.setText("How about calling some method before me?");
}
}
2nd Class
package com.test;
public final class CustomizeMe
{
private String text = null;
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
}
3rd class
package com.test;
public class ReflectCustomizer
{
/**
* #param args
*/
public static void main(String[] args)
{
CustomizeHere customizeHere = new CustomizeHere();
// Requirement here is when customizeMe.setText() before method invocation we want to add some additional behaviour at run time like we should come to
// know setText() is invoked.
customizeHere.setDescription();
}
}
I wanted to know in above scenario can I anyway come to know that setText() method on CustomizeMe is being invoked? And I can't change code from customizeMe, but I have Instance of customizeMe at the runtime using reflection.
I can not change code in CustomizeMe and CustomizeHere classes. Also as java.lang.Reflect.Method class does not allow to attach any listner so that I would come to know that it is being invoked so Is there another way?
If your requirement is to set some parameters on the object before invoking some other methods, you can either have constructors that take these parameters, or to follow the Builder pattern if you have interdependencies between the various configuration options you want to create.
An advanced way is by defining an Aspect targeting the setText method which contains the additional logic you want to write. This would run for all invocations of that method on any instance of that the class this aspect targets.
Aspects are meant to address cross-cutting concerns, though.

Categories

Resources