How can i access an object from another method in java? - java

I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.
Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}

While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.
This example:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
Will work, however, it would be better if it was more like this...
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}

You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.
public class SomeClass {
NumberList numberlist; // Definition
....
Then in your create() function just say:
numberlist= new NumberList(length, offset); // Initialization

Declare numberList outside your methods like this:
NumberList numberList;
Then inside create() use this to initialise it:
numberList = new NumberList(length, offset);
This means you can access it from any methods in this class.

Related

How can my 2nd constructor parameter work?

import java.util.Scanner;
class BloodData{
static Scanner in = new Scanner(System.in);
static String bloodType;
static String rhFactor;
public BloodData(){
bloodType = "O";
rhFactor = "+";
}
public BloodData(String bt, String rh){
bloodType = bt;
rhFactor = rh;
}
public void display() {
System.out.println(bloodType+rhFactor+" is added to the blood bank");
}
public static void main(String[]args) {
System.out.println("Enter Blood Type(O, A, B, AB)");
System.out.println("Enter rhFactor('+' or '-')");
BloodData bd= new
BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine());
BloodData bd1= new BloodData();
bd.display();
}
}
How can i use the constructor with 2 String parameters? because when I always run the code the first one only run. I'm only a beginner so hope someone could help because I already watched a lot of Youtube vids and I really didn't know why this happens
Java doesn't use named parameters like this for method or constructors. I would be surprised if a video showed such syntax...
new BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine())
You need to define String variables on the line above, then pass them into the constructor. You also shouldn't be combining instance constructors with static variables
class BloodData{
private String bloodType;
private String rhFactor;
public BloodData(String type, String rhFactor) {
this.bloodType = type;
this.rhFactor = rhFactor;
}
...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String x = in.nextLine();
String y = in.nextLine();
BloodData bd = new BloodData(x, y);
}
if you want to call a constructor having two parameters: Use this
BloodData blooddata = new BloodData("A","+");

Passing String from one class to another

How can I pass string variable or String object from one class to another?
I've 2 days on this problem.
One class get data from keyboard and second one should print it in console.
Take some help from the below code:-
public class ReadFrom {
private String stringToShow; // String in this class, which other class will read
public void setStringToShow(String stringToShow) {
this.stringToShow = stringToShow;
}
public String getStringToShow() {
return this.stringToShow;
}
}
class ReadIn {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // for taking Keyboard input
ReadFrom rf = new ReadFrom();
rf.setStringToShow(sc.nextLine()); // Setting in ReadFrom string
System.out.println(rf.getStringToShow()); // Reading in this class
}
}
There are two ways:
create an instance of your printer class and evoke the method on the printer object:
public class MyPrinter
{
public void printString( String string )
{
System.out.println( string );
}
}
in your main:
MyPrinter myPrinter = new MyPrinter();
myPrinter.printString( input );
or 2. you create a static method in your printer class and evoke it in your main:
public class MyPrinter
{
public static void printStringWithStaticMethod(String string)
{
System.out.println(string);
}
}
in your main:
MyPrinter.printStringWithStaticMethod( input );
Write a method inside your second class with System.out.println(parameter);
Make the method static and then invoke this in first method like
ClassName.methodName(parameter)
Inside class that accepts Scanner input
variableName ClassName = new Classname();
variablename.methodToPrintString(string);
A textbook can always help in this situation.

How to call a method with parameter from a diffrent class

Possible noob question but I cant get my method with parameters in one class to call in the other ?
FirstClass
public class Firstclass {
public static void main(String[] args) {
Test1 test = new Test1();
test.Passingvalue();
test.myMethod();
}
}
SecondClass
import java.util.Scanner;
public class Test1 {
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
String txtFile = Scan.next();
}
public void myMethod(String txtFile){
System.out.print("Scan this file" + txtFile);
}
}
You can provide the parameters as a comma separated list in the brackets after the method's name:
public static void main(String[] args) {
Test1 test = new Test1();
test.myMethod("my_file.txt");
}
Don't forget to add a parameter like this :
test.myMethod("txtFile");
declare your string txtfile as a public static variable outside the two methods (at the beginning of class test1) .
public class Firstclass {
public static void main(String[] args) {
Test1 test = new Test1();
test.Passingvalue();
test.myMethod();
}
}
import java.util.Scanner;
public class Test1 {
String txtFile;
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
txtFile = Scan.next();
}
public void myMethod(){
System.out.print("Scan this file" + txtFile);
}
}
I think you have a misconception here:
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
String txtFile = Scan.next(); //method scope only
}
Here the local variable txtFile only exists until the method Passingvalue (check naming conventions btw) is finished, i.e. it has method scope. Thus when calling myMethod(String txtFile) the parameter has the same name but is a different reference in a different scope.
So you'd either have to pass the file name to your method as the others already suggested or change the scope of txtFile, e.g. make it an instance variable:
public class Test1 {
private String txtFile; //the scope of this variable is the instance, i.e. it exists as long as the instance of Test1 exists.
public void Passingvalue (){
Scanner Scan = new Scanner(System.in);
System.out.println("File Name ? ");
txtFile = Scan.next();
}
public void myMethod(){
System.out.print("Scan this file" + txtFile);
}
}
Please note that this is just meant to illustrate the immediate problem. There are other issues, e.g. with the general design, which are not addressed. The purpose of your code seems to be learning anyways, so design is not that big an issue for now.
Just as a hint: I'd probably pass the name from outside the method or pass/read it in a constructor.
when you are calling a parameterize method you should have to pass a parameter to calling method other wise jvm will not understand to whom method you are calling becuase on the basis of parameters we can over load the methods .
so the final answer of your question is
public static void main(String[] args) {
Test1 test = new Test1();
test.myMethod("place your file name here");
}

How to access object fields in a loop?

I can access the planetName, but not the Surfacematerial,Diameter etc because they are not in the array and in the object. How do I access the objects in a loop and their respective fields?
import java.util.Scanner;
public class Planet {
private String[] planetName;
private String SurfaceMaterial;
private double daysToOrbit;
private double diameter;
public Planet(){
planetName=new String[8];
SurfaceMaterial="";
daysToOrbit=0;
diameter=0;
}
public Planet(String[] planetName, String SurfaceMaterial,double daysToOrbit, double diameter){
this.planetName=planetName;
this.SurfaceMaterial=SurfaceMaterial;
this.daysToOrbit=daysToOrbit;
this.diameter=diameter;
}
public void setPlanetName(){
Scanner in=new Scanner(System.in);
Planet solar[]=new Planet[8];
for(int i=0;i<solar.length;i++){
solar[i]=new Planet(planetName,SurfaceMaterial,daysToOrbit,diameter);
System.out.println("Enter Planet Name::");
planetName[i]=in.next();
System.out.println("Enter Surface Material");
SurfaceMaterial=in.next();
System.out.println("Enter Days to Orbit");
daysToOrbit=in.nextDouble();
System.out.println("Enter Diameter");
diameter=in.nextDouble();
}
for(int i=0;i<solar.length;i++){
System.out.println(planetName[i]);
System.out.println(this.SurfaceMaterial); //This returns only one value that has been entered at the last
}
}
}
public static void main(String[] args) {
Planet planet=new Planet();
Scanner input=new Scanner(System.in);
planet.setPlanetName();
}
}
just access like following
object[index].member ... // or call getter setter
in your case say the first member name is name .. so call like
staff[0].name // this will return BOB
The staff array is declared as local in the Constructor: Or if it is declared in the class context, you are hiding it. So declare the staff array in the class context and then initialize in the constructor:
class Test
{
public Full_time [] Staff;
public Test()
{
Staff = new Full_time [4];
Staff [0] = new Full_time("BoB", 2000, 70000);
Staff [1] = new Full_time("Joe", 1345, 50000);
Staff [2] = new Full_time("Fan", 3000, 80000);
}
}
And then, in the main function:
public static void main(String[] args) {
Tester t = new Tester();
t.staff[i].name = "A Name";
}
However, instead of accessing member field directly it is suggested to use getter or setter function like: getStaff(i) and similar.

How do I pass an array of strings into another method?

My code is like this:
public class Test() {
String [] ArrayA = new String [5]
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0])
}
}
I've tried various methods (No pun intended) but none worked. Thanks for any help I can get!
public class Test {
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
public Test(){ // Your Constructor
method1(arrayA[0]); // Calling the Method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, you can just call new Test();
OR if you want the method to be called from your main class by creating an instance of Test you may write:
public class Test {
public Test(){ // Your Constructor
// method1(arrayA[0]); // Calling the Method // Commenting the method
}
public void method1 (String yourString) { // Your Method
System.out.println(yourString);
}
}
In your main class, create an instance of test in your main class.
Test test = new Test();
String [] arrayA = new String [5]; // Your Array
arrayA[0] = "Testing";
test.method1(arrayA[0]); // Calling the method
And call your method.
EDIT:
Tip: There's a coding standard that says never start your method and variable in uppercase.
Also, declaring classes doesn't need ().
If we're talking about passing arrays around, why not be neat about it and use the varargs :) You can pass in a single String, multiple String's, or a String[].
// All 3 of the following work!
method1("myText");
method1("myText","more of my text?", "keep going!");
method1(ArrayA);
public void method1(String... myArray){
System.out.println("The first element is " + myArray[0]);
System.out.printl("The entire list of arguments is");
for (String s: myArray){
System.out.println(s);
}
}
try this
private void Test(){
String[] arrayTest = new String[4];
ArrayA(arrayTest[0]);
}
private void ArrayA(String a){
//do whatever with array here
}
Try this Snippet :-
public class Test {
void somemethod()
{
String [] ArrayA = new String [5] ;
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1 (String[] A) {
System.out.println("Here's where I need ArrayA[0]"+A[0]);
}
public static void main(String[] args) {
new Test().somemethod();
}
}
The Class name should never had Test()
I am not sure what you are trying to do. If it is java code(which it seems like) then it is syntactically wrong if you are not using anonymous classes.
If this is a constructor call then the code below:
public class Test1() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
public void Method1 () {
System.out.println(Here's where I need ArrayA[0]);
}
}
should be written as this:
public class Test{
public Test() {
String [] ArrayA = new String [5];
ArrayA[0] = "Testing";
Method1(ArrayA);
}
public void Method1(String[] ArrayA){
System.out.println("Here's where I need " + ArrayA[0]);
}
}

Categories