How to add an integer to my arraylist? - java

I currently have my code set up so a student's name and subject is added to my arraylist, and then printed when user is done. How ever as I'm not wanting to add a string now, I want to add a student number, i'm unfamiliar with how to go about this. I have tried replacing set with add, and string with int, but to no prevail.
Here is my main code
import java.util.*;
public class StudentData
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<Student>();
String yesNo = "true";
do
{
System.out.println("Enter student's name: ");
String name = in.next();
System.out.println("Enter student's subject: ");
String subject = in.next();
System.out.println("Enter student's number: ");
int number = in.nextInt();
Student s = new Student(name,subject,number);
s.setName(name);
s.setSubject(subject);
s.Number.add(number);
studentList.add(s);
do
{
System.out.println("Would you like to enter data for another student? Yes/No ");
yesNo = in.next();
}
while (!yesNo.equalsIgnoreCase("YES") && !yesNo.equalsIgnoreCase("NO"));
}
while (yesNo.equalsIgnoreCase("YES"));
for(int i = 0; i < studentList.size(); i++)
{
System.out.println(studentList.get(i).getName());
System.out.println(studentList.get(i).getSubject());
}
}
}
and
class Student
{
private String studentName;
private String studentSubject;
public Student(String name, String subject, int number )
{
setName(name);
setSubject(subject);
Number.add(number);
}
public String getName()
{
return studentName;
}
public void setName(String name)
{
studentName = name;
}
public String getSubject()
{
return studentSubject;
}
public void setSubject(String subject)
{
studentSubject = subject;
}
public int getNumber()
{
return studentNumber;
}
public void Number.add(int number)
{
studentNumber = number;
}
}

As you are storing Student objects in your list you are also storing the member variables of each object as you entered them. So no different approach needs to be taken to store an integer.
You can declare your private int studentNumber; in your student class, add a getter and a setter for it and then modify your constructor so that setStudentNumber(number); would work in the same way as setting your two Strings up.
Then to iterate through your list you could make use of the 'enhanced-for' syntax instead of a plain old for loop, meaning:
for (Student s : studentList) {
System.out.println(s.getName());
System.out.println(s.getSubject());
System.out.println(s.getStudentNumber());
}
Hope that this helps, if you need anything more just give me a shout below.

Related

java.lang.NullPointerException when I create an array that uses values of an other class

I have a class Student with 3 attributes,
public static class Student {
public String firstname;
public String lastname;
public int studentnumber;
}
that I want to initialize in an array in a suitable loop in an external class. The attributes of each student are to be initialized using user input (for that I have a Terminal class):
public class main {
public static void main(String[] args) {
int numberofstudents = Terminal.askInt("How many students to you want to enter? ");
Student[] array = new Student[numberofstudents];
for (int i = 0; i < numberofstudents; i++) {
array[i].firstname = Terminal.askString("Enter student's firstname ");
array[i].lastname = Terminal.askString("Enter student's lastname ");
array[i].studentnumbere = Terminal.askString("Enter student's number ");
}
}
}
But every time I initialize a value of the Array,
array[i].firstname = Terminal.askString("Student's firstname ");
I get the
Exception in thread "main" java.lang.NullPointerException
You need to initialize the array index with a new Student() before you can update the value at this array index. By default, Student[] contains null at each index and therefore you will get NullPointerException if you try to perform any operation (e.g. assigning a value to array[i].firstname) on it without initializing it will a non-null value.
for(int i = 0;i<numberofstudents;i++){
array[i] = new Student();
array[i].firstname = Terminal.askString("Enter student's firstname ");
array[i].lastname = Terminal.askString("Enter student's lastname ");
array[i].studentnumbere = Terminal.askString("Enter student's number ");
}
Your Student array is empty! It has a length of your input, but has no student objects in it.
Create a new Student, and add it to the list first!
for(int i = 0;i<numberofstudents;i++) {
array[i] = new Student();
array[i].firstname = Terminal.askString("Enter student's firstname ");
// ...
}
You need to initialize each items of an array with new Student();
It's better to have a normal Student class (NOT static one). It seems that you want to hold total student count number so you can only have that variable as a static attribute (private static int studentNumber), and whenever you create a new instance of Student just ++ the value of studentNumber. In this case you don't need to get students number each time.
And it's better to have private attributes and access them via getters and setters rather than public attributes.
public class Student {
private static int studentNumber = 0;
private String firstName;
private String lastName;
private Long studentId;
public Student(String firstName, String lastName, Long studentId) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
studentNumber++; // increase students count after each initialization
}
public static int getStudentNumber() {
return studentNumber;
}
public static void setStudentNumber(int studentNumber) {
Student.studentNumber = studentNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
}
In your Main class, you need to initialize each items of an array with new Student();
public class Main {
public static void main(String[] args) {
int numberOfStudents = Terminal.askInt("How many students to you want to enter? ");
// this line just create an empty array that can hold Student objcets in it
Student[] array = new Student[numberOfStudents];
for (int i = 0; i < array.length; i++) {
// you need to initialize each items of an array with new()
array[i] = new Student(Terminal.askString("Enter student's firstname "),
Terminal.askString("Enter student's lastname "),
Terminal.askString("Enter student's ID "));
}
}
}
Don't forget to follow indentation rules, and start all classes name with Uppercase (Main, Student, Terminal, etc.). Finally use camel-case (studentNumbers, firstName, lastName).
You can add a constructor with three fields to the Student class and simplify your code as follows:
public static class Student {
public String firstname;
public String lastname;
public int studentNumber;
public Student(String firstname, String lastname, int studentNumber) {
this.firstname = firstname;
this.lastname = lastname;
this.studentNumber = studentNumber;
}
}
public static void main(String[] args) {
int numberOfStudents =
Terminal.askInt("How many students to you want to enter? ");
Student[] array = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
array[i] = new Student(
Terminal.askString("Enter student's firstname "),
Terminal.askString("Enter student's lastname "),
Terminal.askString("Enter student's number "));
}
}

adding multiple objects to ArrayList is not printing very well

import java.util.ArrayList;
import java.util.Scanner;
public class Student {
static String studentNum;
static int age;
static String Name;
Student(int Age, String Name){
this.Name = Name;
this.age = Age;
}
public static String input_read() {
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
studentNum = sc.next();
} else {
sc.close();
}
return studentNum;
}
public static int setAge() {
System.out.println("Enter the age of the Student");
return Integer.valueOf(input_read());
}
public static String setName() {
System.out.println("Enter the name of the Student");
return input_read();
}
public static int getAge() {
return age;
}
public static String getName() {
return Name;
}
public static void main(String[] args) {
ArrayList<Student> ar = new ArrayList();
for (int i=0; i<2; i++) {
Student s1= new Student(setAge(), setName());
ar.add(s1);
}
for (Student each :ar){
System.out.println(each.getName());
System.out.println(each.getAge());
}
}
}
I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?
You should remove the keyword static from your member variables.
That is causing them to be shared across all instances.
See here: What does the 'static' keyword do in a class?

How do i take user input and store it successfully in an ArrayList? Then how do i get my program to show me all the elements in the ArrayList?

I want a program that stores details about staff in an arraylist. I'd like to prompt user for input and store each result in the arraylist. How do I do this? And how do i view everything stored in the arraylist after?
It doesn't need to reflect the code I have, just can't seem to figure out how i have a class with setters and getters and then create a new main class promting user for input and store that input in the arraylist.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class salesPersonMain {
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
//ask user for input and get input
System.out.println("Enter id: ");
int id = Integer.parseInt(input.nextLine());
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
List<salesPerson> sPerson = new ArrayList<salesPerson>();
sPerson.add(new salesPerson(id, firstName, lastName));
}
}
I have another class for the salesperson:
import java.util.ArrayList;
public class salesPerson<sPerson> {
//create variables for sales person
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName)throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.lastName = lastName;
}
}
//creates array of salespeople
private ArrayList<sPerson> salesPerson;
public salesPerson() {
salesPerson = new ArrayList<>();
}
//adds new salesperson to the array
public void add(salesPerson sPerson) {
salesPerson.add((sPerson) sPerson);
}
You'll need a loop to repeatedly get the input:
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
List<salesPerson> sPerson = new ArrayList<salesPerson>();
// Loop forever
// Need a way to break the loop. One option: have the user
// input "q" for quit
while (true) {
//ask user for input and get input
System.out.println("Enter id ('q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
// This should be in try/catch in case parseInt fails
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
sPerson.add(new salesPerson(id, firstName, lastName));
}
// Print the list
sPerson.forEach(System.out::println);
}
So it prints out properly, you need to override the toString function in the salesPerson class:
public class salesPerson {
// Other code here.....
#Override
public String toString() {
return id + "," + firstName + " " + lastName;
}
}

Java calling value from a method

first of all sorry for my english it is not perfect.
I got a little problem (for me a huge problem) in java.
package test;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void output (String adress, String city, int postcode) {
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
int [] c = new int [b];
for (int i=0; i<c.length; i++) {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadresse(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
this.adress = adress;
this.city = city;
this.postcode = postcode;
System.out.println("Adress: "+adress+"City"+city+"postcode"+postcode);
}
}
}
Now, i want to save the values in a new class in a array
package test;
public class save {
adress [] saver = new adress[10];
public adressenpool (String adress, String city, int postcode){
for(int i =0; i<10;i++)
saver[i] = ????? ; //i have tried several things here, but it will not work. i know it is just a little problem but i can't get it the mistake
}
}
}
How can i get the values from address class an copy it as an array in the saver class?
It looks like you are attempting to put 10 objects of class address in an object of class save, as opposed to just the information within address. This is generally a good idea so I encourage you to continue.
In order to create the address within method adressenpool you need to use its constructor. At present class address only had a default constructor, which creates an effectively empty address. I would add a new constructor that fully creates the object
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public adress(String adress, String city, int postcode, String ergebnis){
this.adress=address;
this.city=city;
this.postcode=postcode;
this.ergebnis=ergebnis;
}
//you can have several constructors so you can keep the empty constructor if you want to set the elements piece by piece
public adress(){
}
......
other methods as before
}
Having added the constructor you can now make addresses easily
public adressenpool (String adress, String city, int postcode,String ergebnis){
saver[0] = new adress(adress, city, postcode,ergebnis);
}
However, your method adressenpool only contains enough information to create 1 adress. You may wish to set which index to save it at. Or you may want to change from an array to an arraylist so you can just add new adress as you go.
public adressenpool (String adress, String city, int postcode,String ergebnis, int index){
saver[index] = new adress(adress, city, postcode,ergebnis);
}
Notes
Classes always start with an uppercase letter. Objects with
lowercase. So it should be class Save and class Address
For loops (and if statements) without braces are considered a dangerous thing to do. Always include {} with your loops even if it contains a single statement. So
for(int i =0; i<10;i++){
saver[i] new Adress(adress, city, postcode,ergebnis);
}
I think you should be more specific of what you want to do exactly.
Your first class has 4 members (3 String and 1 int) and you want to save the values from address class as an array in the saver class? What do you mean by the last one?
I am guessing you need to fill each address instance in the array you define (saver) by calling the appropriate setters. (You haven't defined setadresse() by the way). This can be done in a loop for example.
Also this is not very straight forward: //i have tried several things here, but it will not work. What have you tried and did not work?
Of course you need a main() function also to run your program.
I hope that helped a bit...
This will solve the issue
package temp;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void setAddress () {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadress(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Adress: "+adress+"City"+city+"postcode"+postcode;
}
}
And the second class
package temp;
import java.util.Scanner;
public class save {
adress [] saver;
public save(){
saver = new adress[10];
}
public void adressenpool(){
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
adress address1 = null;
for (int i=0; i<b; i++) {
address1 = new adress();
address1.setAddress();
this.saver[i] = address1;
}
}
public static void main(String[] args) {
save saveTemp = new save();
saveTemp.adressenpool();
for(int i=0; i<2; i++){
System.out.println(saveTemp.saver[i].toString());
}
}
}

Using multiple classes java

I would like to know how to use multiples clas in Java. I know how use method from other class and also constructors but i would like know how create a new "object" for example. If i am making a PersonDirectory, then i can have class called Person which has the attributes Name and Age. Then i want to make a Person[] in my PersonDirectory Class and add names and ages to it. How can i do that? I have some code that i did, but it doesn't seem to work out.
import java.io.*;
public class PersonDirectory {
static BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
static Person[] personArray = new Person[2];
public static void main(String[] args) throws IOException{
for (int i = 0; i < personArray.length; i++) {
System.out.print("Please enter the name of the person: ");
String name = br.readLine();
System.out.print("Please enter the age of the person: ");
int age = Integer.parseInt(br.readLine());
personArray[i] = new Person(name,age);
}
for(Person p : personArray) {
System.out.println("The name is "+p.getName()+" and the age is "+p.getAge());
}
}
}
second class
public class Person {
private static String name = "";
private static int age = 0;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public static String getName() {
return name;
}
public static int getAge() {
return age;
}
}
This is because the properties in the Person class are static. Static means that they are shared between all object(instances). Remove the static keyword from the Person class and you will be fine.

Categories

Resources