简体   繁体   中英

Converting Strings / ints into an Object Array

I have a question on how to convert a String or int or double value into an Object Array

Assume I am having two classes. One is student class and one is Database Class

Inside the Student class I have the following:

public class Student {
String name;
int grade;
double average;

}

Now in the Database class I am creating some new Students with the code:

Student studentOne = new Student();
System.out.print("Enter student 1's name: ");
studentOne.name = in.next();
Student [] students = new Student [5];

Now, if I create:

students[0] = studentOne.name; // It gives me the following error: "Type mismatch: cannot convert from String to Student"

Now I understand that I cannot convert a String to an Object, but after searching on google or here, I cannot find a method on how this should be done. Can you "cast" into an object? Or .toObject method? I am puzzled.

Thanks and best regards

Your array is of Student type and studentOne.name is of String type, and you cannot assign a String type value to your Student type array. Only Student type objects can be added in your student array.

students[0] = studentOne.name; is invalid.

Change it to

students[0] = studentOne;

Also you first need to instanciate each Student object before you can do anything with it.

Add students[0] = new Student(); before students[0] = studentOne;

Here is something you could do to have variable amount of students to add

public class Main {

    public static class Student {
        String name;
        int grade;
        double average;

        public Student()
        {
            name = "Nothing";
            grade = -1;
            average = 0.0;
        }

        public void PrintStudent()
        {
            System.out.println("[" + name + ", " + grade + ", " + average + "]");
        }

    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        Student [] students = null;
        System.out.print("Enter How Many Students to Create: ");
        String numberOfStudents = in.nextLine();

        if(numberOfStudents.matches("\\d+"))
        {
            students = new Student [Integer.parseInt(numberOfStudents)];
        }
        else 
        {
            System.err.println("Error when reading user input, exiting...");
            return;
        }

        CreateStudents(students, in);
        PrintStudents(students);


    }//main method

    public static void CreateStudents(Student[] allStudents, Scanner inputOrigin)
    {
        System.out.println("Enter Students as CSV(Comma Seperated Values).\nExample Given: Pete The Dragon, 11, 3.67");
        for(int studentIndex = 0; studentIndex < allStudents.length; studentIndex++)
        {
            System.out.println("Enter information for student #" + studentIndex + ": ");
            String[] input = inputOrigin.nextLine().split(",");
            try{
                //note how each index is a value of the student object in the input string array
                Student newStudent = new Student();
                newStudent.name = input[0];
                newStudent.grade = Integer.parseInt(input[1].replaceAll(" ", ""));
                newStudent.average = Double.parseDouble(input[2].replaceAll(" ", ""));
                allStudents[studentIndex] = newStudent;
            }
            catch(Exception ex)
            {
                System.err.println("Failed to create the " + studentIndex + " due to the following:" + ex.toString());
                allStudents[studentIndex] = new Student();
                    //or we can terminate 
                //return;
            }
        }
    }

    public static void PrintStudents(Student[] allStudents)
    {
        System.out.println("The students are as follows:");
        for(int index = 0; index < allStudents.length; index++)
        {
            System.out.print(index + ": ");
            if(allStudents[index] != null)
                allStudents[index].PrintStudent();
        }
    }
}

Here is the following output of a single run of the program where we add 5 students. Important to note that when I hit an exception while trying to create the Student, i will add a default Student object. If you wanted to you could discontinue adding students and simply exit. However it's nice to be able to continue to create students in case the user messes up.

Output

Enter How Many Students to Create: 5
Enter Students as CSV(Comma Seperated Values).
Example Given: Pete The Dragon, 11, 3.67
Enter information for student #0: 
ryan, 4, 3.33
Enter information for student #1: 
harambe the great, 12, 4.32
Enter information for student #2: 
some other person, 6, 2.45
Enter information for student #3: 
donald trump, 1, 0.35
Enter information for student #4: 
another person, incorrect vlaue example, 4.67
The students are as follows:Failed to create the 4 due to the following:java.lang.NumberFormatException: For input string: "incorrectvlaueexample"

0: [ryan, 4, 3.33]
1: [harambe the great, 12, 4.32]
2: [some other person, 6, 2.45]
3: [donald trump, 1, 0.35]
4: [Nothing, -1, 0.0]

You have an array of Student objects. So you can only assign a Student instance to one of its array slots. Student.name is a String . It seems logical to me that your intention here is to assign the whole Student object to your array, not just the name, anyway. Simply change:

students[0] = studentOne.name;

to

students[0] = studentOne;

This will correct your type mismatch error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM