Connecting 2 classes - java

I have a student object class and I have to create an arraylist of these students.
Im trying to create the program that inputs information into the student object then store it into an arraylist.
The first command to this array is to add a student object to the array the next command would be to remove a student from the array.
How would I get a user to input a command then go to another method that leads to storing information if everytime i try to complie i get static errors.
import java.util.Scanner;
import java.util.ArrayList;
public class CollegeTester
{
Scanner input = new Scanner(System.in);
ArrayList<Student> array = new ArrayList<Student>();
CollegeTester collegeTester = new CollegeTester();;
public static void main(String[] args)
{
new CollegeTester().getCommand();
}
public void getCommand()
{
System.out.println("Enter a command: ");
String command = input.nextLine();
if(command.equals("add"))
collegeTester.addCommand();
}
public void addCommand()
{
System.out.println("Enter a Name: ");
String name = input.nextLine();
}
}

There is another loophole. Your main method is not static. Your program will not run without it. Change it to
public static void main(String[] args)
{
}
Also then you cannot access non-static methods directly from static method.
Either you should instantiate class and then call methods or make methods static.
public static void main(String[] args){
CollegeTester collegeTester = new CollegeTester();
collegeTester.addCommand();
}
If you want to call specific method on specific options, then you should use switch case.

You are trying to access to not static method from static method. At first make an instance of CollegeTester class, than call it. For example:
import java.util.ArrayList;
import java.util.Scanner;
public class CollegeTester {
private Scanner input = new Scanner(System.in);
private ArrayList<Student> array = new ArrayList<Student>();
public static void main(String[] args) {
new CollegeTester().getCommand();
}
public void getCommand() {
System.out.println("Enter a command: ");
String command = input.nextLine();
if (command.equals("add"))
this.addCommand();
}
public void addCommand() {
System.out.println("Enter a Name: ");
String name = input.nextLine();
}
}
public class Student {
// Some properties and fty.
}

Related

Is there a way for me to assign variable numA inside a method defined by scanner class and use it in different methods?

import java.util.Scanner;
public class A {
static void aValue1(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of a: ");
double numA = scan.nextDouble();
static void aValue2(){
System.out.println(numA);}
public static void main(String[] args) {
aValue1();
aValue2();
}
}
I understand that numA is a local variable and can not be used again in a different method, but is there any way I declare numA as static outside of the method and still be able to get the user input for it?
I want the user to type what numA is and I want to use it in every method.
Yes you can, you could have numA as a static field
import java.util.Scanner;
public class A {
static double numA;
static void aValue1(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of a: ");
numA = scan.nextDouble();
static void aValue2(){
System.out.println(numA);}
public static void main(String[] args) {
aValue1();
aValue2();
}
}

Program won't run scanner cannot be resolved

This is the code I have so far and this is only one file of multiple ones that all belong to the same program.
As soon as I want to compile and check my errors eclipse tells me that it cannot resolve the scanner and I have no idea how to fix this problem nor what it exactly means.
import java.util.Scanner;
public class PieShop {
static FoodItem foodItem = new FoodItem();
public static void main(String[] args) {
Scanner_in.consoleLine("Enter Food item File name:");
foodItem.foodItemFile=new File(Scanner_in.getConsole());
foodItem.addFoodItem();
foodItem.displayAll();
foodItem.choices();
}
}
Below code should work fine provided that you pass right value to scanner source
import java.util.Scanner;
public class PieShop {
static FoodItem foodItem = new FoodItem();
public static void main(String[] args) {
Scanner Scanner_in = new Scanner(source);
Scanner_in.consoleLine("Enter Food item File name:");
foodItem.foodItemFile=new File(Scanner_in.getConsole());
foodItem.addFoodItem();
foodItem.displayAll();
foodItem.choices();
}
}
This would be the correct way if you wan to read the input from the console:
import java.util.Scanner;
public class PieShop {
private static FoodItem foodItem = new FoodItem();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Initialize scanner
System.out.println("Enter Food item File name:"); // Print yourtext
foodItem.foodItemFile = new File(scanner.nextLine()); // Read from scanner
foodItem.addFoodItem();
foodItem.displayAll();
foodItem.choices();
}
}

How can i access an object from another method in 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.

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.

Categories