public Student retrieveById(int id) - java

public class Roster extends ArrayList<Student>
{
public boolean containsStudent(String ln)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter last name of student: ");
String lName = user_input.next();
for (Student student : this)
{
if (student.getLastName().equals(lName))
return true;
}
return false;
}
How can I fix the error in the next method:
public Student retrieveByld(int id)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter the ID of the student: ");
String idNum = user_input.next();
for (Student student : this)
{
if (student.getID().equals(idNum))
return student.getFullName();
}
return " ";
}
Error: int cannot be dereferenced. I'm guessing I cannot compare to ints using the .equals method but how can I without changing the syntax too much.
Given the id, I have to make the program find the student in the list and return that students full name. If student not found I have to return null. If it helps here's my Student class.
public class Student
{
private String lName, fName;
private int idNum;
public Student(int id, String fn, String ln)
{
lName = ln;
fName = fn;
idNum = id;
}
public String getFullName()
{
return fName + " " + lName;
}
public String getLastName()
{
return lName;
}
public String getFirstName()
{
return fName;
}
public int getID()
{
return idNum;
}
public String toString()
{
return fName + " " + lName + " " + idNum;
}
}

ints do not have the equals() method to see if they are equal, they use the == operator, as it's a primitive type. What you're looking for to change is the line if (student.getID().equals(idNum)), which should be: if (student.getID() == idNum).

Your getID() method returns an int, which is a primitive type, meaning it does not have any methods, including the "equals" that you're trying to call. So, either you need to change your idNum from a String to an int, or you need to change what you get back from student.getID() to a String.
Since you're using a Scanner, that has a nextInt() method, which will return the user input as an int. Then you just check for equals using the standard == operator.
Something like this:
public Student retrieveByld(int id)
{
Scanner user_input = new Scanner (System.in);
System.out.println("Enter the ID of the student: ");
int idNum = user_input.nextInt();
for (Student student : this)
{
if (student.getID() == idNum)
return getFullName();
}
return " ";
}

Use Integer class. It's a wrapper around int, giving you access to such things as equals() method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html

Related

Trying to stop the user from entering a String into my double in java

I tried a for loop with an if in it but I didn't know what I should've put in if(?), so then I went for using try and a catch and imported InputMismatchException. I then tried making an array with numbers from 0 to 9(I am a noob and don't know what I am doing) and used a for loop with and if, I know I could use a while. Please help me recent them from entering a string instead of numbers.
import java.util.Scanner;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Employee {
// fields
private String firstName, lastName;// creates both firstName and lastName as string and private fields
private String sal;// creates sal a private and double field
private int years;// creates years a private and int field
// constructors
public Employee() {// default constructor
this("", "", 0, 0);// this sets the default values for each one of the fields
}
public Employee(String firstName, String lastName, double sal, int years) {// overloaded constructor
this.firstName = firstName;// gets the values from the field firstname and then puts it in string firstname
this.lastName = lastName;// gets the value from the field secondname and then puts it in string
// secondname
this.sal = sal;// gets the value from the field sal and then puts it in float sal
this.years = years;// gets the value from the field years and then puts it in int years
}
// methods
public String getFirstName() {// accessor for the field firstname
return firstName;
}
public void setFirstName(String firstName) {// mutator for the field firstname
this.firstName = firstName;
}
public String getLastName() {// accessor for the field lastname
return lastName;
}
public void setLastName(String lastName) {// mutator for the field lastname
this.lastName = lastName;
}
public String getSal() {// accessor for the field lastname
return sal;
}
public void setSal(String sal) {// mutator for the field sal
this.sal = sal;
}
public int getYears() {// accessor for the field years
return years;
}
public void setYears(int years) {// mutator for the field years
this.years = years;
}
public void ScannerMethod() {
int arrInt[] = new int[10];
arrInt[0] = 0;
int j = 0;
boolean a = false;
Scanner get = new Scanner(System.in);
System.out.println("enter first name: ");
firstName = get.next();
System.out.println("enter second name: ");
lastName = get.next();
System.out.println("enter the salary: ");
while(j<10) {
arrInt[j] = j+1;
j++;
}
for(int i = 0; i<1; i++){
if(sal == arrInt[]){
System.out.println("Pleas enter it agian: ");
sal = get.next();
i = 0;
}else{
i = 2;
}
}
/*/while (!a) {
try {
sal = get.nextDouble();
a = false;
} catch (Exception e) {
System.out.println("Invalid input please enter a numeric value: ");
a = true;
}
}/*/
System.out.println("enter the years of service: ");
years = get.nextInt();
}
public String typeStats() {// this method prints out the stats for the employee
System.out.println("Report: " + firstName.substring(0, 1).toUpperCase() + firstName.substring(1) + " "
+ lastName.substring(0, 1).toUpperCase() + lastName.substring(1) + " $" + sal + " " + years);
return null ;
}
}
Here is a method which asks the user for a double until they input a valid double.
package test2134235;
import java.util.Scanner;
public class ParseDouble {
public static void main(String[] args) {
System.out.println("This is your double: " + getDoubleFromKeyboard());
}
static Double getDoubleFromKeyboard() {
Scanner scanner = new Scanner(System.in);
for (;;) {
System.out.println("input a Double value");
try {
String input = scanner.nextLine();
Double d = Double.parseDouble(input);
return d;
} catch (NumberFormatException e) {
System.out.println("Sorry, only Double values can be used.");
}
}
}
}
You have a comment and an answer that I think address your needs. I wanted to literally answer the question implied in your header: "Trying to stop the user from entering a String into my double in java"
The answer is you can't control what the user types in to the console. What is typed into the console is always going to be characters and read in as a String. It's your job (as the comment and the answer address) to make sure bad input doesn't crash your program. So you need to analyze it and ask "Does this look like it's a double?" and if it does, go ahead and store it in your variable and if not, take some other action like prompting the user to try again.

How can i use input(int) in get and return method in Java?

so im just starting to study java and planning to learn it in-depth and then i wanna ask this thing because im stuck and to learn more.
im trying to use the get and return method.
i wanted to do this in an input way but i cant use the
"int age = person1.GetAge()
System.out.println("Age:" + age) because it will become 2 variables (age)
i hope you understand my question and i know it sounds stupid but i wanna learn xD.
CODE:
//unfinished
//cant use the getAge, no idea how; the value in yrsleft is always 65 despite of the formula that i give
package practice;
import java.util.Scanner;
class person{
String name;
int age;
void speak() {
System.out.print("Hello my name is:" + name);
}
int retire() {
int yrsleft = 65 - age;
return yrsleft;
}
int GetAge() {
return age;
}
}
public class curiosity1{
public static void main(String[]args) {
person person1 = new person();
Scanner input = new Scanner(System.in);
System.out.print("What is your name:");
String name = input.next();
System.out.print("What is your age:");
int age = input.nextInt();
//person1.name = "John";
//person1.age = 30;
System.out.println("Name: " + name);
int age = person1.GetAge();
System.out.println("Age:" + age);
int years = person1.retire();
System.out.println("Years till retirement:" + years);
}
}```
I hope I understood your question correctly, you want to do this?
person1.age = input.nextInt();
person1.name = input.next();
System.out.println("Age:" + person1.getAge());
Or you can override toString() method in your class (since all java classes are inherited from Object, which has this method) to represent your object with a string. Also, you should create a constructor for your Person class.
class Person { // always start class name with a capital letter
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
// Your methods and etc.
#Override
public String toString() {
return "Name:" + this.name + ". Age:" + this.age;
}
}
And then:
int age = input.nextInt();
String name = input.next();
Person person1 = new Person(age, name);
System.out.println(person1.toString());

Objects in Java is printing out junk

My program is a simple program that involves the use of objects. There are no errors the only problem is that my program is printing out junk. After it asked the user for it name, age , and gender.
Down below are two sets of programs. The first one is the object or the skeleton of the person. The second one is the print that asks for the user name age gender and prints it out.
public class Person
{
private String name;
private int age,personality,appearance;
private String gender;
//constructor method. only use it once
public Person(String nm, int ag,String gend) {
name=nm;
age=ag;
gend=gender;
personality=1+(int)(Math.random()*10);
appearance=1+(int)(Math.random()*10);
}
//accessor created
public String getName() {
return name;
}
public String getGend() {
return gender;
}
public int getInt() {
return age;
}
//mutator method. When using "void" NO RETURN TYPE
public void setName (String nm) {
name=nm;
}
public void setAge (int ag) {
age=ag;
}
public void setGender (String gend)
{
gender=gend;
}
//helper method (kind of like print but not really printing
public String toString () {
String orange ="";
orange ="Name "+name+"/n";
orange +="age"+age+"/n";
orange +="Gender: "+gender"/n";
orange +="Personality "+personality+"/n";
orange +="Apperance "+appearance+"/n";
return orange;
}
}
2)
import java .util.Scanner;
public class PersonTester {
public static void main (String []args){
// calling person
Person person;
String name="", gender ="";
int age =0;
Scanner input =new Scanner(System.in);
System.out.println ("What is your name");
name =input.nextLine();
System.out.println("What your age?");
age=input.nextInt();
input.nextLine();
System.out.println ("What is your gender");
gender =input.nextLine();
person=new Person (name,age,gender);
System.out.println(person);
}
We are learning bout basic objects for example we only learned about private variables,constructor, accessor, mutator, and helper methods.
In your toString() you have two errors. You need to use a + between gender"/n" and you need to use \n if you want a newline.
public String toString () {
return "Name " + name + "\n" +
"Age" + age + "\n" +
"Gender: " + gender + "\n" +
"Personality " + personality + "\n" +
"Appearance " + appearance + "\n";
}
If the problem is the gender is not printed out properly, the problem is in your constructor. You are passing in gend, but not saving it. Instead you overwrite the argument with the gender member variable:
public Person(String nm, int ag,String gend)
{
name=nm;
age=ag;
gend=gender;
You wanted:
gender = gend;

How to iterate, search and display a specific element in an ArrayList

I'm having a problem with a specific part of a program. What I want to do is iterate, search and display an element from an ArrayList.
So I tried implementing my own snippet to the main function of the code to try:
else if (menuChoice==3) {
System.out.println("Search Student:");
String search = input.nextLine();
for (Student student : students)
{
if (students.equals(search)){
System.out.println(student);
}
}
}
Hoping that it would iterate through the ArrayList and access/display that specific element in the list. It returns blank, what am I doing wrong?
Here's the whole code if you're wondering:
package student;
import java.util.*;
public class Student
{
private String r_name;
private int r_age;
private String r_course;
private String r_year;
private String r_section;
private String r_studno;
public Student( String name, int age, String course, String year, String section, String studno )
{
r_name = name;
r_age = age;
r_course = course;
r_year = year;
r_section = section;
r_studno = studno;
}
public String getName()
{
return r_name;
}
public int getAge()
{
return r_age;
}
public String getCourse()
{
return r_course;
}
public String getYear()
{
return r_year;
}
public String getSection()
{
return r_section;
}
public String getStudno()
{
return r_studno;
}
public String toString()
{
return "Name: " + r_name + ", Age: " + r_age +
", Course: " + r_course + ", Year: " + r_year +
", Section: " + r_section + ", Student Number: " + r_studno;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int menuChoice = 4;
do {
System.out.println("\t\t\tStudent Record Menu");
System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
try {
System.out.println("Enter a choice: ");
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println("Add a Student");
System.out.println("Full name:");
String name = input.nextLine();
int age = -1;
do {
try {
System.out.println("Age:");
age = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
continue;
}
} while (age <= 0);
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
System.out.println("Section:");
String section = input.nextLine();
System.out.println("Student Number:");
String studno = input.next();
Student student = new Student(name, age, course, year, section, studno);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
} else if (menuChoice==3) {
System.out.println("Search Student:");
String search = input.nextLine();
for (Student student : students)
{
if (students.equals(search)){
System.out.println(student);
}
}
}
} while (menuChoice<4);
}
}
You are checking if the ArrayList students is equal to the String search. The result can only be false. I guess, you are trying to do the following:
for (Student student : students)
{
if (student.getName().equals(search))
{
System.out.println(student);
break;//assuming student name are unique. remove if not
}
}
You must compare the search key with the key id of student for example if all names are unique then use
for (Student student : students)
{
if (student.getname().equals(search)){
System.out.println(student);
}
}
You are compairing the whole student object reference with the search key how it will compare it
if you want to display the whole content then you will have to make a method in which you will get all details using the id eg:
getStudentbyname( String studentname){
here comes the code to get all data
}
then in your for loop call the method and store in array
for (Student student : students)
{
if (student.getname().equals(search)){
Arraylist<String> studentarr = student.getStudentbyname(student.getname());
System.out.println(""+studentarr)
}
}

NullPointerException Error (Java)

I'm getting the NullPointerException when I use this method. Someone told me it is because student.getId() returns a null. I have tried to fix this, but I can't figure it out. Below is just a snippet of the code, just the method and the Student class.
edit: I added the part where the array was created.
Student[] students ;
public Student[] enterStudents(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int numOfStudents = input.nextInt();
Student[] students = new Student[numOfStudents];
int i;
for(i = 0; i <= numOfStudents - 1; i++){
System.out.println("Enter student's ID: ");
int id = input.nextInt();
System.out.println("Enter student's first name: ");
String first = input.next();
System.out.println("Enter student's last name: ");
String last = input.next();
System.out.println("Enter student's class: ");
String stuClass = input.next();
Student x = new Student(id,first,last,stuClass);
students[i] = x;
}
return students;
}
public void retrieveStuId(){
Scanner input = new Scanner(System.in);
System.out.println("Enter student id");
int searchID = input.nextInt();
int i;
for(i = 0; i < students.length; i++){
Student student = students[i];
int search = student.getId();
if (search == searchID) {
System.out.println(student.toString());
}
}
}
class Student{
private int studentID;
private String firstName;
private String lastName;
private String stuClass;
public Student(){
}
public Student(int id, String first, String last, String c ){
studentID = id;
firstName = first;
lastName = last;
stuClass = c;
}
public void setID (int id){
studentID = id;
}
public void setStuClass (String c){
stuClass = c;
}
public void setFirst(String first){
firstName = first;
}
public void setLast(String last){
lastName = last;
}
public String getFirst(){
return firstName;
}
public String getLast(){
return lastName;
}
public int getId(){
return studentID;
}
public String getStuClass(){
return stuClass;
}
public String toString(){
return "Student ID: " + studentID + " --- " + "Student Name: " + firstName + " " + lastName + " --- " + "Class:" + stuClass;
}
}
Thank for any help in advance.
Your students array has null values, which you try to dereference. The bug isn't in the code you posted, rather where the students array is created and filled.
Just check for null values, and print something like "student not found."
for(i = 0; i < students.length; i++){
Student student = students[i];
if ( student != null ) {
int search = student.getId();
if (search == searchID)
System.out.println(student.toString());
}
}
EDIT:
I checked your code, it works, I tested it by adding
public class StudentTest {
public static void main(String[] args) {
StudentTest s = new StudentTest();
}
public StudentTest() {
students = enterStudents();
retrieveStuId();
}
// your code here ...
Student[] students ;
// .... end
}
Check the place where you assign the array returned by enterStudents.
There are two problem with that code. First is related to shadowing as mentioned before.
Second, as long as Im concerned about this code there is problem with not assigned return type to variable. Basically I think you forgotten to assigned return from your method enterStudents to your variable. Hopefully it is clear for you :)
There is an undefined (null) Student in your students array.Check if it's not null then use getID method.
How did you create the student array? Is it initialized with a Student for every position?
To find out print the value of student after this line:
Student student = students[i];
with
System.out.println(student);
for example. Also check whether all the students in the array have been initialized with a
correct ID so getIt() returns a non-null value. (try printing the value after assigning to search).
You have two (that is TWO) declarations for something called students. One of them (the local variable) is being initialized, and the other (the instance variable) is not being initialized. The NullPointerException is being thrown when you try to use the one that is not initialized.
You shouldn't have two declarations.
Since this is homework, I'll leave it to you to figure out which declaration to delete ... and what to do about the other one.

Categories

Resources