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.
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 11 months ago.
import java.util.*;
public class ReadFile {
public static class Em implements Comparable<Em> {
private int id;
private String name;
private double Salary;
public int getId() {
return id;
}
// same get methods for sal and name here
public Em(int id, String name, double e) {
this.id = id;
this.name = name;
this.sal = sal;
}
}
public static void main(String a[]) throws IOException {
String record;
List<Em> eL = new ArrayList<Em>();
BufferedReader be = new BufferedReader(new File("Location"));
List<String> arrList = new ArrayList<>();
try {
while ((record = br.readLine()) != null) {
String[] rows = record.spilt(",");
Em e = null;
int a = Integer.parseInt(rows[0]);
String b = rows[1];
double c = Double.parseDouble(rows[2]);
eL.add(new Em(a, b, c);
arlist.add(Arrays.toString(rows));
System.out.println(eL.toString);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Please Note:
Location of file is correct.
Any typo might be there.
The file contains data as follows:
1,Duke,13000
2,Jake,14000
...
OUTPUT:
[test.ReadFile$Em#7852e922]
[test.ReadFile$Em#7852e922,test.ReadFile$Em#4e25154f]
I need help
Am I doing it correctly
Any alternate program will help
Future:
I have to write emp details who has maximum salary into another file
Try overriding toString() method in Em class.
#Override
public String toString() {
return this.id + " " + this.name + " " + this.salary;
}
Your approach is good (if we forget the typos which, I assume, are not present in your code). The reason your program is outputting [test.ReadFile$Em#7852e922] [test.ReadFile$Em#7852e922,test.ReadFile$Em#4e25154f] is because of the way you are trying to print it. What you see is the memory adress of your ArrayList, not the content. To print the content of your ArrayList, you need to use a for loop that goes through the entire content of your ArrayList index by index and then prints its content. Here's a quick example:
for (int i = 0; i < eL.length(); i++) {
System.out.println(eL.get(i).getA)
System.out.println(eL.get(i).getB)
System.out.println(eL.get(i).getC)
}
This way of doing it gets the Em object for every index in the El ArrayList, and then prints its A, B and C value using a get command that you can easily add to your Em Class.
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 2 years ago.
Improve this question
I am making a simple java application that asks user for the subject they want tutors for, and then prints the tutors teaching that subject.
This is what I've written so far.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Tutor tutorOne = new Tutor("Anthony Joshua", "Mathematics", "31", "London, England");
Tutor tutorTwo = new Tutor("Andy Ruiz", "Physics", "31", "Mexico City, Mexico");
Tutor tutorThree = new Tutor("Vitali Klitschko", "Computer Science", "49", "Saint Petersberg, Russia");
Tutor tutorFour = new Tutor("Ray Leonard", "Mathematics", "64", "North Carolina, USA");
Tutor[] allTutors = {tutorOne, tutorTwo, tutorThree, tutorFour};
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the subject: ");
String tutorNeeded = userInput.nextLine();
if (tutorNeeded.contains("Math")) {
System.out.println(tutorOne.name+"\n"+tutorOne.subject+"\n"+tutorOne.age+"\n"+tutorOne.location);
}else if (tutorNeeded.contains("Physics")) {
System.out.println(tutorTwo.name+"\n"+tutorTwo.subject+"\n"+tutorTwo.age+"\n"+tutorTwo.location);
} else if (tutorNeeded.contains(("Computer"))) {
System.out.println(tutorThree.name+"\n"+tutorThree.subject+"\n"+tutorThree.age+"\n"+tutorThree.location);
} else {
System.out.println("Sorry, we don't have any tutors for that subject availible right now.");
}
}
static class Tutor {
String name;
String subject;
String age;
String location;
Tutor(String name, String subject, String age, String location) {
this.name = name;
this.subject = subject;
this.age = age;
this.location = location;
}
}
}
How would I make it so that when the user types "Maths", they get shown tutor 1 as well as tutor 4?
I could do this manually, but there has to be a better way.
You can iterate over all objects using either a normal for-Loop or a foreach-Loop in your main function, depending on you Java version:
for (int i = 0; i < allTutors.length; i++) {
Tutor t = allTutors[i];
if (t.subject.contains(tutorNeeded)) {
System.out.println(t.name + "\n" + t.subject + "\n" + t.age + "\n" + t.location);
}
}
Using the forEach-Loop:
for (Tutor t : allTutors) {
if (t.subject.contains(tutorNeeded)) {
System.out.println(t.name + "\n" + t.subject + "\n" + t.age + "\n" + t.location);
}
}
You can create a Map that holds key as user type and value as the tutor object. When user types a input just grab that using map.get(USERINPUT) it will return you the object.
You could iterate or stream the array of tutors, and filter accordingly. E.g.:
Arrays.stream(allTutors)
.filter(t -> t.subject.contains(tutorNeeded))
.forEach(System.out::println);
Note:
The System.out.println call at the end relies on the Tutor class overriding the toString() method, which you should probably do regardless.
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
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);
.
.
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I'm writing a program that takes in a string, a state name (for example New York), and outputs the corresponding abbreviation (e.g. NY). My program considers all 50 states, so my first thought was to use a boatload of if/else if statements, but now I'm thinking there's gotta be a better way...a faster way...without so much seemingly redundant code.
Snippet:
if (dirtyState.equalsIgnoreCase("New York")) {
cleanState = "NY";
} else if (dirtyState.equalsIgnoreCase("Maryland")) {
cleanState = "MD";
} else if (dirtyState.equalsIgnoreCase("District of Columbia")) {
cleanState = "DC";
} else if (dirtyState.equalsIgnoreCase("Virginia")) {
cleanState = "VA";
} else if (dirtyState.equalsIgnoreCase("Alabama")) {
cleanState = "AL";
} else if (dirtyState.equalsIgnoreCase("California")) {
cleanState = "CA";
} else if (dirtyState.equalsIgnoreCase("Kentuky")) {
cleanState = "KY";
// and on and on...
Is there an API that could make this process simpler? A shortcut perhaps?
Any feedback is greatly appreciated and thanks in advance =)
You could use a TreeMap which allows you to use a custom comparator that is case insensitive. It would look like this:
Map<String, String> states = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
states.put("New York", "NY");
states.put("Maryland", "MD");
//etc.
And to retrieve an abbreviation:
String abbreviation = states.get("new york");
System.out.println(abbreviation); //prints NY
If you're using Java 7 you can use strings in a switch statement, e.g.:
switch (dirtyState.toLowerCase())
{
case "new york": cleanState = "NY"; break;
case "maryland": cleanState = "MD"; break;
// so on...
}
It would be better to grab a city code list and put it in a properties file like:
New York=NY
Maryland=MD
District of Columbia=DC
Virginia=VA
Then load the content in a Properties and loop on its entries (it extends HashTable):
Properties cityCodes = new Properties()
citycodes.load(new FileInputStream(...));
for(Entry<String,String> entry : cityCodes.entrySet()){
if(dirtyState.equalsIgnoreCase(entry.getKey())){
cleanState = entry.getValue();
}
}
Here is a working example :
public static void main(String[] args) throws Exception{
Properties cityCodes = new Properties();
cityCodes.load(new FileInputStream("/path/to/directory/cityCodes.properties"));
System.out.print(getCode("Maryland",cityCodes));
}
public static String getCode(String name, Properties cityCodes){
for(Map.Entry<Object,Object> entry : cityCodes.entrySet()){
String cityName=(String)entry.getKey();
String cityCode=(String)entry.getValue();
if(name.equalsIgnoreCase(cityName)){
return cityCode;
}
}
return null;
}
Output:
MD
You could use an enum:
public enum State {
AL("Alabama"), CA("California"), NY("New York");
private State(String name) {
this.name = name;
}
private String name;
static String findByName(String name) {
for ( int i = 0; i != values().length; ++i ) {
if ( name.equalsIgnoreCase(values()[i].name))
return values()[i].toString();
}
throw new IllegalArgumentException();
}
}
public class StateTest {
public static void main(String[] args) {
String name = "New York";
System.out.println(name + ": " + State.findByName(name));
}
}