How to set condition for object's property in class java - java

I have a program to enter the student's name, gender, grade, and rank
Here is my code:
public class Exercise_W28 {
String name;
String Sex;
int Score;
String ratting;
public Exercise_W28(String name, String Sex,
int Score, String ratting)
{
this.name = name;
this.Sex = Sex;
this.Score = Score;
this.ratting = ratting;
}
public String getName()
{
return name;
}
public String getSex()
{
return Sex;
}
public int getScore()
{
return Score;
}
public String getratting()
{
return ratting;
}
public String toString()
{
return("Name: "+ this.getName()+
".\nSex: "+ this.getSex()+
".\nScore: "+ this.getScore()+
".\nRank: "+ this.getratting()+"."
);
}
public static void main(String[] args)
{
Exercise_W28 std = new Exercise_W28("Jullien","male", 9, "RankA");
System.out.println(std.toString());
} }
Now I want to not put the rank in, but based on the score to determine the rank 1~5 : rankC, 5~7: rankD, 8~10: rankA.
I just learned about classes in java and I don't know how to handle it

You can remove the Rank from constructor and basis on the score passed, initialize the Rank value in constructor itself !
For e.g.
public Exercise_W28(String name, String Sex,
int Score)
{
this.name = name;
this.Sex = Sex;
this.Score = Score;
// if(score == 5)
{
ratting="Rank C" ; //so on and so forth
}
If the logic is too long, consider defining it in another method which returns Rank in String form!

Related

How to use boolean with constructor in java?

We have an activity that will store and display the information of an employee.
I've already created no-modifier class named Person and a public class named Employee which is the the main method. My problem is I don't know how to make the boolean in the class Person which will be used in the main method with a scanner.
class Person {
private String name;
private int contactNum;
private boolean status;
public boolean isRegular;
public String getName(){
return name;
}
public int getContactNum(){
return contactNum;
}
public void setName(String name){
this.name=name;
}
public void setContactNum(int contactNum){
this.contactNum=contactNum;
//how to make the boolean of status and isRegular?
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person P = new Person();
System.out.println("Type employee's name, contact number");
System.out.println("Press Enter after every input");
P.setName(input.nextLine());
P.setContactNum(input.nextInt());
System.out.println("Press Y if employee is regular or N if not");
//how to use boolean here that comes from the class Person?
System.out.println("Name: "+ P.getName());
System.out.println("Contact Number: "+ P.getContactNum());
System.out.println("Status:" + this is where the user is ask to Press Y if employee is regular or N if not )//the status is if the employee is regular or not.
My suggestion for your code:
System.out.println("Press Y if employee is regular or any other key if not");
P.setRegular(input.nextLine().equalsIgnoreCase("Y"));
Your constructor
public class Person {
private String name;
private int contactNum;
private boolean status;
private boolean isRegular;
//No arg constructor
public Person() {
}
//Full arg constructor
public Person(String name, int contactNum, boolean status, boolean isRegular) {
this.name = name;
this.contactNum = contactNum;
this.status = status;
this.isRegular = isRegular;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getContactNum() {
return contactNum;
}
public void setContactNum(int contactNum) {
this.contactNum = contactNum;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public boolean isRegular() {
return isRegular;
}
public void setRegular(boolean regular) {
isRegular = regular;
}
}
Edit
I've noticed an error in the above code and fixed it. This line should be:
P.setRegular(input.next().equalsIgnoreCase("Y"));
You can print booleans as is just like any other Java primitive. `
System.out.println("Status:" + P.isRegular());
would print Status: true or Status: false.
If you want it to print Status: Yes or Status: No, you could do something like this:
System.out.println("Status: ".concat((P.isRegular())?("Yes"):("No")));

File with multiple data types, into arrays, then sort one array while keeping the records together

My problem is that I will be giving a file with student information: name, age, and GPA. I then have to turn each data element into a separate array. I then have to sort GPA into descending order, while keeping name and age with the corresponding GPA, and then print it out with "Name Age GPA" heading.
Check below code to sort data based on GPA. However you will have to include relevant code for file reading.
Student.java (POJO)
public class Student {
String name;
int age;
double GPA;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getGPA() {
return GPA;
}
public void setGPA(double gPA) {
GPA = gPA;
}
public Student(String name, int age, double gPA) {
super();
this.name = name;
this.age = age;
GPA = gPA;
}
#Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", GPA=" + GPA + "]";
}
}
StudentSorter.java
import java.util.Comparator;
public class StudentSorter implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
if(o1.getGPA() < o2.getGPA()) return 1;
if(o1.getGPA() > o2.getGPA()) return -1;
else return 0;
}
}
Tester.java
public class Tester {
public static void main(String[] args) {
Student s1 = new Student("A",14,7.9);
Student s2 = new Student("B",17,8.2);
Student s3 = new Student("C",20,7.0);
Student s4 = new Student("D",15,6.9);
Student s5 = new Student("E",14,9.1);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
StudentSorter ss = new StudentSorter();
Collections.sort(list, ss);
System.out.println(list.toString());
}
}

Java Store multiple phone number for one user

Question: Store more than 1 user data with id, name, weight, age, and phone number (can have multiple phone number)
How do I store multiple phone number for one user?
I facing an error "Exception in thread "main" java.lang.NullPointerException at Store_User.main(Store_User.java:29). Anyone can solve it?
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Mark", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Ken", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Callie", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
String out ="";
for(String number: usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}
Chat conversation end
EDIT: Phone numbers are stored as an ArrayList of Strings and are "linked" to the usrId since they are non-static members of the same class, hence each User object will have it's own id and list of numbers. You can access the phone numbers of a user using:
usr.getPnum()
where usr is an instance of User.java, this will return a ArrayList<String> representing the phone numbers, if you want a specific number you can access the list by index like so:
usr.getPnum().get(0) //The index in this case is 0
User.java
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
this.Pnum = Pnum;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
Store_User.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Tee Ting Ong", 55.5, 26, Arrays.asList("00000000", "00000000", "00000000"));
User usr2 = new User(2, "Tee Soon Teh", 54.7, 33, Arrays.asList("00000000", "00000000"));
User usr3 = new User(3, "Tee Ting Ken", 62.3, 34, Arrays.asList("00000000"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
//This print out the numbers
String out = "";
for(String number : usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}

Filling array with next empty space?

Here are my two classes Country and Countries. I am doing questions from online as extra practice.
I need to:
-Add a method to Countries - addCountry(String name, String capital, int population - Which fills in the element by nextFreeCountry and increments nextFreeCountry
Can somebody provide some help? I am struggling to understand how to fill in the element by nextFreeCountry.
Country:
public class Country {
private String name;
private String capital;
private int population;
Constructor to add the name capital and population
public Country(String name, String capital, int population) {
this.name = name;
this.capital = capital;
this.population = population;
}
Get name method
public String getName() {
return name;
}
public String getCapital() {
return capital;
}
public int getPopulation() {
return population;
}
public String toString() {
return "Name = " + getName() + " Capital = " + getCapital() + " Population = " + getPopulation();
}
}
Countries:
class Countries {
Creating an array of Country called countries
private Country[] countries;
private int nextFreeCountry = 0;
Setting the size for the array
public Countries(int size) {
countries = new Country[size];
}
addCountry method
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] =
nextFreeCountry++;
}
}
As countries array hold Country objects, so create a new object and put it in array. Something like this:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name,capital,population);
nextFreeCountry++;
}
You have to add a new country to the array which you are not doing at the moment. Like so:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name, capital, population);
nextFreeCountry++;
}
Alternatively just pass a Country to the method like this:
public void addCountry(Country country) {
countries[nextFreeCountry] = country;
nextFreeCountry++;
}
You may also be better off using an ArrayList rather than an array so you dont have to worry about the array index being out of bounds etc.

NullPointerException on array with length one initializing

This is my method to updateHighScoreRecords():
public GameRecord[] updateHighScoreRecords(GameRecord[] highScoreRecords, String name, int level, int score) {
GameRecord[] gameRecord = null;
if (highScoreRecords.length == 0) { // Rule one
gameRecord = new GameRecord[1];
gameRecord[0].setName(name);
gameRecord[0].setLevel(level);
gameRecord[0].setScore(score);
System.out.println("Role one Done");
}
return gameRecord;
}
And this is my GameRecord class:
public class GameRecord {
private String name;
private int level;
private int score;
public GameRecord(String name, int level, int score) {
this.name = name;
this.level = level;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
But there is a nullPointer exception on this line:
gameRecord[0].setName(name);
Why?
I want to return an array of GameRecord type when highScoreRecords length is zero.
You never initialized zeroth element. First you have to add element at zero position and then access it.
gameRecord[0] = new GameRecord();
gameRecord[0].setName(name);
When you wrote
gameRecord = new GameRecord[1];
That means you are just initializing an array to store 2 GameRecord elements. Nothing else. Initially those are null's. You need to initialize each element to use them further. Otherwise they are still null.

Categories