Need help making ArrayList - java

I am trying to create an ArrayList using at least six Person objects that will contain user inputted name and age resulting in information being printed out in alphabetical order.
Array list that contains person:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Categorization
{
public static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
System.out.println("Please enter a name " + name); // Can't return values
String nameEntry = input.toString();
System.out.println("Please enter an age " + age);
int ageEntry = input.nextInt();
}
}
I am unfamiliar with creating classes and feel like this is where most of my errors occur.
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
Tried to return name and age but they are not going back to the Public Class
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
}

You can try this:
public class Categorization {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
List<Person> people = new ArrayList<Person>();
for(int i=1; i<=6; i++) {
System.out.print("Please enter name for person " + i + " : ");
String nameEntry = input.next();
System.out.print("Please enter an age for person " + i + " : ");
int ageEntry = input.nextInt();
Person obj = new Person(nameEntry, ageEntry);
people.add(obj);
}
System.out.println("List of entries you entered: ");
for(Person obj: people) {
System.out.println("Name: " + obj.getName() + " " + "Age: " + obj.getAge());
}
}
}
Output:
You need to create a Person object using new keyword to store respective values and then finally add it to the people list.

Related

Print a specific cell from a string array

I've created a class that includes people data named "Datiutente" and an object based on that class named "du". Every person has a name and a surname (with the set/get methods).
I want to create a system that can provide the user information on a specific person based on the position which they are stored in the array.
I tried using a variable named vd to ask the user which person wanted to visualize based on the position that a person gained in the array (inserted in the for cycle), but when I try to print with vd it just prints "Name: null". Same if I change "vd" to "1". It always prints "Null".
(Yes, I tested this when I already inserted some data.)
Here's the full code:
package appartamento;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Appartamento {
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyb = new BufferedReader(input);
boolean attiva = true;
do {
System.out.println("what do you want to do?");
System.out.println("1 - check for a person");
System.out.println("2 - Add person");
int choice = Integer.parseInt(keyb.readLine());
Datiutente du[] = new Datiutente[10];
if (choice == 2){
System.out.println("How many people?");
int hm = Integer.parseInt(keyb.readLine());
for (int i=0;i<hm;i++){
du[i] = new Datiutente();
System.out.println("insert name:");
du[i].setName(keyb.readLine());
System.out.println("insert surname");
du[i].setSurname(keyb.readLine());
}
}
if (choice == 1){
System.out.println("which person are you searching?");
int vd = Integer.parseInt(keyb.readLine());
System.out.println("position: " + i);
System.out.println("Name: "+ du[i]);
System.out.println("Surname: " + du[i]);
}
} while (attiva = true);
}
}
and the class "Datiutente":
package appartamento;
public class Datiutente {
private String name;
private String surname;
private String codfis;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSurname(String surname){
this.surname = surname;
}
public String getSurname(){
return surname;
}
}
In every iteration you define the Datiutente du[] = new Datiutente[10];, so du is reset to {null,...,null} and the data saved in the previous iteration are replaced;
Try to define the array before the loop statement.
I found a way here:
You need to insert values on object creation, you can also use hashmaps
hashmap will benefit you more I think.
Code sample to fix your stuff.
class GFG {
public static void main(String args[]){
// Declaring an array of student
Student[] arr;
// Allocating memory for 2 objects
// of type student
arr = new Student[2];
// Initializing the first element
// of the array
arr[0] = new Student(1701289270, "Satyabrata");
// Initializing the second element
// of the array
arr[1] = new Student(1701289219, "Omm Prasad");
// Displaying the student data
System.out.println(
"Student data in student arr 0: ");
arr[0].display();
System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}
class Student {
public int id;
public String name;
// Student class constructor
Student(int id, String name)
{
this.id = id;
this.name = name;
}
// display() method to display
// the student data
public void display()
{
System.out.println("Student id is: " + id + " "
+ "and Student name is: "
+ name);
System.out.println();
}
}

Java how to get and show simple data

I need to get data and show it.
This is my question
Construct a class designed to perform that takes student record containing Roll Number, Name and Marks
as data and functions like get()and show() to take input in data and display data.
I am trying to do like this
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
public Student() {
this(" ", " ", 0);
}
public Student(String initName, String initId, int initScore) {
name = initName;
stu_id = initId;
score = initScore;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = Integer.parseInt(in.nextLine().trim());
System.out.println("Input Student Name, ID, Score:");
Student stu = new Student();
for (int i = 0; i < n; i ++) {
stu.name = in.next();
stu.stu_id = in.next();
stu.score = in.nextInt();
System.out.println(stu.name + " " + stu.stu_id);
}
System.out.println("name, ID of the highest score and the lowest score:");
System.out.println(stu.name + " " + stu.stu_id);
in.close();
}
}
But its wrong I just need to create a function show() on which ill get data and from get() function it will just print
It seems to me that this solution is acceptable, you will try to rewrite it later from memory, this is how I began to learn to program.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
public Student() {
this("None", "None", 0);
}
public Student(String initName, String initId, int initScore) {
name = initName;
stu_id = initId;
score = initScore;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", stu_id='" + stu_id + '\'' +
", score=" + score +
'}';
}
}
public class Main {
public static Student get(Scanner in) {
System.out.println("Input Student Name, ID, Score:");
String name = in.next();
int score = in.nextInt();
String stu_id = in.next();
return new Student(name, stu_id, score);
}
public static void show(Student student) {
System.out.println(student);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = Integer.parseInt(in.nextLine().trim());
List<Student> studentList = new ArrayList<>();
for (int i = 0; i < n; i ++) {
Student stu = get(in);
studentList.add(stu);
}
studentList.forEach(student -> {show(student);});
in.close();
}
}
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
Scanner in = new Scanner(System.in);
public void get()
{
System.out.println("Enter Student Name, ID, Score:");
name = in.nextLine();
stu_id = in.nextLine();
score = in.nextInt();
}
public void show()
{
System.out.println("Name: "+name+"\nId: "+stu_id+"\nScore: "+score);
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = in.nextInt();
in.nextLine();
Student[] stu = new Student[n];
for (int i = 0; i < n; i++) {
stu[i] = new Student();
stu[i].get();
}
for (int i = 0; i < n; i++) {
stu[i].show();
}
in.close();
}
}

Java - Enhanced for loop for ArrayList with custom object

Given this StudentList Class with ArrayList that takes Student Object with three fields: Roll number, Name and Marks, how to write enhanced For Loop instead of the regular For Loop method as written in the code below?
Student.java
public class Student {
private int rollNumber;
private String name;
private int marks;
public Student(int roll, String name, int marks){
this.rollNumber=roll;
this.name=name;
this.marks=marks;
}
public int getRollNumber(){
return this.rollNumber;
}
public String getName() {
return name;
}
public int getMarks() {
return marks;
}
}
Here is the SudentList Class with Main Method
StudentList.java
import java.util.ArrayList;
import java.util.List;
public class StudentList {
public static void main(String[] args) {
Student a = new Student(1, "Mark", 80);
Student b = new Student(2, "Kevin", 85);
Student c = new Student(3, "Richard", 90);
List<Student> studentList = new ArrayList<>();
studentList.add(a);
studentList.add(b);
studentList.add(c);
for (int i = 0; i < studentList.size(); i++) {
System.out.println("Roll number: " +
studentList.get(i).getRollNumber() +
", Name: " + studentList.get(i).getName() + ", Marks: " +
studentList.get(i).getMarks());
}
}
}
Instead of index, foreach gives you direct objects
for (Student st : studentList) {
System.out.println("Roll number: " + st.getRollNumber() + ", Name: " + st.getName() + ", Marks: " + st.getMarks());
}
So whenever you see list.get() replace it with direct object reference and you are done.

How do I create a class to sort a file in java

I have my program reading in the file(which contain first name and last names) from the user and printing it out. Now I need to write a method to sort the contents of the file by last name to call in the main. My question is where to begin. I started making my class for sortFile but am stuck on where to even begin.
package javaproject1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class JavaProject1 {
public static void main(String[] args) throws FileNotFoundException
{
String check = "y";
do{
Scanner fileRead = new Scanner(System.in);
System.out.println("Enter the name of the file: ");
File myFile = new File(fileRead.next());
Scanner scanTwo = new Scanner(myFile);
while(scanTwo.hasNext())
{
String i = scanTwo.next();
String j = scanTwo.next();
String sortLast;
System.out.println(i + " " + j + " ");
}
System.out.println();
Scanner anw = new Scanner(System.in);
System.out.println("Add another? y/n ");
check = anw.next();
}while(check.equals("y"));
}
public File sortFile(String sortLast)
{
}
}
Create a class Person implementing the Comparable interface:
public class Person implements Comparable<Person> {
protected String firstName;
protected String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
#Override
public int compareTo(Person o) {
return this.lastName.compareTo(o.lastName);
}
}
The class overrides the compareTo method, defining the sorting.
You can then store the file contents you read, in a SortedSet<Person> like TreeSet.
Assuming i is the first name and j is the last name, add the following two lines to your code:
String check = "y";
SortedSet<Person> persons = new TreeSet<>();
and
System.out.println(i + " " + j + " ");
persons.add(new Person(i, j));
persons will always contain the file contents you read so far, sorted by last name.
After the }while(check.equals("y")); you can then do a:
for (Person person : persons) {
System.out.println(person);
}

Callling method from another class + sorting

I am working on a program where I have to call a method that prompts the user to enter data from another class. This program should print the name, age, address, and gender of customers. However, I am having problem to call a method for inputting each customer information.
Also, I have to create a method that sort the ages of customers in ascending order. So the program prints out all info based on the order of age from the (youngest customer) to the (oldest one). I am not sure how to create a method that will only sort the ages of customers without sorting the name, address, and gender. I would really appreciate any feedback or comments!
This is what I have so far.
import java.util.Scanner;
public class Customer1 {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
int x;
System.out.print("Total number of customers: ");
x = input.nextInt();
Customer [] person = new Customer[x];
System.out.println("Name" + " " + "Age"+ " " + "Address" + " " + "Gender");
for(int i = 0; i < person.length; i++){
System.out.println(person.toString());
}
}
}
class Customer{
String name;
int age;
String address;
String gender;
public Customer(String newName, int newAge, String newAddress, String newGender){
name = newName;
age = newAge;
address = newAddress;
gender = newGender;
}
public void data(Customer [] person){
Scanner input = new Scanner(System.in);
for(int i = 0; i < person.length; i++){
System.out.print("Name: ");
name= input.toString();
System.out.print("Age: ");
age = input.nextInt();
System.out.print("Address: ");
address= input.toString();
System.out.print("Gender: ");
gender = input.toString();
}
}
/*This is the "uncompleted" method that I tried to create in order to sort the ages of customers.
But I don't know how to use it in order to sort only the ages*/
public void sort(Customer [] person){
double temp;
for(int a = 0; a < (person.length - 1); a++){
for( int b = (a + 1); b < person.length; b++){
if(person[a] > person[b]){
temp = person[a];
person[a] = person[b];
person[b] = temp;
}
}
}
}
public String toString(){
String result;
result = name + " " + age + " " + address + " " + gender;
return result;
}
}
I recommend you to rethink a little bit your code and take a look at the following tips
Using Comparator or Comparable interfaces
These interfaces helps you out with the sorting of your collections, lists and etc, i.e, the Comparator interface allows you to impose ordering to your collection with a hand from Collections.sort and Arrays.sort operations.
You must define the implementation of you Comparator, based on you target class(Person), then define the ordering by any field you want:
class PersonSort implements Comparator<Person>{
#Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}}
Then you are allowed to force its ordering via Arrays.sort(T[], Comparator):
Arrays.sort(yourArray, new PersonSort());
I also recommend you to take a look at Oracle's Collection Framework Tutorial. You will find information over ordering, implementations and etc.
Try out the below code which might solve this question .. I have included the methods suggested in the previous replies and created this program ..
import java.util.Scanner;
public class ReadSortCustomerData {
public static void main(String [] args) {
int numberOfCustomers;
Scanner input = new Scanner(System.in);
System.out.print("Enter the total number of customers: ");
numberOfCustomers = input.nextInt();
CustomerData [] customer = new CustomerData[numberOfCustomers];
for(int countCustomer=0 ; countCustomer < numberOfCustomers; countCustomer++) {
System.out.println("Enter the name of the"+(countCustomer+1)+"customer");
customer[countCustomer].setName(input.next());
System.out.println("Enter the age of the"+(countCustomer+1)+"customer");
customer[countCustomer].setAge(input.nextInt());
System.out.println("Enter the gender of the"+(countCustomer+1)+"customer");
customer[countCustomer].setGender(input.next());
System.out.println("Enter the address of the"+(countCustomer+1)+"customer");
customer[countCustomer].setGender(input.next());
}
}
public CustomerData[] sortCustomerData(CustomerData[] customers) {
for (int i=0;i<customers.length;i++) {
for(int j=i+1;j<customers.length;j++) {
if(ageCompare(customers[i], customers[j])==1) {
CustomerData tempCustomer = new CustomerData();
tempCustomer = customers[i];
customers[i] = customers[j];
customers[j] = tempCustomer;
}
}
}
return customers;
}
public int ageCompare(CustomerData a, CustomerData b)
{
return a.getAge() < b.getAge() ? -1 : a.getAge() == b.getAge() ? 0 : 1;
}
}
import java.util.Comparator;
import java.util.Scanner;
public class CustomerData {
private String name;
private int age;
private String address;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
This might need some tweaking during the run time but it should give you a good start.
1. Getting the data that you require
Currently in your Customer1 class you're accepting an x amount of customers provided from user input. Following which you create an array for x Customer objects. You do not currently populate the array with any data.
Customer[] person = new Customer[x];
After this line you could then do a for loop with the following:
String name;
int age;
String address;
String gender;
for( int i = 0; i < person.length; i++ )
{
System.out.print("Name: ");
name = input.next();
System.out.print("Age: ");
age = input.nextInt();
System.out.print("Address: ");
address= input.next();
System.out.print("Gender: ");
gender = input.next();
person[i] = new Customer( name, age, address, gender );
}
A cavaet must be observed in your code, you've put input.toString(). This will give you a string representation of your scanner, not the input. input.next() will give you next input as a string.
2.Sorting
I would advise looking at the comparator documentation. Have a comparator object that implements comparator with Customer as the type parameter. Override the compare to check against each Customer object's age.
Example would be:
class CustomerComparator implements Comparator<Customer>
{
#Override
public int compare(Customer a, Customer b)
{
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
}
You should look into making the variables name, age, address gender private and using getX() methods (getters/setters).

Categories