I got from my teacher the next assignment -
I need to build a Course class and Student class
and to insert every Student into the Course class
Each Student has an Id,name and grade.
I have tried the next code:
public class Course {
Student[] android = new Student[100];
private void addStudent(Student a) {
for (int i=0;i<android.length;i++) {
if (android[i] == null) {
android[i] = a;
break;
}
}
}
public static void main(String[] args) {
addStudent(Joe);
}
}
I need to insert a Student that i have created in the Students class to the first null position in the array.
When i try addStudent(Joe); it gives me an error : "Joe cannot be resolved to a variable"
The Student class code:
public class Student {
private float grade;
private String name;
private long id;
public Student(long c,String b,float a) {
grade = a;
name = b;
id = c;
}
public static void main(String[] args) {
Student Joe = new Student(1,"Joe",40);
}
**The array holds 100 students (null at start)
When adding a student - i need to check for the first null value in the array and put it
there
When printing the students: i need to print only the non-null Objects in the array**
This code
Array[] Android = new Array[100];
is creating an array of type Array, so you can only store Array objects in it.
If you want to store Students, you need to create an array that, instead:
Student[] android = new Student[100];
Also, you need to realize that arrays in Java are indexed from 0. That is, you cannot reference a position that is the same as the size of the array. In your case, you have made
an array with 100 elements, but your for-loop is trying to put 101 objects in it.
Furthermore, your question text implies you only want to insert the new Student object once, but your loop puts it into every empty location in your array.
Try this instead:
for (int i=0;i<android.length;i++) { // < instead of <=, don't hardcode the length
if (android[i] == null) {
android[i] = a;
break; // once we insert a, stop looping
}
}
Update
The reason that the compiler can't find Joe is an issue of scope. You have declared Joe as a local variable in the main() method in the Student class. If you want the compiler to be able to see it, you need to declare it in the same method you are using it:
public static void main(String[] args) {
Student Joe = new Student(1,"Joe",40);
addStudent(Joe);
}
A quick google search of "Java variable scope tutorial" should give you plenty of reading about how and when you can use local and member variables.
insert method of student S (1111,"ahmed",3.5)in the position "p" in array of students(id,name,GBG)array size 100 and curent size =3.
-remove method that remove the student having GBG =2.5from the array of student .array size 100 and currentsize=3
First, change the
Array[] Android = new Array[100];
to
Student[] listOfStudent = new Student[100];
What this does is creates a array of size 100, and the type of the array is Students, which is what you will be inserting into the array. You are also going to have to change
for (int i=0;i<=100;i++) {
if (Android[i] == null) {
Android[i] = a;
}
}
to
for(int i=0; i < listOfStudents.length; i++){
if(listOfStudents[i] == null){
listOfStudent[i] = a;
}
}
otherwise you will get a "List Out of Bounds" error. It is better to not hard code values into your code - good practice for the future!
Good Luck!
Related
I have the class Student with a constructor that sets the values int s_code, String name and int age.
When I create an object of the class Student I pass it into an ArrayList AllStudents.
My problem is that I want the user to enter an Id and check if there is that Id in the ArrayList. If its not let him add a new student else tell him to try again.
I tried to loop through the ArrayList with for and inside of it
I have an if statement with .contains and if it is true I have a simple println("Good") just to test it.
When I run my program though it skips it.
Here is my code:
static ArrayList<Student> AllStudents = new ArrayList<Student>();
static void InitStudents() //this is a method that creates some students when I call it in main.
{
AllStudents.add(new Student(1,"James",15));
AllStudents.add(new Student(2,"John",16));
AllStudents.add(new Student(3,"Rose",15));
}
System.out.println("Enter the ID of the student you want to add.");
Scanner get_new_code = new Scanner(System.in);
int s_code = get_new_code.nextInt();
for(Student code : AllStudents)
{
if (AllStudents.contains(s_code)) //I think that I have to include age and name for it to work.
{
System.out.println("Good");
}
}
By the way sorry if I didn't explain something or I did something completely wrong I'm new to Java.
That advanced loop is not helping you in the way you implemented it.
for(Student code : AllStudents){ //"code" is one element out of the list
if (AllStudents.contains(s_code)){ //here you are checking the whole list
System.out.println("Good");
}
}
This might be what you are looking for:
for(Student code : AllStudents){
if(code.getSCode() == s_code){ //here the one element named "code",
//out of the list, will be checked
System.out.println("Good");
}
}
A getter method (this one is called for example getSCode()) will help you here, to ask for every attribute of a student object. It will return the s_code of the object you are looking at.
EDIT AS EXAMPLE:
public class Student{
int s_code;
String name;
int age;
public Student(int code, String name, int age){
this.s_code = code;
this.name = name;
this.age = age;
}
public int getSCode(){
return s_code;
}
public int setSCode(int newSCode){
this.s_code = newSCode;
}
}
With the getter and setter you can ask for data of an object or you can set the data.
AllStudents contains students and s_code is an int.
You can search by id mapping it first. Assuming the code is in a field called Id.
allStudents.stream().map(s -> Student::getId).collect(Collectors.toList()).contains(s_code);
This question already has answers here:
How to find an object in an ArrayList by property
(8 answers)
Closed 5 years ago.
I've just started learning java and I'm trying to create an application to register students.
Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.
public class RegStudent {
ArrayList<Student> studentList = new ArrayList<>();
Scanner input = new Scanner(System.in);
public void reggaStudent(int start) {
while (start != 0) {
String programNamn, studNamn;
int totalPoint, antalKurser;
System.out.println("Vad heter programmet?");
programNamn = input.nextLine();
System.out.println("Vad heter studenten");
studNamn = input.nextLine();
System.out.println("Hur många poäng har studenten?");
totalPoint = input.nextInt();
System.out.println("Hur många kurser är studenten registrerad på?");
antalKurser = input.nextInt();
// Add student to list of students
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
System.out.println("Vill du registrera in en fler studenter? "
+ "Skriv 1 för ja och 0 för nej");
start = input.nextInt();
input.nextLine();
} // End of whileloop
}
}
The class is:
public class Student {
private int totalPoint;
private int antalKurser;
private String programNamn;
private String studNamn;
private static int counter;
public Student(int totalPoint, int antalKurser, String program, String studNamn) {
this.totalPoint = totalPoint;
this.antalKurser = antalKurser;
this.programNamn = program;
this.studNamn = studNamn;
counter++;
}
public int getTotalPoint() {
return totalPoint;
}
public void setTotalPoint(int totalPoint) {
this.totalPoint = totalPoint;
}
public int getAntalKurser() {
return antalKurser;
}
public void setAntalKurser(int antalKurser) {
this.antalKurser = antalKurser;
}
public String getProgramNamn() {
return programNamn;
}
public void setProgramNamn(String programNamn) {
this.programNamn = programNamn;
}
public String getStudNamn() {
return studNamn;
}
public void setStudNamn(String studNamn) {
this.studNamn = studNamn;
}
public static int getCount(){
return counter;
}
#Override
public String toString() {
return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
+ "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
}
}
How do I go about to get and set the instance variables in specific instance? I.e find the instances.
I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.
I've added a counter just to see I actually created some instances of the class.
You simply query objects for certain properties, like:
for (Student student : studentList) {
if (student.getProgramName().equals("whatever")) {
some match, now you know that this is the student you are looking for
In other words: when you have objects within some collection, and you want to acquire one/more objects with certain properties ... then you iterate the collection and test each entry against your search criteria.
Alternatively, you could "externalize" a property, and start putting objects into maps for example.
studentList.add(new Student(totalPoint, antalKurser,
programNamn, studNamn));
You now have your Student objects in a list. I assume you have something like
List<Student> studentList = new ArrayList<>();
somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?
Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.
im having a trouble finishing my work because i dont know how to do the sorting of names together with the grade in ascending and descending. i hope you guys can help.
import java.util.Scanner;
public class SortingStudents {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int capacity = s.nextInt();
String [] name = new String[capacity];
Double [] grade = new Double[capacity];
for(int i = 0; i < capacity; i++) {
System.out.print("student's name: ");
name [i] = s.next();
System.out.print("grade: ");
grade [i] = s.nextDouble();
}
Scanner input = new Scanner(System.in);
System.out.println("Type A for Ascending D for Descending:");
char a=input.nextLine().charAt(0);
if(a == 'A' || a == 'a'){
for(int i = 0; i<grade.length;i++){
System.out.println(grade[i]+"\t" +grade[i]);
}
}
}
You are using Java, which is an object-oriented programming language. This means you can think about your problem in terms of classes which represent state in your problem domain and have behavior (methods) which manipulate this state.
In this case your code shows several responsabilities, for which you could create useful classes and/or methods:
entering data via the command line (number of students, name and grade and desired sorting direction)
a registry of students with a fixed size
sorting the student registry in the desired direction
Class names that come to mind are: DataEntry, Student, StudentRegistry. For sorting the students in different ways the standard approach is creating a Comparator class, see below.
The classes could look roughly like this:
public class Student {
private String name;
private Double grade;
// getters and setters ommitted for brevity
}
The registry:
public class StudentRegistry {
// it's easier to use a List because you are adding students one by one
private List<Student> students;
public StudentRegistry(int capacity) {
// ...constructor code initializes an instance of StudentRegistry
}
public void addStudent(Student student) {
// add a student to the list
}
public Student[] getStudents(Comparator<Student> comparator) {
// sort the list using the comparator and Collections.sort()
// use List.toArray() to convert the List to an array
// alternatively (java 8) return a Stream of Students
// or return an unmodifiable List (using Collections.unmodifiableList())
// you don't want to expose your modifiable internal List via getters
}
}
A comparator which can sort Ascending or Descending. You could consider adding the capability to sort either by grades or by names, that would be quite easy.
public class StudentComparator implements Comparator<Student> {
public enum Direction {
ASCENDING, DESCENDING
}
// optional addition:
//public enum Field{
// NAME, GRADE
//}
// if used, add Field parameter to the constructor
public StudentComparator(Direction direction) {
// initialize instance
}
#Override
public int compare(Student a, Student b) {
// implement Comprator method, see JavaDoc
}
#Override
public boolean equals(Object o) {
// implement equals, see JavaDoc
}
}
Class for letting the user enter data:
public class DataEntry {
public int getNumberOfStudents() {
// ...
}
public Student getStudent() {
// ...
}
public StudentComparator.Direction getSortingDirection() {
// ...
}
}
And a main class:
public class Main {
public static void main(String[] args) {
DataEntry dataEntry = new DataEntry();
int capacity = dataEntry.getCapacity();
StudentRegistry studentRegistry = new StudentRegistry(capacity);
for(int i=0; i<= capacity; i++) {
studentRegistry.addStudent(dataEntry.getStudent());
}
StudentComparator comparator = new StudentComparator(dataEntry.getSortingDirection());
Student[] students = studentRegsitry.getStudents(comparator);
}
}
This approach separates concerns of your problem in separate classes and methods, making the code much easier to understand, debug and test.
For example, to test the Main class you could set up a mock DataEntry class which provides predetermined values to your test. See the topic of unit testing.
If you want to do it your way without changing how the arrays are stored separately. You will not be able to use the Arrays.sort() method to sort your grades because that will not take the name array into account and you will lose the link between them so that the grades will no longer match with the names.
You could very quickly code up your own bubble sorter to quickly sort the array, and then you could use your loop to affect the name array at the same time. But if you don't want to code your own sorter, you will need to organise your grades and names array so that can be treated as one unit i.e in a separate class.
If you choose to code your own sorter then here is a great link to learn that: http://www.java-examples.com/java-bubble-sort-example
If you choose to change the way that you store the grades and names, here is how you can use the Arrays.sort() method:
http://www.homeandlearn.co.uk/java/sorting_arrays.html
You could just concatenate the name and grade and sort them, that way it could be a lot easier.
I'm having trouble with calling a method. The basis of the program is to read in data from data.txt, grab the name token given, then all of the grades that follow, then implement some operations on the grades to give details of the person's grades. I do all of the methods in a separate file named Grades.java, which has the Grades class. I'm just having trouble because I MUST have the testGrades method in my code (which I don't find necessary). I have done everything I need to do for the results to be perfect in a different program without having two different .java files. But it's necessary to do it this way. I think I have mostly everything pinned down, I'm just confused on how to implement and call the testGrades method. I commented it out and have the question on where it is in the program. Quite new to classes and objects, and java in general. Sorry for the lame question.
public class Lab2 {
public static void main(String[] args) {
Scanner in = null; //initialize scanner
ArrayList<Integer> gradeList = new ArrayList<Integer>(); //initialize gradeList
//grab data from data.txt
try {
in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException exception) {
System.err.println("failed to open data.txt");
System.exit(1);
}
//while loop to grab tokens from data
while (in.hasNext()) {
String studentName = in.next(); //name is the first token
while (in.hasNextInt()) { //while loop to grab all integer tokens after name
int grade = in.nextInt(); //grade is next integer token
gradeList.add(grade); //adding every grade to gradeList
}
//grab all grades in gradeList and put them in an array to work with
int[] sgrades = new int[gradeList.size()];
for (int index = 0; index < gradeList.size(); index++) {
sgrades[index] = gradeList.get(index); //grade in gradeList put into grades array
}
//testGrades(sgrades); How would I implement this method call?
}
}
public static void testGrades(Grades grades) {
System.out.println(grades.toString());
System.out.printf("\tName: %s\n", grades.getName());
System.out.printf("\tLength: %d\n", grades.length());
System.out.printf("\tAverage: %.2f\n", grades.average());
System.out.printf("\tMedian: %.1f\n", grades.median());
System.out.printf("\tMaximum: %d\n", grades.maximum());
System.out.printf("\tMininum: %d\n", grades.minimum());
}
}
This is a little snippet of the beginning of the Grades.java file
public class Grades {
private String studentName; // name of student Grades represents
private int[] grades; // array of student grades
public Grades(String name, int[] sgrades) {
studentName = name; // initialize courseName
grades = sgrades; // store grades
}
public String getName() {
return studentName;
} // end method getName
public int length() {
return grades.length;
}
well your test grades take a Grades object so you need to construct a Grades object using your data and pass it to your test grades method
i.e.
Grades myGrade = new Grades(studentName,sgrades);
testGrades(myGrade);
It looks like what you need to do is have some type of local variable in your main method, that would hold your custom Grade type. So you need add a line like..
Grades myGrades = new Grades(studentName, sgrades);
Then you can call your testGrades method with a line like...
testGrades(myGrades);
Looks like you may also need a toString method in your Grades class.
Seems like homework, so I tried to leave a bit to for you to figure out :)
I want to create a 2D Array that creates a mini seating chart of an airplane. So far, I've gotten it to successfully print out something that looks like this:
1A(0) || 1B(0) || 1C(0)
2A(0) || 2B(0) || 2C(0)
3A(0) || 3B(0) || 3C(0)
4A(0) || 4B(0) || 4C(0)
The zeroes represent an empty seat, and the number one is used to represent an occupied seat.
I first created the program with arrays that were class variables for a First Class, but I wanted to make this program usable for an Economy Class section. The only difference between the two sections is the size of the array so I edited my code to look like this:
public class Seating
{
private int FIRSTCLASS= 12;
private int ECONOMYCLASS= 240;
private int occupied, column;
private String[][] seatchart;
private int[][] seatlist;
private String[][] namelist;
private String name;
public String customer;
public Seating(String seatclass)
{
seatclass.toUpperCase();
if (seatclass.equals("FIRSTCLASS"))
{
seatchart= new String[FIRSTCLASS/3][3];
seatlist= new int[FIRSTCLASS/3][3];
namelist= new String[FIRSTCLASS/3][3];
}
else
if (seatclass.equals("ECONOMY"))
{
seatchart= new String[ECONOMYCLASS/3][3];
seatlist= new int[ECONOMYCLASS/3][3];
namelist= new String[ECONOMYCLASS/3][3];
}
}
public void Creation()
{
for (int i=0; i< seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
seatlist[i][j]= 0 ;
}
}
I get an null pointer exception error around for (int i=0; i< seatlist.length; i++)
How can I fix this error?
Thanks in advance!
The problem is with this line:
seatclass.toUpperCase();
Replace it with:
seatclass = seatclass.toUpperCase();
I think you are creating the class with a string like "firstclass" rather than "FIRSTCLASS" right? Those aren't the same strings and just invoking the toUpperCase method on the string without assigning the result to a variable to then be tested means nothing happens.
Then since none of your if conditions are met, the arrays are not initialized and a null pointer exception is thrown when Completion() is called.
I'm not sure if you are new to java programming, but I wanted to add a few recommendations to your class:
public class Seating {
private static int FIRSTCLASS= 12; // Make these constants static since they pertain to all
private static int ECONOMYCLASS= 240; // instances of your class. That way there is exactly on
// copy of the variables, which is more memory efficient.
private int occupied;
private column; // Okay but Java convention is to declare each member variable on its own line
// increases code readability.
private String[][] seatchart;
private int[][] seatlist;
private String[][] namelist;
private String locSeatClass;
private String name;
public String customer; // Okay but better to leave this private and then provide getter and
// setter methods to provide access to this string. Much easier to track
// down who is changing its value in your code.
public Seating(String seatclass) { // Java convention is to place the opening bracket here not
// on the next line.
// Make sure that seatClass is not null or empty. NOTE: This is a neat trick for
// simultaneously checking for both null and empty strings in one shot. Otherwise, you have
// you have to check for null and then examine the string's length which is more code.
if ("".equalsIgnoreCase(seatClass) {
throw new IllegalArgumentException("Seat class undefined.");
}
// Store the seat class in a member variable for use. Could also be a local variable.
// My original solution is problematic because it changes the original value of the seat
// class that was passed into the constructor (you might want that information).
locSeatClass = seatclass.toUpperCase();
if (locSeatClass.equals("FIRSTCLASS"))
{
seatchart= new String[FIRSTCLASS/3][3];
seatlist= new int[FIRSTCLASS/3][3];
namelist= new String[FIRSTCLASS/3][3];
}
else if (locSeatclass.equals("ECONOMY")) {
seatchart= new String[ECONOMYCLASS/3][3];
seatlist= new int[ECONOMYCLASS/3][3];
namelist= new String[ECONOMYCLASS/3][3];
}
else {
// Throw an exception if someone passes in an unknown seat class string.
throw new IllegalArgumentException("Unknown seat class detected.")
}
}
public void creation() { // NOTE: Java convention is to begin method names with a lower
// case letter.
// This method is unnecessary. Arrays of integers are initialized with an initial value
// of zero by default. However, if you want to make your class reusable, you could change
// change the name of the this method to clear, which would allow you to clear the arrays of
// an existing object.
for (int i=0; i< seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
seatlist[i][j]= 0 ;
}
}
}
The only way that line of code can generate a NPE is if seatlist is null. Unless you assign null to seatlist somewhere else in your class, the only way it can be null is if the argument that you pass to the Seating constructor does not match either "FIRSTCLASS" or "ECONOMY". Check your call to the constructor. Also, you might want to just use seatclass.equalsIgnoreCase().
You should modify your constructor to at least warn about that eventuality, since it is vital to the proper operation of the class that any instances of Seating have valid seatlist and namelist arrays.