Why every elements of an array changes continuously in Java? - java

I wanted to create array of an objects. There will be many user objects and I want to keep these user objects in an array. I have a class called Data. I tried and searched a lot but couldn't find the solution. When user enters a new name the names of all objects changes with the given name, and at last when i print all the names it prints the last entered name for several times. Here is my code, it will be much helpful you to understand:
testClass.java
public class testClass {
public static void main(String[] args) {
mainScreen();
}
public static void mainScreen(){
Scanner scan = new Scanner(System.in);
System.out.println("1) Add a new user:");
int choice = scan.nextInt();
switch(choice){
case 1:
System.out.println("Enter name:");
String name = scan.next();
Data.users[Data.count] = new Data(name);
mainScreen();
break;
case 2:
for(int i =0; i<=Data.count; i++){
System.out.println(Data.users[i].name);
}
break;
}
}
}
Data.java
public class Data {
public static Data[] users = new Data[600];
public static String name;
public static int count = 0;
public Data(String name) {
users[count].name = name;
count++;
}
}
I want that every object will have unique name, id, phone number, etc.. Does anybody have a suggestion for me?

Because name is static field of your Data class like count and users.
Remove static modifier from name field.

One solution is to remove the static modifier from name field in Data:
public static Data[] users = new Data[600];
public static int count = 0;
public String name;
public Data(String name) {
this.name = name;
Data.count++;
}
Also modify your for loop, because you'll get a NullPointerException, remove equals from the condition:
for(int i =0; i<Data.count; i++){

First you need to correct your Object structure
you have defined a class Data which contains a static array of Data Class itself
I prefer to have data class as:
class Data {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
create a array of Data class in your testClass
create new Data Object for each input and assign the name to the newly created Object using setName
maintain the count variable in testClass. Increment it each time when you get a new input and use count variable to assign newly created Object to the Data array

Related

How to use setter to set a value to a attribute which is a private array?

I had made an array of roll number so how to give a user input using setter to the private attribute which is roll number.
I made an object of class Students which is a students and tried thisstudents.for(int i=0;i<n;i++)
{(setRollno[i](sc.next()))};
But it did not worked.
class Students{
private String[] rollno = new String[1000];
private int[] intel = new int[1000];
private int[] type = new int[1000];
private String[] name = new String[1000];
public void setRollno(String[] rollno) {
this.rollno = rollno;
}
public void setName(String[] name) {
this.name = name;
}
public void setIntel(int[] intel) {
this.intel = intel;
}
public void setType(int[] type) {
this.type = type;
}
public String[] getRollno() {
return rollno;
}
public String[] getName() {
return name;
}
public int[] getIntel() {
return intel;
}
public int[] getType() {
return type;
}
}
Possibly I'm misunderstanding the aim of your data structure, but it sounds like you're trying to create a collection of student data all in one place. If this is the case then I'd strongly recommend creating a Student class which represents just one student at a time, and then using one or more standard types from the Java Collection Framework to make it easy to find a particular student.
For example, your Student class could simply contain fields which hold the roll number, name, and other data for one student. Then, assuming that you'll want to find students quickly by roll number you could create a Map<String, Student> where the map keys are roll numbers and the corresponding map value is the student who has that roll number. Simply put a new Student object into the Map after constructing it. If you need to find students by name then you could create a Map<String, Collection<Student>> (because more than one student might have the same name) and put each new Student object into this name map after constructing it.
This is likely to lead to code which is a lot easier to read, maintain, and use than an all-in-one custom collection class such as the one shown in your question.
As a rough code example:
String rollNumber = getNewRollNumber(); // wherever roll numbers come from
String name = getStudentName(); // wherever the name comes from
Student newStudent = new Student(rollNumber, name, etc);
studentsByRollNumber.put(rollNumber, newStudent);
studentsByName.computeIfAbsent(name,
n -> new ArrayList<>(1)).add(student);
Student studentWithParticularRollNumber =
studentsByRollNumber.get("123456");
Collection<Student> studentsWithParticularName =
studentsByName.get("Perry, Fred");
The Map#computeIfAbsent method will create a new ArrayList under the given student name only if no entry already exists under that name, or will fetch the existing list if that name already exists in the map, and then will put the new student into the list.
Within the call to computeIfAbsent the lambda expression t -> new ArrayList<>(1) simply means "take the value of the map key, and whatever it is just create a new ArrayList of size one". It simply guarantees that if there is not already a Collection<Student> stored under the given student name then a new ArrayList<Student> will be created and stored there.
setRollno[i](sc.next()); isn't the good syntax. Your function setRollno take an array of strings as parameter, and change all the array you have. If that's what you want, you must pass an array of Strings as parameter:
If you want to set one specific String in your rollno, you must create another function:
setRollNoAtIndex(int i, String s) {
this.rollno[i] = s;
}
If you need to call this in a loop, you can then simply do:
for(int i=0; i < n ;i++) {
students.setRollNoAtIndex(i, sc.next());
}
As per Berger's comment:
The syntax you were trying to use was probably either:
for(int i=0; i < n ;i++) {
students.getRollno()[i] = sc.next();
}
or
String[] list = new String [1000];
for(int i=0; i < n ;i++) {
list[i] = sc.next();
}
students.setRollno(list);
I think that design of this class is not correct, because we have access to internal arrays directly. Moreover, in that case you do not have to init all these arrays on new instance creation. I offer a little bit another implementation of this class, that I found more suitable for this goal:
final class Students {
private static final int TOTAL = 1000;
private final Map<String, Student> students = new HashMap<>(TOTAL);
public void setName(String rollno, String name) {
getOrCreateStudent(rollno).name = name;
}
public void setIntel(String rollno, int intel) {
getOrCreateStudent(rollno).intel = intel;
}
public void setType(String rollno, int type) {
getOrCreateStudent(rollno).type = type;
}
public Set<String> getRollno() {
return students.keySet();
}
public String getName(String rollno) {
return students.getOrDefault(rollno, Student.NULL).name;
}
public int getIntel(String rollno) {
return students.getOrDefault(rollno, Student.NULL).intel;
}
public int getType(String rollno) {
return students.getOrDefault(rollno, Student.NULL).type;
}
private Student getOrCreateStudent(String rollno) {
Student student = students.get(rollno);
if (student == null)
students.put(rollno, student = new Student(rollno));
return student;
}
private static final class Student {
private static final Student NULL = new Student(null);
private final String rollno;
private int intel;
private int type;
private String name;
public Student(String rollno) {
this.rollno = rollno;
}
}
}

Generating tracking numbers for orders

I have this class which will be used from my main class and will be creating objects of class Sale:
import acm.program.*;
public class Sale {
int size = 0;
public int scode = 0 ; // sell code
public String cname ; // client name
public int cphone ; // client phone
public String sdate ; // selling date
public int cost ; // final cost
public int aItems[] // sold product
public Sale (Item aItems[],String cname, String cphone, String sdate) {
this.aItems = aItems ;
this.cname= cname;
this.sphone= sphone;
this.sdate= sdate;
}
public void setsItems(Items aItems) {
this.aItems= aItems;
}
public void setCname (String name) {
this.name= name;
}
public void setCphone(String cphone) {
this.cphone= cphone;
}
public void setSDate(String sdate) {
this.sdate= sdate;
}
The project says that in my main class I must have a way to review any sale made by entering the unique id number of the sale which will be created in this class. My problem is that I don't know how to set my class so that every time it's called from my main it will generate a new id number, starting from 1 and increasing by 1 every time.
Any ideas?
Use a static member variable to store the ID number of the last sale. A static member is a variable that is part of the class, not the object. This value can get incremented like you want.
Make a new method to access that variable that also increments the variable by one each time you generate a new ID.
In your main, call the Sale.generateNewID() method, then pass that new ID into the constructor of your Sale class.
public class Sale {
public static int idCount = 0;
public static int generateNewID() {
return ++idCount;
}
// this is a new member variable to store the id of the sale
private int id;
// note: added id parameter to constructor
public Sale (int theId, Item aItems[],String cname, String cphone, String sdate) {
this.id = theId;
// other constructor assignments that you had go here.
}
... // rest of your code
}

How to store String varables in an array from class to another in java

How can I explain this... well in my java program I have to classes one containing a dialog input and the other containing a string array.
In this program , when the user runs it , I would like the user to enter their name into the dialog input. when they enter their name i want it to be stored in a string array that is in another class and as soon as their name is stored in a variable i would like it to be printed in a console.. I hope this makes sense thank you.
Here is my work so far:
Class 1: getting the user's name
String name = JOptionPane.showInputDialog("Please Enter Your Name:")
{
// This is where i am a bit stuck as i don't how to send
// the name variable to class 2 and store it in an array
}
class 2: getting the name variable from class 1
String []names = new String[1];
public String getName()
{
return name; // not working as I am unable to retrieve the name variable
// from class 1
}
String []usernames {name};
System.out.println(usernames); //trying print out the name that is entered.
Thank you for your time
I don't understand what you try to do but this could be an answer.
public class Storage{
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
public class Main {
public static void main(String[] args){
Storage storage = new Storage();
String name = JOptionPane.showInputDialog("Please Enter Your Name:");
storage.setName(name);
[...]
storage.getName(); // Give you the name
}
}
But... why??

How to print a String defined in one class in a different class?

I have two classes. In the first one, I used the Scanner to retrieve the user's name and then store it in a String called name. Then say, I start a new class, and want to print that came out, how do I go about it. So I just wrote up this code as an example, so you can get an idea of what I'm trying to ask. I'll post both classes.
import java.util.Scanner;
public class One {
public static void main(String[] args) {
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two object = new Two();
}
}
}
Second class.
public class Two {
public Two() {
System.out.println("Ok "+One.name+", lets start!");
}
}
So, you will probably be doing something like this: -
class One
{
private String name = "bob";
public String getName()
{
return name;
}
public static void main(String [] args)
{
One one = new One();
Two two = new Two(one);
// You could also just pass an r-value to Two, as in, Two(new One()) if you
// never require 'one' again
}
}
class Two
{
public Two(One one)
{
System.out.println("Ok " + one.getName() + ", lets start!");
}
}
What is going on?
Creating two classes in your main entry point method.
Passing the instance of One to the constructor of Two
Two then calls getName()
You could, as others have suggested, pass a string as the constructor; alternatively, you could do both if required as Java supports overloading methods see
Recommendations
Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html for overriding methods so that you may see how to pass both a string and an object reference by value. What you are doing right now is passing the object reference of one by value. It may not be needed or you may want to provide restrictions using an interface, see http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Use the constructor to pass the values
public class Two {
private String value;
public Two(String a){
this.value=a;
System.out.println("Ok "+value+", lets start!");
}
//getter and setters
}
Then while creating the instance use that constructor
Two object = new Two(name);
pass your value to the Two class constructor.
if(start != null){
Two object = new Two(start );
}
and
public Two(String s){
System.out.println("Ok "+s+", lets start!");
}
To make your code compile, move the String name variable into a static field:
public class One {
public static String name;
public static void main(String[] args){
// Note: The "name" variable is no longer defined here
String start; // etc
// rest of code the same
}
}
I'm not going to tell you this is good code design, but it does what you asked.
You will also do like this
public class One {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
retrun this.name;
}
public static void main(String[] args){
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two two = new Two();
two.printName(this);
}
}
class Two{
public void printName(One one){
System.out.println("" + one.getName() );
}
}

Creating a simple stock inventory program - 2nd attempt

I have asked this question before and followed the feedback as best as I could but I am still having one problem with storing the info that the user enters into the array.
Here is the first attempt:
OOP Java: Creating a stock inventory program
So I need to have in total three classes(That's required). The Stock, stock inventory and then the user interface. The purpose of this program is to ask the user to input the company's name, stock rating, price and the number of shares. Of course, I then have to do other things. I think I am okay with the rest, the problem is the stockInterface, the last bit of code that I post below.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
public class StockInterface() {
private static StockInventory stockPortfolio;
public static void main (String [] args){
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
This piece of code doesn't work.
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares)
Can somebody please show me the proper way to store the info into the array? Thank you very much.
Lots of compile errors...
You have defined stockRating as a String but yet return it as an int:
public int getStockRating() {
return stockRating;
}
The same is true for price.
You have extra parenthesis here:
public class StockInterface() {
^
Also in StockInventory, there are multiple statements in the class block They belong in a method.
console is not instantiated.
stockPortfolio is assigned as an array entry, yet it is a single object, and assigned to the Stock which is not a matching type.
So you've declared the stockPortfolio as an instance of StockInventory. StockInventory is a class not an array, so you can't use stockPortfolio [0] = ... because stockPortfolio is an instance of the class. You have a private member in StockInventory that is an array of Stock class instances. What you need is an accessor method to be able to manipulate it. So change StockInventory as follows:
public class StockInvetory {
/*
All the code you have now ...
*/
public Stock [] getStocks(){
return stocks;
}
public setStocks(Stock [] value){
//maybe some checking here ...
stocks = value;
}
}
Now just a slight change in using the class. You need to use the accessor methods as follows:
public class StockInterface {
/*
What you have just the following line changes ...
*/
stockPortfolio.getStocks()[0] = new Stock(stockName, stockRatings, stockPrice, numberShares);
}
I am assuming you are happy with the way you are initializing the array and that you have decided arrays are better than more dynamic data structures in collections for your specific project. If this is not true have a look at Java Collections they may bring you more joy.

Categories

Resources