How to use Data from an array in another class & method? - java

I've got a class named "User" which has a method that makes the User type his name. This name is saved in an array that is empty at first.
Question is, how can I use this "stored" name in another class (I want to show the name in this other class)
Here's what I've got (Sorry for the spanish lol)
public class Usuario {
private Scanner entrada = new Scanner(System.in);
private String Usuario[] = new String[20];
private int Posicion = 0;
private int punteo;
public void Datos() {
System.out.println("Ingresa tu nombre");
if(Usuario[Posicion] == null) {
this.Usuario[0] = entrada.nextLine();
Posicion++;
}
}
public String Usuario() {
return Usuario[Posicion-1];
}
And I want to use the name (Usuario[Posicion-1]) for example in a class like this:
public class Score extends Usuario {
Usuario usr = new Usuario();
String[] Name = new String[20];
public void Score () {
Name[0]=usr.Usuario();
System.out.println("------------Scores ------------------");
System.out.println(" Name "+ " Score");
for(int i=0;i<11;i++) {
System.out.println(i+".- " + " "+Name[0] +" 200 ");
}
}
}
But Everytime I try to retrieve this data in this class I get a "null" value or an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1" error, which makes me believe that I can't use the information from the array in another class :(
I'd appreciate any help. (also Sorry for the not-so-good english).

Each new version of a class or an object is not going to have the same values.
you will have to get the name from the object User.name then set it in your other object secondObject.name = User.name

Related

Access arraylist from another class inside main class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I don't have any idea on how to make this since i'm a new in java. I want to display all my objects in the arraylist of my TimeSlot class into the main class. I've tried few ways like using for (int = 0; i < bookingList.size(); i++) but still can't work. I'm getting nullPointerException so i dont know if there's other way to solve this. Please help.
TimeSlot.java
import java.util.ArrayList;
public class TimeSlot {
private String slotName;
private ArrayList<Booking> bookingList;
public TimeSlot(String sn) {
this.slotName = sn;
this.bookingList = new ArrayList<Booking>();
Booking booking1 = new Booking("CS1011", "A04", "Aiman");
Booking booking2 = new Booking("CS1012", "A13", "Nazim");
Booking booking3 = new Booking("CS1013", "A06", "Sarah");
Booking booking4 = new Booking("CS1014", "A21", "Majid");
bookingList.add(booking1);
bookingList.add(booking2);
bookingList.add(booking3);
bookingList.add(booking4);
}
public String getSlotName() {
return slotName;
}
public ArrayList<Booking> getBookingList() {
return bookingList;
}
public boolean isBooking (String bId, String cId, String sId) {
boolean isVerifyBooking = false;
for(Booking newBooking: bookingList){
if((newBooking.getBookingId().equals(bId)) && newBooking.getComputerId().equals(cId) && newBooking.getStudentId().equals(sId)) {
return true;
}
}
return isVerifyBooking;
}
}
Main.java
public static void main(String[] args) {
// TODO Auto-generated method stub
Faculty faculty = new Faculty("Computer Science and Technology", "");
Lab lab = new Lab("");
ArrayList<Computer> computerList = new ArrayList<Computer>();
ArrayList<Booking> isBookingList = new Booking(null, null, null).getBookingList();
if (option.equals("1")) {
System.out.println("\nChoose day: ");
String days = sc.next();
System.out.println("\nChoose date: ");
String date = sc.next();
boolean isValidDay = lab.verifyDate(days, date);
if (isValidDay) {
Day day = new Day(days, date);
System.out.println("\nBooking date: " + day.getDay() + " " + day.getDate());
System.out.println("\nPlease select a computer (A01 ~ A40): ");
String cId = sc.next();
System.out.println(isBookingList.size());
}
} else if (option.equals("2")) {
// I want to display it here
for (Booking booking: isBookingList) {
System.out.println(booking.getBookingList());
}
}
Replace the line
isBookingList = new Booking(null, null, null).getBookingList();
with
isBookingList = new TimeSlot("your sn").getBookingList();
Now try your for loop.
Instantiate your TimeSlot class. so you can get bookingList data.
TimeSlot timeSlot = new TimeSlot("yourSlotName");
You are creating object of Booking class with null values and trying to access the list
You should be creating TimeSlot object to access the initiated list
Create instance of TimeSlot class with parameter slot-name and then access the booking list.

I want to use a stringtokenizer to store strings into an object User array but get an error message

I am getting an error that says Exception in thread "main" java.lang.NullPointerException at Members. init (Members.java:23) at Main.main(Main.java:9)
And what I'm trying to do is to use StringTokenizer to store strings from a file input into and object array.
In main, line 9 just initiates the object and the code is: Members members = new Members("users.txt");
Line 23 is class Members is: users[nm].setId(st.nextToken());
I can't figure out what the error is.
import java.io.*;
import java.util.*;
public class Members {
int nm = 0; //Number of members
User [] users = new User[100]; //Assuming max
number of user is 100
StringTokenizer st;
Scanner s1;
File f1;
String var1; //this string determines if it a standard or admin user;
String var2;
public Members(String fn) throws FileNotFoundException {
f1 = new File(fn);
s1 = new Scanner(f1);
while(s1.hasNext()) {
//System.out.println("true");
st = new StringTokenizer(s1.nextLine(),"/");
while(st.hasMoreTokens())
{
//System.out.print(((String)st.nextToken()));
users[nm].setId(st.nextToken());
users[nm].setPw(st.nextToken());
var1 = st.nextToken();
users[nm].setFn(st.nextToken());
users[nm].setLn(st.nextToken());
users[nm].setEmail(st.nextToken());
//System.out.print(st.nextToken() + " ");
if(var1.equals("Admin")) {
users[nm].setAdmin(true);
((Admin)users[nm]).setRank(st.nextToken());
}
if(var1.equals("Standard")) {
users[nm].setStandard(true);
while(st.hasMoreTokens())
{
((Standard)users[nm]).addCar(st.nextToken());
}
}
}
nm++;
System.out.println();
}
s1.close();
System.out.println("Number of members: " + nm);
}
You're creating an array that can hold Users, but as far as I can tell you aren't creating any instances of User. When you first try to reference users[nm] its value is going to be null.
You could do something like this:
users[nm] = new User();
users[nm].setId(st.nextToken());
The main culprit is User [] users = new User[100]; //Assuming max
This is creating a array of size 100 only. Not Creating any object. You are setting Id to a null object. Before setting the Id you have to initialize your user object.

Variable not in scope (I think), but not sure how to fix it

What I am doing is just practicing for a test and I thought it was doing just fine, but I am getting, what I think is a scope problem. It says, "teams cannot be resolved to a variable type" and I've tried a few things I thought would fix it, but they didn't work. Here is the code:
import java.util.Scanner;
public class fundamentalsofgame {
public String hteam;
public String cteam;
public String teams(String hometeam, String compteam){
String hteam = hometeam;
String cteam = compteam;
return "The teams are " + hteam + " vs " + cteam;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String hometeam;
String awayteam = "New England Cheatriots";
hometeam = scanner.next();
teams team = new teams(hometeam, awayteam); //error
}
}
teams is a method and not your class name instead it is fundamentalsofgame. So you need to make object of fundamentalsofgame and call teams method on it. Change this:
teams team = new teams(hometeam, awayteam); //error
to
fundamentalsofgame obj = new fundamentalsofgame();
fundamentalsofgame.teams(hometeam, awayteam);

Is there way to keep queue data in memory in java GUI program

I'm writing a program to simulate a waiting queue for campus students this program users a linked list to do the queue and I used a button click event to execute the code.
It works only once every time add it only holds one student I think it because the list gets cleared after the button click event. I just want know is there a way to keep the list active till I terminate the main program.
My Code Below:
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
Queue stdQue = new LinkedList(); <-- Create the queue
String stName = addStdName.getText();
int sId;
int stdQuality;
if(!stName.isEmpty()){
// Generate a random number as Id
RanNum tempId = new RanNum();
sId = tempId.genNum();
// Generate a random number as a quality number to be matched later with the apartment
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
Object atTop = stdQue.element().toString();
if (!stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
if(!stdQue.isEmpty()){
for(Object name : stdQue){
lstQue.setText(name.toString());
}
}
}
The above code functions with out error I just want to find out to keep the queue live until the user terminate the main program.
I think this can be archived in a CLI program using a while loop but this is a GUI program I don;t know how to do that in a this format.
UPDATE
I made changes according to #learninloop when I do that I get an error "Cannot Find Symbol:method addStd1ActionPerformed(evt)". Also like to inform you that I'm using NetBeans 8.0.2 as my java IDE.
addStd1.setText("Add Student");
addStd1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {addStd1ActionPerformed(evt);}
And the changed main code is below:
class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
int sId;
int stdQuality;
RanNum tempId = new RanNum();
sId = tempId.genNum();
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
Object atTop = stdQue.element().toString();
if (!stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
if(!stdQue.isEmpty()){
for(Object name : stdQue){
lstQue.setText(name.toString());
}
}
}
}
UPDATE
I changed the code and put my linked list in to a class and moved it totally out of the button click event. So the new code as follows,
class stdQueCls{
Queue stdQue;
public stdQueCls(){
stdQue = new LinkedList();
if (!stdQue.isEmpty()){
for(Object all : stdQue){
lstQue.setText(all.toString());
}
}
}
}
public void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQueCls stdQue1 = new stdQueCls();
int sId;
int stdQuality;
RanNum tempId = new RanNum();
sId = tempId.genNum();
RanNum tempQuality = new RanNum();
stdQuality = tempQuality.genNum();
stdQue1.stdQue.add(sId);
stdQue1.stdQue.add(stdQuality);
stdQue1.stdQue.add(stName);
Object atTop = stdQue1.stdQue.element().toString();
if (!stdQue1.stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
}
Now as you see in my class I want to display what ever in the queue in a text area named queLst as you can see I have used a for loop to do it but my issue is it's not displaying the list in the text area and the other thing when it's placed inside the button click event it works but adds what ever I enter at that point can some show me a way or give an idea to how to archive this.
UPDATE
I did some changes to the above code now it working but I don't if I'm doing this wrong one things is when I retrieve the inserted data from the queue it not what I expect to see and I think still my queue linked list is not getting populated.
Can some one please have a look at my code and tell me what I'm doing is write or wrong.
class stdQueCls{
Queue<stdDetailGroup> stdQue;
public stdQueCls(){
stdQue = new LinkedList<stdDetailGroup>();
//lstQue.setText(stdQue.toString());
}
}
class stdDetailGroup{
String stdId;
String stQuality;
String stdName;
public stdDetailGroup(String a, String b, String c){
stdId = a;
stQuality = b;
stdName = c;
}
}
public void addStd1ActionPerformed(java.awt.event.ActionEvent evt) {
/*AddStdFrm newWindow = null;
newWindow = new AddStdFrm();
newWindow.setVisible(true);
this.setVisible(false);*/
String stName = addStdName.getText();
if(!stName.isEmpty()){
//StdDetails sTn = new StdDetails(sId, stName, stdQuality);
stdQueCls stdQue1 = new stdQueCls();
int stdQualityInt;
int sIdInt;
String sId;
String stdQuality;
RanNum tempId = new RanNum();
sIdInt = tempId.genNum();
sId = Integer.toString(sIdInt);
RanNum tempQuality = new RanNum();
stdQualityInt = tempQuality.genNum();
stdQuality = Integer.toString(stdQualityInt);
stdDetailGroup stdDetailsAdd = new stdDetailGroup(sId, stdQuality, stName);
stdQue1.stdQue.add(stdDetailsAdd);
Object atTop = stdQue1.stdQue.toString();
if (!stdQue1.stdQue.isEmpty()){
crntTop.setText("Current top of the list: " + atTop + " Student ID: " + sId);
addStdName.setText("");
}else{
crntTop.setText("Queue list is empty.");
}
}else{
crntTop.setText("Please, enter student name.");
}
}
private void shwQue1ActionPerformed(java.awt.event.ActionEvent evt) {
stdQueCls stdQue2 = new stdQueCls();
lstQue.setText(stdQue2.stdQue.toString());
}
As you are creating the linkedlist object stdQue inside the action performed event of button, the object is getting created and reinitialized every time the button is clicked. To make the data persistent, please take the object creation outside the button click event.
Assuming the class name as StudentManager, you can create the object inside the constructor:
class StudentManager {
Queue stdQue;
public StudentManager() {
stdQue = new LinkedList(); <-- Create the queue
}
private void addStd1ActionPerformed(java.awt.event.ActionEvent evt)
{
.
.
stdQue.add(sId);
stdQue.add(stdQuality);
stdQue.add(stName);
.
.
}
}

Why can't I call a private variable in main method?

this code is supposed to receive a full name string example "Billy Bob Smith" in an input dialog box and output the initials as a monogram example "BBS" in a message dialog box. but for some reason the main method won't let me acces the fullName variable.
import javax.swing.*;
public class HardMonogram {
//---------- ATTRIBUTES ----------//
private String fullName;
private String monogram;
private String first;
private String middle;
private String last;
//---------- METHODS ----------//
public String getInitial(String seperateName) {
return seperateName.substring(0, 1);
}
public void getSeperateName(String fullName) {
first = fullName.substring(0, fullName.indexOf(" "));
middle = fullName.substring(fullName.indexOf(" ") + 1, fullName.length());
last = middle.substring(middle.indexOf(" ") + 1, middle.length());
middle = middle.substring(0, middle.indexOf(" "));
}
public void setMonogram() {
monogram = getInitial(first) +
getInitial(middle) +
getInitial(last);
JOptionPane.showMessageDialog(null, monogram);
}
public static void main(String[] args) {
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
HardMonogram myMono = new HardMonogram();
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();
}
}
gives me this build error
/Users/aaron/School/Fall 2012/CSCI-C 201/Labs/LB08/HardMonogram.java:33: error: cannot find symbol
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
^
symbol: variable myMono
location: class HardMonogram
1 error
[Finished in 1.2s with exit code 1]
it's for my intro to java class but I don't know why I can't acces the variable. I'm obviously overlooking something. any ideas?
Update:
After another read of question, you just need to move first line in main method after instance creation.
HardMonogram myMono = new HardMonogram();
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();
Simply put myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name"); after object declaration (HardMonogram myMono = new HardMonogram();).
MyMono has not been declared in the first line of your main method. Add it to the beginning.
public static void main(String[] args) {
HardMonogram myMono = new HardMonogram();
myMono.fullName = JOptionPane.showInputDialog(null, "Type in you full name");
myMono.getSeperateName(myMono.fullName);
myMono.setMonogram();
}

Categories