Print array at given position - java

I am trying to print out two arrays at given position.
The program has two parts. One where the user is asked to enter a string(student name) and an int (student grade) at the end the user is asked to search for the name entered and to print out the student name and the grade
So far I cant't print any.
This is my code for populating the arrays...
System.out.println("Please Enter The Number Of Students In The Class!!");
int numberOfStudents = input.nextInt();
String []studentNames = new String[numberOfStudents];
int [] StudentGrades = new int[numberOfStudents];
int i;
for (i =0; i<numberOfStudents; i++)
{
System.out.println("Enter Student Name!");
studentNames[i]= input.next();
System.out.println("_________________");
System.out.println("Enter Student Grade");
StudentGrades[i] = input.nextInt();
System.out.println("_________________");
}
... and this for searching the name:
Scanner input = new Scanner(System.in);
String nameInput = input.next();
int cheak;
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
cheak++;
}
}
if (cheak !=0)
{
System.out.println("Name Found ");
}
else
{
System.out.println("Name Not Found");
}
Now I want to print the student name that is entered in the search with the corresponding grade.
How do I accomplish that?

You have to just keep a record of the index of target name in the studentNames array.
You can modify the loop in the following way to get the index in the cheak variable -
cheak = 0;
for ( String student : studentNames)
{
if (nameInput.equals(student))
{
break;
}
cheak++;
}
if (cheak != numberOfStudents)
{
System.out.println("Name Found. Name = " + studentNames[cheak] + " Grade = " + StudentGrades[cheak]);
}
else
{
System.out.println("Name Not Found");
}

try the following:
for ( String student : studentNames) {
if (nameInput.equals(student)) {//if the student is found, stop the loop
break;
}
cheak++;
}
if (cheak != studentNames.length){
System.out.println("Name Found ");
System.out.println("The name is: " + studentNames[cheak]);
System.out.println("Grade is: " + studentGrades[cheak]);
} else {
System.out.println("Name Not Found");
}

Related

Displaying Info

In a project for school, I'm required to make a menu system with the following options:
Load employees’ data - prompts user for the number of employees to be loaded and then prompts for each employee name, id (5 digit number), and annual salary
Add new employee - prompts user for an employee data, name, id, and annual salary
Display all employees - displays each employee’s data to the console, one employee per line
Retrieve specific employee’s data - prompts user for the employee id and displays the corresponding employee’s data: id, name, and salary
Retrieve employees with salaries based on range - prompts user for the lowest and highest salary and displays all employees with salaries in that range. Display each employee on separate line with all information - name, id, and salary
Exit
Each menu choice must be it's own be its own method, and he prefers we use arrays instead of lists, which is why I allotted 100 spaces. Here is what I have so far. Menu options 1, 2, and 6 run without breaking the program. But anything where things have to be displayed seems to break. My best guess is that there is an issue with passing and updating the array "employees" between all of the methods.
package practice;
import java.util.Arrays;
import java.util.Scanner;
public class Project {
public static Employee[] loadData() {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("How many employees would you like to add?"); //Determines how many employees to create
Employee[] employees = new Employee[100];
int numberEmployees = scanint.nextInt();
for (int i = 0; i < numberEmployees; i++) {
System.out.println("Enter name: ");
String empName = scanstr.nextLine();
System.out.println("Enter ID: ");
int empID = scanint.nextInt();
System.out.println("Enter Salary: ");
int empSalary = scanint.nextInt();
employees[i+1] = new Employee(empName, empID, empSalary); //Add employee to array
}
return employees;
}
public static Employee addEmployee() {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("Enter name: ");
String empName = scanstr.nextLine();
System.out.println("Enter ID: ");
int empID = scanint.nextInt();
System.out.println("Enter salary: ");
int empSalary = scanint.nextInt();
return new Employee(empName, empID, empSalary);
}
public static void displayEmployees(Employee[] employees) {
for (int i = 0; i < employees.length; i++) {
if (employees[i] != null) {
System.out.println(Arrays.toString(employees));
//System.out.println("Employee Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
}
}
public static void specificEmployee(Employee[] employees, int id) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].id == id) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("ID not recognized");
}
}
}
public static void salaryRange(Employee[] employees, int salaryMinimum, int salaryMaximum) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].salary >= salaryMinimum && employees[i].salary <= salaryMaximum) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("No employees within salary range");
}
}
}
public static void main(String[] args) {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
int menuChoice = 0;
while (menuChoice != 6) {
System.out.println("\tMenu:");
System.out.println("1. Load Employee Data");
System.out.println("2. Add New Employee");
System.out.println("3. Display All Employees");
System.out.println("4. Retrieve Specific Employee Data");
System.out.println("5. Retrieve Employees Within Salary Range");
System.out.println("6. Exit");
menuChoice = scanint.nextInt();
Employee[] employees = new Employee[100];
int amountEmployees;
if (menuChoice == 1) {
employees = loadData();
}
else if (menuChoice == 2) {
employees[0] = addEmployee();
}
else if (menuChoice == 3) {
displayEmployees(employees);
}
else if (menuChoice == 4) {
System.out.println("Enter 5 digit employee ID: ");
int id = scanint.nextInt();
specificEmployee(employees, id);
}
else if (menuChoice == 5) {
System.out.println("Enter minimum of salary range: ");
int salaryMinimum = scanint.nextInt();
System.out.println("Enter maximum of salary range");
int salaryMaximum = scanint.nextInt();
salaryRange(employees, salaryMinimum, salaryMaximum);
}
else if (menuChoice == 6) {
break;
}
else {
System.out.println("Invalid Choice");
}
}
scanint.close();
scanstr.close();
}
Any help would be appreciated!!!!!
There are a few problems in your code:
while (menuChoice != 6) {
System.out.println("\tMenu:");
System.out.println("1. Load Employee Data");
System.out.println("2. Add New Employee");
System.out.println("3. Display All Employees");
System.out.println("4. Retrieve Specific Employee Data");
System.out.println("5. Retrieve Employees Within Salary Range");
System.out.println("6. Exit");
menuChoice = scanint.nextInt();
**Employee[] employees = new Employee[100];**
int amountEmployees;
if (menuChoice == 1) {
employees = loadData();
}
You have declared the employees array inside the while loop, so each time you read an input you are creating a new one. This totally defeats the purpose of storing employees in an array and later retrieving them, which also makes the assignment redundant if menuChoice == 1. You must think about where you should declare your array.
public static void specificEmployee(Employee[] employees, int id) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].id == id) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("ID not recognized");
}
}
}
When you declare an array, the values by default are null, unless you assign them some values. Here, you are iterating the entire array and checking for employee id. You should consider what would happen if the employee at a particular index in the array is null. You must have checks for such cases.
A similar problem is in one of the other methods that you have created. I will let you debug that on your own.
And as suggested by #NomadMaker - Your second menu item only sets element 0 of the array. You can't add two or more employees.
I would suggest, you try to dry run your code and if you find it tough, try debugging it in an ide.

add method continues to add even when it exceeds the arraylist's size

import java.util.ArrayList;
import java.util.Scanner;
/*Create a program that keeps track of specific information for Students. The information stored should be the following:
First Name, Last Name, Major, GPA, UIN, NetID, Age, Gender,
For this simple program we will only need to store 10 students in an ArrayList.
Your students should be stored in an object called Student.
You should be able to add, display and remove Students in the ArrayList.
You will submit 2 files for grading: Lab4.java and Student.java*/
public class Lab4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
ArrayList<Student> newStudents = new ArrayList<Student>();
// ArrayList<Student> newStudents = new ArrayList<Student>(10); tried this as well, but doesn't work.
System.out.println("Welcome to the Student Interface!.");
System.out.println("Please select a number from the options below \n");
while (true) {
// Give the user a list of their options
System.out.println("1: Add a student to the list.");
System.out.println("2: Remove a student from the list.");
System.out.println("3: Display all students in the list.");
System.out.println("0: Exit the student interface.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
addStudents(newStudents);
break;
case 2:
removeStudent(newStudents);
break;
case 3:
displayStudent(newStudents);
break;
case 0:
System.out.println("Thank you for using the student interface. See you again soon!");
System.exit(0);
}
}
}
public static void addStudents(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
boolean student_added = false;
// TODO: Add a student that is specified by the user
System.out.println("Please enter first name: ");
String firstName = input.next();
System.out.println("Please enter last name: ");
String lastName = input.next();
System.out.println("Please enter major: ");
String Major = input.next();
System.out.println("Please enter GPA: ");
String GPA = input.next();
System.out.println("Please enter UIN: ");
String UIN = input.next();
System.out.println("Please enter NetID: ");
String NetID = input.next();
System.out.println("Please enter Age: ");
String Age = input.next();
System.out.println("Please enter Gender: ");
String Gender = input.next();
for (int i = 1; i < 5; i++) { // ( I have also tried i<newStudents.size(). Didn't work.Thank you in advance!)
newStudents.add(new Student(firstName, lastName, Major, GPA, UIN, NetID, Age, Gender));
student_added = true;
break;
}
if (student_added) {
System.out.println("Student Added");
System.out.println();
} else {
System.out.println("\n Student Interface is full!");
}
}
private static void displayStudent(ArrayList<Student> newStudents) {
// TODO Auto-generated method stub
for (Student e : newStudents) {
System.out.println(e);
}
}
private static void removeStudent(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
System.out.println("Please, enter the UIN to remove the Student: ");
String uin = input.nextLine();
for (Student e : newStudents) {
if (e.getUIN().equals(uin)) {
newStudents.remove(e);
System.out.println("Student removed");
break;
}
else {
System.out.println("Sorry, no such student with this " + uin + " " + "number exist");
}
}
}
}
The Student instance is being added to the list, and there is no check for if the size of the array is larger or equal to 10. You are checking the value of the i variable, which is created when you enter the for loop.
The for loop isn't the right tool for this job in this case.
Instead, do a check for newStudents.size(), and if that does not exceed the maximum value, add the student to the list.
For example:
if (newStudents.size() <= 10) { // check the size of the array [see note 1]
newStudents.add(new Student(firstName, lastName, Major, GPA, UIN, NetId, Age, Gender));
System.out.println("Student added\n");
} else {
System.out.println("\n Student interface is full!");
}
Note 1: As an aside, it'd be best if 10 was a constant at the top of the program (defined like public static const MAX_STUDENTS = 10;) to make the code more maintainable. See this question about what a magic number is.

Displaying details of object arrays

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();
}

No Such Element - No Line Found (Java)

I'm creating a program which prints a summary of the situation after interactive input has ended (ctrl - d). So it prints a summary of the average age and percentage of children who have received vaccines after interactive input.
However, I'm always receiving the No Line Found error whenever I press ctrl-d at Name:. My compiler tells me the error is at name = sc.nextLine(); within the while loop but I don't know what is causing the error exactly.
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
You do not correctly implement an exit condition for your loop if you ask me.
Try something like this:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
This way you can quit entering new persons without having to enter a strange command that might lead to an error. Furthermore, a do-while loop helps you to reduce your code, because you don't have to use the same code twice, i.e., everything between Scanner sc = new Scanner(System.in); and while(sc.hasNextLine()) in your example.

Java: coding that uses a variable to specify array length?

I am working on a student scores application that accepts the last name, first name and score for one or more students and stores the results in an array. Then it prints the students and their scores in alphabetical order by last name. We do not know how many students there are, but there will be fewer than 100.
We have to display the class average at the end of the student information and display a message after each student whose grade is more than 10 points below the class average.
My first issue is that I have created a do/while loop to ask if the user would like to enter another but it will not work!?!?
Second, I can not figure out how to display the "10 points below" message on individual students.
public class Student implements Comparable
{
String firstName;
String lastName;
int score;
//stores last name, first name and score for each student
public Student(String lastName,String firstName,int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.score = score;
}
//implement the comparable interface so students can be sorted by name
public int compareTo(Object o)
{
Student otherStudent = (Student)o;
if(otherStudent.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(otherStudent.firstName);
}
else
{
return lastName.compareToIgnoreCase(otherStudent.lastName);
}
}
public String toString()
{
return lastName + ", " + firstName + ": " + score;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class StudentApp
{
static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
Student [] studentArray;
String lastName;
String firstName;
int score = 0;
double average = 0;
System.out.println("Welcome to the Student Scores Application.");
System.out.println();
do{
//code that uses variable to specify the array length
int nStudent = 100; //array size not set unit run time
studentArray = new Student[nStudent];
for (int i=0; i<nStudent; i++)
{
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
studentArray[i] = new Student(lastName, firstName, score);
double sum = 0.0;
sum += score;
average = sum/nStudent;
}
}while (getAnotherStudent());
Arrays.sort(studentArray);
System.out.println();
for (Student aStudent: studentArray)
{
System.out.println(aStudent);
if (score<= (average-10))
{
System.out.println ("Score 10 points under average");
}
}
System.out.println("Student Average:" +average);
}
public static boolean getAnotherStudent()
{
System.out.print("Another student? (y/n): " );
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
}
}
There are a few problems here:
Every time through the do...while, you reinstantiate studentArray and sum. This means that all of your previously iterated over data is nuked when getAnotherStudent() is true - you want to instantiate the array and sum only once.
You don't stop if you have more than 100 students. You need an ending condition around nStudent as well in your loop.
You should make a few adjustments to getAnotherStudent() so that you can block on data, and wait when valid data is input - by using a loop:
public static boolean getAnotherStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) {
String choice = sc.next();
// blocks here - ignores all input that isn't "y" or "n"
while(!((choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("N")))) {
if (choice.equalsIgnoreCase("Y")) {
return true;
}
System.out.print("Another student? (y/n): " );
choice = sc.next();
}
}
return false; // obligatory
Your code is close there are just a couple of problems. The reason why your do while loop is not working is that you have a for loop inside of it. This means that you will ask for 100 students before you ask if they want to add another one. Your sum is being created inside this loop so it will be reset each time.
Finally you do not know how many Students will be added but your code assumes there will be 100 Students. This means you cannot use the for each loop to go through the array as some could be null. Just use a regular for loop going up to the last index of a student you added. Here are the changes:
Student[] student = new Student[nStudent];
int studentCount = 0; //declear the counter outside the loop
double sum = 0.0; //declear the sum outside the loop
do {
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
student[studentCount] = new Student(lastName, firstName, score);
sum += score; //increase the sum
studentCount++; //increment the counter
} while (studentCount < nStudent && getAnotherStudent()); //stop if the user says 'n' or we hit the maximum ammount
average = sum / studentCount; //work out the average outside the loop
System.out.println();
for (int i= 0; i< studentCount; i++ ) {
System.out.println(aStudent);
if (score <= (average - 10)) {
System.out.println("Score 10 points under average");
}
}
System.out.println("Student Average:" + average);
}
Your getAnotherStudent() method should read:
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) { // blocks until user entered something
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
} else {
// won't come here
return false;
}

Categories