Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have figured out how to gather the data from the user to make a new student in my array, but I am having trouble adding that information to the array. Please show me how I can add this data as a new Student object in the given code. Please reference to the AddStudent method.
import java.util.Scanner;
public class ArrayDemo {
static Student[] students;
private static void ViewStudents() {
for (int i = 0; i < students.length; i++) {
System.out.println(i + ") " + students[i].getLName() + ", " + students[i].getFName());
}
}
private static void ViewDetails() {
Scanner kb = new Scanner(System.in);
int i;
System.out.println("Who would you like to view?");
ViewStudents();
i = Integer.parseInt(kb.nextLine());
System.out.println("ANum:\t\t" + students[i].getANum());
System.out.println("\nAddress:\t" + students[i].address.getHouseNum() + " " + students[i].address.getStreet());
System.out.println("\t\t" + students[i].address.getCity() + ", " + students[i].address.getState() + " " + students[i].address.getZip());
System.out.println("\t\t" + students[i].address.getLine2());
}
private static void AddStudent() {
Scanner kb = new Scanner(System.in);
Student student = new Student();
String FirstName;
String LastName;
int HouseNum;
String Street;
String City;
String State;
int Zip;
String Line2;
System.out.println("\tInput Information");
System.out.println("\tFirst Name:");
FirstName = kb.nextLine();
System.out.println("\tLast Name:");
LastName = kb.nextLine();
System.out.println("\tHouse Number:");
HouseNum = Integer.parseInt(kb.nextLine());
System.out.println("\tStreet:");
Street = kb.nextLine();
System.out.println("\tCity:");
City = kb.nextLine();
System.out.println("\tState:");
State = kb.nextLine();
System.out.println("\tZip Code:");
Zip = Integer.parseInt(kb.nextLine());
System.out.println("\tExtra Information:");
Line2 = kb.nextLine();
System.out.println("\nStudent:\t" + LastName + ", " + FirstName);
System.out.println("ANum:\t\t" + student.getANum());
System.out.println("Address:\t" + HouseNum + " " + Street);
System.out.println("\t\t" + City + ", " + State + " " + Zip);
System.out.println("\t\t" + Line2);
//students.setAddress( HouseNum, Street, City, State, Zip, Line2 );
System.out.println("\tYour Student was Successfully Added");
}
private static void RemoveStudent() {
Scanner kb = new Scanner(System.in);
System.out.println("Who would you like to remove?");
ViewStudents();
for (int j = Integer.parseInt(kb.nextLine()); j < students.length - 1; j++) {
students[j] = students[j + 1];
}
students[students.length - 1] = null;
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x = 40;
//students = new Student[0];
students = new Student[2];
students[0] = new Student("Thomas", "Emily");
students[1] = new Student("Bob", "Joe");
students[0].address = new Address(6614, "White Sands ln", "Hixson", "Tennessee", 37343, "");
students[1].address = new Address(66, "White ln", "Hson", "Tealamabaee", 373873, "");
do {
System.out.println();
System.out.println("Do you want to:");
System.out.println("\t0) View Students");
System.out.println("\t1) View Students' Details");
System.out.println("\t2) Add a Student");
System.out.println("\t3) Remove a Student");
System.out.println("\t4) Exit");
x = Integer.parseInt(kb.nextLine());
switch (x) {
case 0:
ViewStudents();
break;
case 1:
ViewDetails();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
break;
default:
}
} while (x != 4);
}
}
From what I can see, you are using the wrong kind of data structure. You seem to what to add a dynamic number of Students and an ArrayList would be a lot better and more appropriate than an Array. Then you can simply use the add method.
Remember, the size of an Array is immutable (it cannot change) so what you want in this case is definitely some sort of List, probably the ArrayList
If you insist on using an array, you would need to keep track of the number students already added and use that as an index (either as a global variable or pass it in as a parameter). But bear in mind that the nature of an Array means that you will hit a cap very quickly unless you set an very high capacity,
Believe me that there is no way you can add records to array without knowing how many records are there currently in your array. If you don't want another static variable to keep track number of records, you have to loop through the array till it is null.
static int numOfStudents = 0; //declare outside your main
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
if (numOfStudents < students.length){
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[numOfStudents] = stud;
numOfStudents ++;
}
}
An alternative solution which you would prefer. But this is bad in my opinion.
public static void AddStudent()
{
Scanner scn = new Scanner( System.in );
int index=0;
while(x<students.length && student[x] != null)
index++; //get position to add new student
System.out.println("Enter last name:");
String ln = scn.nextLine():
System.out.println("Enter first name:");
String fn = scn.nextLine():
Student stud = new Student(ln, fn);
students[index] = stud;
}
The easiest way without much change to your code would be to add a class variable called index next to the students array. This variable will keep track of the amount of students since arrays in Java have fixed length:
public class ArrayDemo
{
static Student[] students;
static int index = 0; // keeps track of the amount of students in the students array
// ... rest of your code
Then inside AddStudent() you add all the information you got from input to the current student at the index and update the index:
private static void AddStudent() {
// ... the code where you obtain user information
if(index < students.length) { // make sure there is room to add the user
Student student = new Student(/* add user information into the constructor */);
students[index] = student; // add the user at the index
index++; // update the index
} else {
System.err.println("No more room for students");
}
}
The code above assumes you have a constructor that accepts necessary user information.
Otherwise you can assign the information individually:
Student student = new Student();
student.firstName = firstName;
// ...
Or use setters like:
student.setFirstName(firstName);
If you do not with to use an index to keep track of amount of users and have a more dynamic way of storing the students, then I suggest using a List or some class that extends it such as an ArrayList
Your array has a fixed size of 2 elements. You could instead use a larger MAX value and (as the other answers have hinted) keep a variable that counts the actual number of array indices that are filled.
static int ARRAY_MAX = 10;
static Student[] students;
static int numStudents;
...
students = new Student[ARRAY_MAX];
numStudents = 0;
Adding a student would then look like...
students[numStudents] = new Student();
numStudents++;
...but its going to break when numStudents is greater than equal 10 (ArrayIndexOutOfBoundsException).
In this event you need to enlarge (resize) your array. In Java arrays have fixed size - resizing an array amounts to declaring a brand new array (with increased size), and then copying the old array into the new one. Use System.arraycopy to copy the contents from one array into the other.
You should really just use an ArrayList - behind the scenes this is what that object is doing.
Related
We are asked to write a code and enter name and age for 4 people. After that, we are required to find whether any of the age match each other. Later the question asks whether the names match, but I haven't gotten to that part just yet.
I tried making an array so that I can store the values of the inputted ages. I cannot figure out how I can compare age's values with other elements in the array.
package person;
public class Person
{
static int personAge;
String personName;
public void setName(String name) {
name=personName;
}
public String getName() {
return personName;
}
public void setAge(int age){
age=personAge;
}
public int getAge() {
return personAge;
}
}
package person;
import java.util.Scanner;
public class PersonMain extends Person
{
static int [] ageStore=new int [4];
public static void main(String[] args)
{
for(int i=1;i<5;i++)
{
Person person= new Person();
person.setName(person.personName);
System.out.println("Please enter name for person " + i );
Scanner input= new Scanner(System.in);
person.personName=input.next();
Scanner keyboard= new Scanner(System.in);
System.out.println("Now, input " + person.personName + "'s age" );
person.setAge(personAge);
personAge=keyboard.nextInt();
ageStore[i]=person.personAge;
System.out.println("Age is " + ageStore[i]);
}
//what can help me compare the values of int age in the array?
}
}
The end goal here is to print out the names of people that have the same age.
Of course they all have the same age: personAge is declared as static. Remove the static keyword in front of the declaration.
UPDATE: and yes, use getters and setters instead of accessing fields directly.
To summarise:
remove the static keyword in front of personAge declaration,
declare personAge and personName as private to ensure you use the getters and setters,
remove the extends Person in class PersonMain,
in method main, use the getters and the setters instead of accessing the fields directly.
UPDATE 2: Oh! yes! some more issues:
in the setters, assign the argument to the field, not the other way around (personName=name; and personAge=age).
variable i should go from 0 to 3 because the array is declared with a size of 4: for(int i=0;i<4;i++) or better: for(int i=0;i<ageStore.length;i++),
move the Scanner declaration and initialisation out of the loop, and use only one of them.
If you are collecting information that is required for later processing, you need to store all of that information.
At the moment, you are storing the ages in an array, but throwing away the names.
So, instead of keeping an age array like this:
static int [] ageStore=new int [4];
... try keeping an array of Persons. Plus you don't need to keep them outside the main method. So, in the main method:
Person[] persons = new Person[4];
Also, fix your Person class so that the age is not static and the variables are private:
private int personAge;
private String personName;
Now create a single scanner because you don't need one per loop or per input:
Scanner input= new Scanner(System.in);
Then create your loop, but run it from 0 to less than the length of the array to fill (because indexes in Java start at 0):
for (int i = 0; i < persons.length; i++) {
Then make a new Person object to populate:
Person person = new Person();
Then collect the name and age from the user (remembering that i is 1 less than what you want to show to the user):
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
And add the person to the array:
persons[i] = person;
Then you can close your loop.
So far you should have:
package person;
import java.util.Scanner;
public class PersonMain {
public static void main(String[] args) {
Person[] persons = new Person[4];
Scanner input= new Scanner(System.in);
for (int i = 0; i < persons.length; i++) {
Person person = new Person();
System.out.println("Please enter name for person " + (i + 1) );
person.setName(input.next());
System.out.println("Now, input " + person.getName() + "'s age" );
person.setAge(input.nextInt());
persons[i] = person;
}
// matching code will go here
}
}
Now we need to do the matching part.
One way of doing that is to check each item against all the items after it in the list. That would look like this:
for (int i = 0; i < persons.length - 1; i++) { // until 'persons.length - 1' because if we look at the last item, it has nothing left to compare against
Person currentPerson = persons[i];
for (int j = i + 1; j < persons.length; j++) { // start at the next index (i + 1)
if (currentPerson.getAge() == persons[j].getAge()) { // we have an age match
System.out.println(currentPerson.getName() + " has the same age as " + persons[j].getName());
}
}
}
I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information
Hi I'm very new to programming and I'm trying to write a programme in eclipse that does the following.
Create a Student class with 4 attributes: name, mark, course and phone number which are entered by the user.
Have a constructor which initialises those four attributes to the parameters passed in, and a display() method which displays the details of the Student.
Declares an empty array of 5 Student objects.
Create a Student object at the current position of the array using these variables.
Make a loop which calls the display() method of each Student in the array.
So far I've got the programme working to the point that it creates the array of 5 students and reads in the four different attributes from the user. But I can not figure out how to create a loop which calls the display method for each of the students.
This is my code so far..
import java.util.Scanner;
public class Student {
private String name, course;
private int mark, number;
public Student(String nameIn, String courseIn, int markIn, int numberIn)
{
this.name = nameIn;
this.course = courseIn;
this.mark = markIn;
this.number = numberIn;
}
public void display()
{
System.out.println("Name: " + this.name + " Course " + this.course + " mark: " + this.mark + " Number " + this.number);
}
public static void main (String[] args)
{
String[] Student = new String[5];
Scanner scanner = new Scanner(System.in);
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter course for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter number for student " + counter);
Student[counter] = scanner.nextLine();
}
for (int counter=0; counter< 5; counter++)
{
System.out.println(Student[counter].display());
}
}
}
PS sorry in advance if I have posted this question wrong. Its my first post and I couldn't find a similar question else where.
Thanks in advance.
Your current code doesn't create an array of Student, nor populate it correctly (each loop overwrites the former data) .
Also, the way you were calling display was wrong :
System.out.println(Student[counter].display());
First, you want to call display on an instance of Student, not on the class.
Second, you don't have to call System.out.println, because displayalready does this work (and calling System.out.println with the void parameter, because the display method returns nothing, will get you nowhere)
Try this way :
Student[] students = new Student[5];
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
String name = scanner.nextLine();
System.out.println("Enter course for student " + counter);
String course = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
String mark = scanner.nextLine();
System.out.println("Enter number for student " + counter);
String number = scanner.nextLine();
Student student = new Student(name, course, mark, number);
students[counter] = student;
}
for (int counter=0; counter< students.length; counter++)
{
students[counter].display();
}
My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}
The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.
you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];
I want to create an array from object then store in that array with 2 different type of date
i'm still learning java and this is kinda my task and i searched many times and have find nothing so please i need your help :D
the base class :
package com.matcho.task;
public class Subject {
String name;
Double grade;
public Subject(String myname, double myGrade) {
name = myname;
grade = myGrade;
}
public void printermethod() {
System.out.println("Your Subject is " + name + " and ur grade is "
+ grade);
}
}
and this is the main class :
package com.matcho.task;
import java.util.Scanner;
public class subjectUseing {
public static void main(String[] args) {
String studentName = "";
double studentGrade = 0;
Subject object1 = new Subject(studentName, studentGrade);
Scanner input = new Scanner(System.in);
System.out.print("Please, Enter the Size of the Array : ");
int arraySize = input.nextInt();
Subject[] gradeArray = new Subject[arraySize];
for (int i = 0; i < gradeArray.length; i += 2) {
if ((i + 1) % 2 == 0) {
System.out.println("Please, Enter Subject Number Grade");
studentGrade = input.nextDouble();
studentGrade = object1.grade;
gradeArray[i] = object1.grade;
//Error said (cannot convert from Double to Subject)
//object1.grade = (Double)gradeArray[i];
//gradeArray[i] = object1.grade;
continue;
} else {
System.out.println("Please, Enter Subject Number Name");
studentName = input.next();
studentName = object1.name;
//Error said (cannot convert from String to Subject)
gradeArray[i] = new Subject(object1.name, object1.grade);
// gradeArray[i] = object1.name;
// gradeArray[i] = new String(object1.name); // Failed T_T
}
}// For End
for (int i = 0; i < gradeArray.length; i += 2) {
System.out.println("Your Grade in each Subject is : "
+ gradeArray[i] + " " + gradeArray[i + 1]);
}// For End
}
}
i tried many ways and search many times but found nothing so please i need help because this error
[cannot convert from Double to Subject] blow up my mind :D
You basically need to simplify your loop: on each iteration of the loop, ask for both the subject name and the grade, then create one object to store them both:
for (int i = 0; i < gradeArray.length; i++) {
System.out.println("Please enter the subject name");
String name = input.next();
System.out.println("Please enter the subject grade");
double grade = input.nextDouble();
gradeArray[i] = new Subject(name, grade);
}
Note the declaration of the variables inside the loop - you don't need them outside the loop, so don't declare them there.
Then for display, you'd just use:
for (Subject grade : gradeArray) {
System.out.println(grade);
}
Again, there's no need to skip every other item in the array - each element in the array is a reference to a Subject object, which contains both a name and a grade.
(Or add getName and getGrade methods to Subject so that you can customize the output.)
Note that you may find Scanner a bit of a pain to work with - nextDouble() won't consume a line break, for example, which may mean you get an empty string when reading the next name. You might want to consider just reading a line at a time and using Double.parseDouble to parse a string. (Or use NumberFormat.)
By Definition
An array is a container object that holds a fixed number of values of a single type
You can not create an array then fill it with values of other types.
In your code you've created an array of Subject then all it's elements should be of type Subject , The members of Subject class doesn't matter at this point the array should handle Elements of type Subject.
In your logic "Business requirements " you're asked to create an array which holds the values of Student subject plus their Grades , then you say OK Easy task and you create the array and then you try to store grades and names of an object of Subject Class in the array Saying that
" Object is a reference type , and so as it's members " but NO!! it's not;
Your array should contains only Subject Elements
Take a look in the correct solution:
Scanner in = new Scanner(System.in);
System.out.println("Enter array size");
int size = in.nextInt();
Subject[] subjects = new Subject[size];
String name;
Double grade;
Subject object;
for(int i =0; i<size; i++)
{
System.out.println("Enter Subject name: ");
name=in.next();
System.out.println("Enter Subject Grade: ");
grade = in.nextDouble();
object = new Subject(name,grade);
subjects[i] = object;
}
for(int i=0; i<size; i++)
System.out.println("Subject name is "+subjects[i].name + " Grade is "+subjects[i].grade);
}
You created an array of Subject objects, but you are storing Double.
studentGrade = object1.grade;
gradeArray[i] = object1.grade;
You should store it like:
object1.grade = studentGrade;
gradeArray[i].grade = object1.grade;
But as already mentioned, you don't need so many local variables. You could dou it lik:
gradeArray[i].grade = input.nextDouble();