How to access object fields in a loop? - java

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.

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","+");

Cannot make a static reference to the non-static field players

I'm making a program in java to register players and add them in an arraylist. My method for adding players is this:
void registerNewPlayer() {
System.out.print("Name?> ");
String name = input.nextLine();
System.out.print("Game?> ");
String game = input.nextLine();
System.out.print("Age?> ");
int age = input.nextInt();
Player player = new Player(name, game, age);
players.add(player);
}
my problem is that i don't know where to put
ArrayList<Player> players = new ArrayList<>();
if i have it in main, the method doesn't know what players is, but if i have it in the class i get a "Cannot make a static reference to the non-static field players" exception, when i try to print it from main. What's the best way of solving this.
Update: thanks for the help, i realized that since my command loop is already running on an instanced version of my class there is actually no problem, there was only a problem when i tried to test my method outside the instanced command loop.
If you'd like to have it at the class level, escape the static context.
public class YourClass {
ArrayList<Player> players = new ArrayList<>();
public static void main(String[] args) {
new YourClass(); // or YourClass yourClass = new YourClass();
}
// Create an instance of YourClass to leave the static context
public YourClass() {
registerNewPlayer();
}
public void registerNewPlayer() {
System.out.print("Name?> ");
String name = input.nextLine();
System.out.print("Game?> ");
String game = input.nextLine();
System.out.print("Age?> ");
int age = input.nextInt();
System.out.print("Weight?> ");
int weight = input.nextInt();
Player player = new Player(name, game, age, weight);
players.add(player);
}
}
I thinik this is the best solution for your problem. I hope it helps :)
Your Player class:
public class Player {
private static ArrayList<Player> _players = new ArrayList<Player>();
private String name;
private String game;
private int age;
private int weight;
public Player(String name, String game, int age, int weight){
this.name = name;
this.game = game;
this.age = age;
this.weight = weight;
}
public static void AddPlayer(Player player){
_players.add(player);
}
public static ArrayList<Player> getPlayers(){
return _players;
}
}
Now you can create some players and get them as follow:
... main ...
.
.
.
Player p1 = new Player("Name1", "Game1", 20, 70);
Player p2 = new Player("Name2", "Game2", 30, 80);
Player p3 = new Player("Name2", "Game3", 25, 73);
Player.AddPlayer(p1);
Player.AddPlayer(p2);
Player.AddPlayer(p3);
ArrayList<Player> allPlayers = Player.getPlayers();
.
.
.
Let me know if it is working for you !
The error you get is because you are trying to access a non-static variable (i.e. a value or object that exists only in instances of that class) from outside of such an instance. What you can do is to create an object of that class to be able to access the players through it:
public class Demo {
private List<Player> players = new ArrayList<>();
public static void main(String[] args) {
Demo demo = new Demo();
demo.registerNewPlayer();
System.out.println(demo.players);
}
private void registerNewPlayer() {
System.out.print("Name?> ");
String name = input.nextLine();
System.out.print("Game?> ");
String game = input.nextLine();
System.out.print("Age?> ");
int age = input.nextInt();
Player player = new Player(name, game, age);
players.add(player);
}
}
By creating an object of the class and executing the method as well as access the variable through it, allows you to do what you want (if I understood correctly that is).
Further reading material:
Java: when to use static methods
Type List vs type ArrayList in Java (you may have noticed that I changed the type of players to List<Player> from ArrayList<Player>)
What is the difference between public, protected, package-private and private in Java? (you may have noticed the private keyword on the list and the method)
Globally declare the list.
ArrayList<Player> players = new ArrayList<>();

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.

Is there a way to create an object with object name from the value of a string

class states{
List<String> cities = new ArrayList<String>();
public void add_city(String current_city){
this.cities.add(current_city);
}
}
class add_values{
public static void main(String [] args){
System.out.println("Enter the state name : ");
Scanner sc = new Scanner(System.in);
String user_state = sc.nextLine(); // need to create an object with the name from a string value
states user_state = new states();
....
....
}
}
Is there a way to create an object for a class with the name from a string.
If, user enters the state name as "Michigan", an object is created with "Michigan" which is got from scanner. and cities can be added for the state Michigan.
You will want to understand that objects have no names -- none, zero, zip. Yes, variables can have names, but that is not the same, since two or more variables can refer to the same object, and when that happens, which name is the name for the object? Again, neither/none since objects don't have names. As for variable names, they're way less important than you believe and almost don't exist in compiled code. What is most important are object references. Here an object can be associated with a String by means of a Map such as a HashMap<String, String> which is similar to an array or ArrayList that uses a String as its index rather than a number.
Now having said this, you can give your State class a String name field, and this may serve your purposes well.
i.e.,
import java.util.ArrayList;
import java.util.List;
public class State {
private String name;
private List<String> cities = new ArrayList<>();
public State(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addCity(String city) {
cities.add(city);
}
public List<String> getCities() {
return cities;
}
#Override
public String toString() {
return "State of " + name + ", Cities: " + cities;
}
}
Which can be run like:
public class StateTest {
public static void main(String[] args) {
State illinois = new State("Illinois");
illinois.addCity("Chicago");
illinois.addCity("Peoria");
illinois.addCity("Springfield");
System.out.println(illinois);
}
}
You can do something different using HashMap. Hope this will help to achieve your goal. Here is the code:
class States{
List<String> cities = new ArrayList<String>();
public void add_city(String current_city){
this.cities.add(current_city);
}
}
class add_values{
public static void main(String [] args){
HashMap<String, States> userStatesMap = new HashMap<String, States>();
System.out.println("Enter the state name : ");
Scanner sc = new Scanner(System.in);
String user_state = sc.nextLine(); // need to create an object with the name from a string value
userStatesMap.put(user_state, new states());
....
....
}
}

Connecting 2 classes

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.
}

Categories