(Java)할 수 있는 방법을 인쇄하는 개체의 정보를 때는 객체에 ArrayList? [중복]

0

질문

가 ArrayList 에서 주요하고 내가 있는 클래스를 생성자 그 안에 메서드를 인쇄하는 데이터입니다. 추가로 새로운 개체로,새로운 정보를 호출할 때,그리고 그것을 추가 ArrayList 에 그것을 유지합니다. 내가 무슨 힘든 시간이 구문을 인쇄하는 정보입니다. 나는 그것을 시도했으로 일반 편지를 사용하 ArrayList. 필요를 얻을 수 있 인덱스의 특정 개체에 인쇄하는 개체의 정보입니다. 예를 들어,아래 코드는 지난 몇 줄:

import java.util.ArrayList;
import java.util.Scanner;

public class student{

    String name;
    int age;
    int birthYear;

    public student(String name, int age, int birthYear){
        this.name = name;
        this.age = age;
        this.birthYear = birthYear;
    }
    
    public void printStudentInformation(){
        System.out.println(name);
        System.out.println(age);
        System.out.println(birthYear);
    }
}

public class Main{
    public static void main(String[] args){

        ArrayList listOfObj = new ArrayList();
        ArrayList names = new ArrayList();
        Scanner sc = new Scanner(System.in);

        for(int i = 0; i < 3; i++){

            System.out.println("New Student Information:"); // Three student's information will be saved
            String name = sc.nextLine();
            int age = sc.nextInt();
            int birthYear = sc.nextInt();

            student someStudent = new student(name, age, birthYear);
            listOfObj.add(someStudent);
            names.add(name);
        }

        System.out.println("What student's information do you wish to view?");
        for(int i = 0; i < names.size(); i++){
            System.out.println((i + 1) + ") " + names.get(i)); // Prints all students starting from 1
        }
        int chosenStudent = sc.nextInt(); // Choose a number that correlates to a student
        
        // Should print out chosen student's object information
        listOfObj.get(chosenStudent).printStudentInformation(); // This is incorrect, but I would think the syntax would be similar?
        
    }
}

어떤 도움 또는 설명이 크게 감사합니다.

arraylist java printing
2021-11-24 04:07:52
3
1

당신이 변화하는 필요의 정의 listOfObj from:

ArrayList listOfObj = new ArrayList();

하기:

ArrayList<student> listOfObj = new ArrayList<>();

첫 번째 것입니다 만들기 ArrayListObject 클래스 개체입니다.

두 번째 만들 것입니다 ArrayListstudent 클래스 개체입니다.

몇 가지 더 문제 코드:

  1. 기 때문에 당신은 독서를 사용하는 이름 nextLine해야 할 수 있습니 건너뛰고 새로운 라인을 읽은 후에는 출생해 다음과 같:
...
int birthYear = sc.nextInt();
sc.nextLine();  // Otherwise in the next loop iteration, it will skip reading input and throw some exception
...
  1. 당신은 옵션을 선택하는 학생을 위한 전시이지만,이 옵션은 1 인덱싱 ArrayList 점 0 색인,그래서 당신은 변화 라인 sc.nextInt() - 1:
int chosenStudent = sc.nextInt() - 1; // Choose a number that correlates to a student
  1. Scanner 을 던질 수 있습니다 예외를 입력할 경우,예를 들어,문자열을 대신 int. 도록 처리하고 있는지 확인하십시오 예외를 제대로 사용하는 try-catch 블록이 있습니다.
2021-11-24 04:26:42
1
  • 을 변경하십시오 해상력과 추가 toString()에학생 클래스입니다.
  • 고를 인쇄하는 모든 학생 개체 필를 사용하여 루 사용 한 sop.

EX:-

import java.util.*;

class Student {
    private String name;
    private int age;
    private int birthYear;

    public Student() {
        super();
    }

    public Student(String name, int age, int birthYear) {
        super();
        this.name = name;
        this.age = age;
        this.birthYear = birthYear;
    }

    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 int getBirthYear() {
        return birthYear;
    }

    public void setBirthYear(int birthYear) {
        this.birthYear = birthYear;
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", birthYear=" + birthYear + ", name=" + name + "]";
    }

}

public class DemoArrayList {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<Student>();

        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();

        for (int i = 0; i < n; i++) {
            scan.nextLine();
            String name = scan.nextLine();
            int age = scan.nextInt();
            int birthYear = scan.nextInt();
            list.add(new Student(name, age, birthYear));
        }

        System.out.println(list);
    }
}

O/P:-

2
joy 
10
2003
jay
20
2005
[Student [age=10, birthYear=2003, name=joy], Student [age=20, birthYear=2005, name=jay]]
2021-11-24 04:14:02

안녕하세요,편집할 수는 당신의 답변과 몇 가지를 추가 코드뿐만 아니라는 OP 더 잘 이해할 수?
kiner_shah

ok 그냥 기다려 어떤 시간
Batek'S

지금 보는 이 코드입니다.
Batek'S
0

할 수 있는 선언의 유형 ArrayList 면 초기화 listOfObjnamesArrayList.

여기에 올바른 방법을 선언하십시오:

ArrayList<type> list = new ArrayList();

와 다른 문제는 동안 당신은 가져 오기에서 데이터 ArrayList. 변수 chosenStudent 위치에서 사용자의 데이터 listOfObj 그러나 인덱스 시작 01.

예를 들어 입력 2 그런 다음,ArrayList 데이터를 얻을에서 두 번째 위치하지만 당신의 색인은 시작에서 1 는 동안 인쇄 데이터가 들어 있습니다. 이 있을 넣 chosenStudent - 1 에 대한 정확한 데이터를 얻을.

listOfObj.get(chosenStudent - 1).printStudentInformation() // chosenStudent = 2 - 1 = 1 

여기 아래로 내 코드:

ArrayList<student> listOfObj = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
Scanner sc = new Scanner(System.in);
    for(int i = 0; i < 3; i++){
        System.out.println("New Student Information:");
        String name = sc.next();
        int age = sc.nextInt();
        int birthYear = sc.nextInt();

        student someStudent = new student(name, age, birthYear);
        listOfObj.add(someStudent);
        names.add(name);
     }

     System.out.println("What student's information do you wish to view?");
     for(int i = 0; i < names.size(); i++){
        System.out.println((i + 1) + ") " + names.get(i));
     }
     int chosenStudent = sc.nextInt();
        
     listOfObj.get(chosenStudent - 1).printStudentInformation();
2021-11-24 04:41:01

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................