So im stuck with my code here. Im supposed to use get and set method to give a person a name, a surname and year of birth.
Here is the class:
import java.util.Scanner;
public class Person {
private int Birthyear;
private String Sname;
private String Name;
public Person() {
}
public Person(String n,String s,int b){
Name = n;
Sname = s;
Birthyear = b;
}
public String getName (){
return Name;
}
public String getSname (){
return Sname;
}
public int getBirthyear (){
return Birthyear;
}
This is the set code where i check the code for things like a name containing a number and if your birtyear is incorrect. This is also where i believe the problem is.
public void setb(int b){
while(b < 1899 || b >= 2016 ){
System.out.print("Du existerar inte , försök igen: " );
b = new Scanner(System.in).nextInt(); //Checks if age is possible.
}
}
public void setn(int n){
while(Name.matches(".*\\d+.*")){
System.out.print("Felaktigt namn, försök igen: " );
n = new Scanner(System.in).nextInt(); //Checks to see if there is any numbers in the name. }
}
public void sets(int s){
while(Sname.matches(".*\\d+.*")){
System.out.print("Felaktigt namn, försök igen: " );
s = new Scanner(System.in).nextInt(); //Checks so there is no numbers in the surname
}
}
}
This is my main.
import java.util.Scanner;
public class PersonUI {
public PersonUI() {
}
public static void main(String[] args) {
System.out.println("Skriv in ditt förnamn: " );
String n = new Scanner(System.in).nextLine();
System.out.print(n); //Your name
System.out.println(" Skriv in ditt efternamn: " );
String s = new Scanner(System.in).nextLine();
System.out.print(n +" "+ s);//your surname
System.out.println(" Skriv in ditt födelseår: " );
int b = new Scanner(System.in).nextInt();
System.out.println(n +" "+ s +" "+ b);//date of birth
Person p1 = new Person (n,s,b); //Name of person and date of birth
here is the get method
System.out.print(p1.getName());
System.out.print(" ");
System.out.print(p1.getSname());
System.out.print(" ");
System.out.print(p1.getBirthyear());
}
}
I believe the code fails here
public void setb(int b){
while(b < 1899 || b >= 2016 ){
System.out.print("Du existerar inte , försök igen: " );
b = new Scanner(System.in).nextInt(); //Kollar ifall du har en ålder som fungerar.
}
}
public void setn(int n){
while(Name.matches(".*\\d+.*")){
System.out.print("Felaktigt namn, försök igen: " );
n = new Scanner(System.in).nextInt(); //Kollar så att det inte finns siffror i namnet.
}
}
public void sets(int s){
while(Sname.matches(".*\\d+.*")){
System.out.print("Felaktigt namn, försök igen: " );
s = new Scanner(System.in).nextInt(); //Kollar så att det inte finns siffror i namnet.
}
or here
Person p1 = new Person (n,s,b); //Säger vad personen heter och när dne är född
System.out.print(p1.getName());
System.out.print(" ");
System.out.print(p1.getSname());
System.out.print(" ");
System.out.print(p1.getBirthyear());
}
}
So i changed your code a little bit, it should be working like this
The methods to check the values are now static and do return a boolean to check if the are matching the correct input.
public class Person {
private int Birthyear;
private String Sname;
private String Name;
public Person() {
}
public Person(String n, String s, int b) {
Name = n;
Sname = s;
Birthyear = b;
}
public String getName() {
return Name;
}
public String getSname() {
return Sname;
}
public int getBirthyear() {
return Birthyear;
}
public void setName(String name) {
Name = name;
}
public void setSName(String sName) {
Sname = sName;
}
public void setBirthYear(int birthyear) {
Birthyear = birthyear;
}
public static boolean setb(int b) {
return !(b < 1899 || b >= 2016);
}
public static boolean setn(String n) {
return !n.matches(".*\\d+.*");
}
public static boolean sets(String s) {
return !s.matches(".*\\d+.*");
}
}
The other class does simply use these static methods now to loop as long as the input is not matching your critera.
Also you don´t need to create a new Scanner object for each input, just create it once.
public class PersonUI {
public static void main(String[] args) {
String n, s;
int b;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Skriv in ditt förnamn: ");
n = scanner.nextLine();
System.out.println(n); // Your name
} while (!Person.setn(n));
//
do {
System.out.println(" Skriv in ditt efternamn: ");
s = scanner.nextLine();
System.out.println(n + " " + s);// your surname
} while (!Person.sets(s));
do {
System.out.println(" Skriv in ditt födelseår: ");
b = scanner.nextInt();
System.out.println(n + " " + s + " " + b);// date of birth
} while (!Person.setb(b));
Person p1 = new Person(n, s, b); // Name of person and date of birth
System.out.print(p1.getName());
System.out.print(" ");
System.out.print(p1.getSname());
System.out.print(" ");
System.out.print(p1.getBirthyear());
scanner.close();
}
}
How about this?
public class Person {
private int Birthyear;
private String Sname;
private String Name;
public Person(String n, String s, int b) {
if (!isBOk(b) || !isNOk(n) || !isSOk(s)) {
throw new IllegalArgumentException();
}
Name = n;
Sname = s;
Birthyear = b;
}
public String getName() {
return Name;
}
public String getSname() {
return Sname;
}
public int getBirthyear() {
return Birthyear;
}
private boolean isBOk(int b) {
return (b >= 1899 || b < 2016);
}
private boolean isNOk(String n) {
return n.matches(".*\\d+.*");
}
private boolean isSOk(String s) {
return s.matches(".*\\d+.*");
}
}
public void setb(int b)
You can rename this method to something like
private static boolean checkB(int b)
Do this in the constructor: (you can do this in the setter methods as well, make seperate methods to validate your data)
public class Person{
int b;
public person(int b){
if(checkB(b)){
this.b = b;
}
else{
//throw exception
}
}
private static boolean checkB(int b){
return (b < 1899 || b >= 2016);
}
public void setB(int b){
if(checkB(b)){
b = b;
}
else{
//throw exception
}
}}
Related
The question wants me to do:
An array of Finance called financeRecord to store the details
of the payments for each semester.
This is my code
package lab5;
class Student_U extends Student {
public String student_name;
private String studentID;
public int student_age;
private byte currentSemester;
private byte TotalFinanceRecord;
private String cohort;
public Student_U() {
student_name = " ";
studentID = " ";
student_age = 0;
currentSemester = 1;
TotalFinanceRecord = 0;
cohort = " ";
}
public Student_U(String student_name, String studentID, int student_age,
String course, String year,
String section, String subject, String student_name2,
String studentID2, int student_age2,
byte currentSemester, byte totalFinanceRecord, String cohort) {
super(student_name, studentID, student_age, course, year,
section, subject);
student_name = student_name2;
studentID = studentID2;
student_age = student_age2;
this.currentSemester = currentSemester;
TotalFinanceRecord = totalFinanceRecord;
this.cohort = cohort;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
public byte getCurrentSemester() {
return currentSemester;
}
public void setCurrentSemester(byte currentSemester) {
this.currentSemester = currentSemester;
}
public byte getTotalFinanceRecord() {
return TotalFinanceRecord;
}
public void setTotalFinanceRecord(byte totalFinanceRecord) {
TotalFinanceRecord = totalFinanceRecord;
}
public String getCohort() {
return cohort;
}
public void setCohort(String cohort) {
this.cohort = cohort;
}
public void initStudent() {
}
public void print() {
System.out.print("Student name: " + student_name + " ");
System.out.print("\nMatric No: " + studentID + " ");
System.out.print("\nAge: " + student_age + " ");
System.out.print("\nCurrent Semester: " + currentSemester + " ");
System.out.print("\nCohort: " + cohort + " ");
System.out.println();
}
}
Please help me fix my code I would appreciate it so much.
This is my lab assignment which needs to be submitted by tomorrow.
You could try this, but it's also better to review standard java concepts (arrays, classes, etc). After, just adapt your code as suitable.
public class Finance extends Student
{
public static void main(String args[])
{
Finance f1 = new Finance("Student_1");
System.out.println(f1);
f1.setPayment(1, 10);
System.out.println(f1);
f1.setPayment(2, 10.77);
System.out.println(f1);
Student s2 = new Student("Student 2");
Finance f2 = new Finance(s2);
f2.setPayment(2, 88.77);
System.out.println(f2);
}
Double finaceRecord[] = new Double[3];
private void initPayment()
{
for(int i=0;i<finaceRecord.length;i++)
{
finaceRecord[i]=0.0;
}
}
public Finance(Student s)
{
super(s.name);
initPayment();
}
public Finance(String name)
{
super(name);
initPayment();
}
//store first or second
public void setPayment(int i, double d)
{
if(d<=0) return;
if(i==1)
{
finaceRecord[i] = d;
}
else
{
finaceRecord[2] = d;
}
finaceRecord[0] = finaceRecord[2] + finaceRecord[1];
}
public String toString()
{
return "name="+super.name+", Total Paid="+finaceRecord[0]+","
+ " Sem1="+finaceRecord[1]+", Sem2="+finaceRecord[2];
}
}
...
public class Student
{
String name;
int Semester;
Student(String name)
{
this.name = name;
this.Semester = 1;
}
}
Ouptut
name=Student_1, Total Paid=0.0, Sem1=0.0, Sem2=0.0
name=Student_1, Total Paid=10.0, Sem1=10.0, Sem2=0.0
name=Student_1, Total Paid=20.77, Sem1=10.0, Sem2=10.77
name=Student 2, Total Paid=88.77, Sem1=0.0, Sem2=88.77
from what I understand you are supposed to create an array of Finance type
Finance []financeRecord = new Finance[totalFinanceRecord];
and then you can access the values of Finance class
financeRecord[indexNumber].methodName();
I'm learning java language and I saw this code. I was wondering if I can add an if else condition that if the grade is below 80, it will print failed and else passed. Like.
System.out.print("Your Grade is ");
if(avg>80)
{
System.out.print("A");
I searched for other links but I can't find anything. I hope someone can help me. Thanks in advance.
import java.util.*;
public class UserInteraction {
public static void main(String[] args) {
UserChoiceManager userChoiceManager = new UserChoiceManager();
UserChoice choice = UserChoice.UNKNOWN;
do {
choice = userChoiceManager.manage();
} while (choice != UserChoice.EXIT);
System.out.println("Thank you for using the system!");
}
}
enum UserChoice {
UNKNOWN(0),
ENTER_SUBJECT(1),
DISPLAY_DATA(2),
CALCULATE_AVERAGE_GRADE(3),
EXIT(4);
private int id;
public int getId() {
return id;
}
UserChoice(int id) {
this.id = id;
}
public static UserChoice getById(int input) {
for (UserChoice value : UserChoice.values()) {
if (value.getId() == input) {
return value;
}
}
return UserChoice.UNKNOWN;
}
}
class Subject {
private String name;
private int grade;
public Subject(String name, int grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
class UserChoiceManager {
private final static int SUBJECT_COUNT = 3;
private Subject[] subjects = new Subject[SUBJECT_COUNT];
private Scanner scan = new Scanner(System.in);
public UserChoiceManager() {
}
public UserChoice manage() {
System.out.println(printHelp());
UserChoice choice = getUserChoiceById(scan);
if (choice == UserChoice.ENTER_SUBJECT) {
choice = enterSubjects(choice);
}
if (choice == UserChoice.DISPLAY_DATA) {
printSubjectsAndGrades();
}
if (choice == UserChoice.CALCULATE_AVERAGE_GRADE) {
printAverageGrade();
}
return choice;
}
private static String printHelp() {
StringBuilder usage = new StringBuilder("\nUsage:\n");
usage.append(UserChoice.ENTER_SUBJECT.getId()).append(". Enter a subject name and a corresponding grade").append("\n");
usage.append(UserChoice.DISPLAY_DATA.getId()).append(". Display all grades").append("\n");
usage.append(UserChoice.CALCULATE_AVERAGE_GRADE.getId()).append(". Calculate the average grade").append("\n");
usage.append(UserChoice.EXIT.getId()).append(". Exit system");
return usage.toString();
}
private UserChoice getUserChoiceById(Scanner scan) {
return UserChoice.getById(scan.nextInt());
}
private UserChoice enterSubjects(UserChoice choice) {
System.out.println("Enter " + subjects.length + " subjects and their corresponding grades:");
System.out.println();
for (int i = 0; i < subjects.length; i++) {
String subjectName = scanSubjectName();
int grade = scanGrade();
subjects[i] = new Subject(subjectName.toLowerCase(), grade);
}
System.out.println("Thank you!");
System.out.println();
return choice;
}
private String scanSubjectName() {
Scanner temp = new Scanner(System.in);
String subjectName = "";
do {
System.out.println("Subject:");
subjectName = temp.nextLine();
if (subjectName.equals("")) {
System.out.println("Empty subject name! Try again.");
}
} while (subjectName.equals(""));
return subjectName;
}
private int scanGrade() {
int grade = 0;
do {
Scanner temp = new Scanner(System.in);
System.out.println("Grade:");
try {
grade = temp.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid grade. Enter numeric value! Try again.");
}
} while (grade == 0);
return grade;
}
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
System.out.println("Your average grade is: " + getAverage(subjects));
System.out.println();
}
private void printSubjectsAndGrades() {
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for (int p = 0; p < subjects.length; p++) {
System.out.println(subjects[p].getName() + "\t" + "\t" + subjects[p].getGrade());
}
}
public static double getAverage(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects)
sum += s.getGrade();
return ((double) sum) / subjects.length;
}
public static double getSum(Subject[] subjects) {
int sum = 0;
for (Subject s : subjects) {
sum += s.getGrade();
}
return sum;
}
}
I tried adding some if functions in print out tag but it's not working.
Change your implementation of printAverageGrade to this, and the program will print out what you want:
private void printAverageGrade() {
System.out.println("Total of grades: " + getSum(subjects));
System.out.println("Count of grades: " + subjects.length);
double average = getAverage(subjects);
System.out.println("Your average grade is: " + average);
System.out.print("Your Grade is ");
if (average > 80) {
System.out.println("A");
} else {
System.out.println("Failed");
}
System.out.println();
}
I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?
The search function:
public static int studentFinder(ClassSection classOne) {
int studentIndex = 0;
boolean searchAgain = false;
boolean correctStudent = false;
do {
studentIndex = idFinder(classOne);
if (studentIndex == -1) {
System.out.println("That student was not found in the class");
System.out.println("Would you like to search again?");
searchAgain = yesNoBool();
} else {
System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
System.out.println("Is this correct?");
correctStudent = yesNoBool();
if (!correctStudent) {
System.out.println("Would you like to search again?");
searchAgain = yesNoBool();
}
}
} while(searchAgain);
return studentIndex;
}
ID Finder module:
public static int idFinder(ClassSection classOne) {
int studentID = 0;
String intString = "a Student ID to search for:";
int studentIndex = 0;
System.out.println("Please enter a Student ID to search for:");
studentID = intChecker(intString);
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
} else if (studentIdTest != studentID){
studentIndex = -1;
}
}
return studentIndex;
}
The ClassSection class:
import java.util.*;
public class ClassSection {
//instance variables
protected int crnNum = 0;
protected String deptCode = "null";
protected int courseNum = 0;
protected String instructMode = "null";
protected String meetingDays = "null";
protected String meetingTimesStart = "null";
protected String meetingTimesEnd = "null";
protected int classCapacity = 0;
protected int classEnrollment = 0;
protected int instructorID = 0;
protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();
//constructors
public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
int instructorID) {
super();
this.crnNum = crnNum;
this.deptCode = deptCode;
this.courseNum = courseNum;
this.instructMode = instructMode;
this.meetingDays = meetingDays;
this.meetingTimesStart = meetingTimesStart;
this.meetingTimesEnd = meetingTimesEnd;
this.classCapacity = classCapacity;
this.classEnrollment = classEnrollment;
this.instructorID = instructorID;
}
public ClassSection() {
super();
this.crnNum = 0;
this.deptCode = "";
this.courseNum = 0;
this.instructMode = "";
this.meetingDays = "";
this.meetingTimesStart = "";
this.meetingTimesEnd = "";
this.classCapacity = 0;
this.classEnrollment = 0;
this.instructorID = 0;
}
//getters and setters
public void getStudents() {
this.students.forEach(System.out::println);
}
public int getStudentIDByIndex(int index) {
return this.students.get(index).getStudentID();
}
public void addStudent(StudentEnrollee student) {
this.students.add(student);
}
public void removeStudent(int removalIndex) {
this.students.remove(removalIndex);
}
public void changeAddStudentGrade(int studentIndex, int studentGrade) {
this.students.get(studentIndex).setStudentGrade(studentGrade);
}
public int getCrnNum() {
return crnNum;
}
public void setCrnNum(int crnNum) {
this.crnNum = crnNum;
}
public String getDeptCode() {
return deptCode;
}
public void setDeptCode(String deptCode) {
this.deptCode = deptCode;
}
public int getCourseNum() {
return courseNum;
}
public void setCourseNum(int courseNum) {
this.courseNum = courseNum;
}
public String getInstructMode() {
return instructMode;
}
public void setInstructMode(String instructMode) {
this.instructMode = instructMode;
}
public String getMeetingDays() {
return meetingDays;
}
public void setMeetingDays(String meetingDays) {
this.meetingDays = meetingDays;
}
public String getMeetingTimesStart() {
return meetingTimesStart;
}
public void setMeetingTimesStart(String meetingTimesStart) {
this.meetingTimesStart = meetingTimesStart;
}
public String getMeetingTimesEnd() {
return meetingTimesEnd;
}
public void setMeetingTimesEnd(String meetingTimesEnd) {
this.meetingTimesEnd = meetingTimesEnd;
}
public int getClassCapacity() {
return classCapacity;
}
public void setClassCapacity(int classCapacity) {
this.classCapacity = classCapacity;
}
public int getClassEnrollment() {
return classEnrollment;
}
public void setClassEnrollment(int classEnrollment) {
this.classEnrollment = classEnrollment;
}
public int getInstructorID() {
return instructorID;
}
public void setInstructorID(int instructorID) {
this.instructorID = instructorID;
}
//mutators
#Override
public String toString() {
return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
+ " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
+ " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
meetingTimesStart, meetingTimesEnd, instructorID);
}
}
The student enrollee class (where the objects in the arraylist are from):
public class StudentEnrollee {
protected int studentID = 0;
protected int studentGrade = 0;
public StudentEnrollee() {
super();
studentID = 0;
studentGrade = 0;
}
public StudentEnrollee(int studentID, int studentGrade) {
super();
this.studentID = studentID;
this.studentGrade = studentGrade;
}
//setters & getters
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public int getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(int studentGrade) {
this.studentGrade = studentGrade;
}
#Override
public String toString() {
return String.format("Student ID: %20s \nStudent Grade: %20s \n", studentID, studentGrade);
}
}
The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:
public static int intChecker(String object) {
boolean correctInput = false;
int userInput = 0;
while (!correctInput) {
try {
userInput = scanner.nextInt();
correctInput = true;
} catch(InputMismatchException e) {
System.out.println("I'm sorry, that doesn't seem to be a number");
System.out.println("Please enter " +object);
scanner.next();
}
}
return userInput;
}
public static boolean yesNoBool() {
String yesNo = "";
boolean yesNoBool = false;
System.out.println("Please enter Y/N");
yesNo = scanner.next();
while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
System.out.println("I'm sorry, please enter Y/N");
yesNo = scanner.next();
}
if (yesNo.equalsIgnoreCase("y")) {
yesNoBool = true;
} else if (yesNo.equalsIgnoreCase("n")) {
yesNoBool = false;
}
return yesNoBool;
}
Once you found the match you have to break the loop, otherwise studentIndex gets overwritten for rest of the records for which loop iterating. Also you don't need if(studentIdTest != studentID) just else is also work same.
Add Break in loop in idFinder method as follows:
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
break;
} else{
studentIndex = -1;
}
}
Suggestion: you can intialize studentIndex with -1 instead of setting it in each iteration where match not found.
I hope this will solve your problem.
In your idFinder method, you continue to search for the id even when you find it. In the for loop, you need to stop when you find the id.
Modify your for loop to:
public static int idFinder(ClassSection classOne) {
String intString = "a Student ID to search for:";
int studentIndex = -1; // Initialize the studentIndex to a negative value since 0 is a valid index
System.out.println("Please enter a Student ID to search for:");
int studentID = intChecker(intString);
for (int i = 0; i < classOne.students.size(); i++) {
int studentIdTest = classOne.students.get(i).getStudentID();
if (studentIdTest == studentID) {
studentIndex = i;
break;
}
}
return studentIndex;
}
I have the following code and I want to ask the user after an name that's already stored in the Arraylist and increase that (dogs) age by +1.
Here's the most important (I guess) part of the code. This is the Register Class.
import java.util.Scanner;
import java.util.ArrayList;
public class Register {
private Scanner keyboard = new Scanner(System.in);
private ArrayList<Dog> dogs = new ArrayList<>();
private String readString() {
return keyboard.nextLine();
}
public int readInt() {
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
}
public double readDouble() {
double d = keyboard.nextDouble();
keyboard.nextLine();
return d;
}
public void registrateDog(){
System.out.println("Dogs name: ");
String name = readString();
System.out.println("Dogs breed: ");
String breed = readString();
System.out.println("Dogs age: ");
int age = readInt();
System.out.println("Dogs weight: ");
double weight = readDouble();
Dog newDog = new Dog(name, breed, age, weight);
dogs.add(newDog);
System.out.println(newDog.toString() + " is added");
}
public void increaseAge(){ //Here's the problem
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
private void exitProgram(){
System.out.println("Goodbye!");
keyboard.close();
}
private void run(){
setUp();
runCommandLoop();
exitProgram();
}
public static void main(String[] args){
new Register().run();
//setUp();
}
}
And
public class Dog {
private String name;
private String breed;
private int age;
private double weight;
private double tailLenght;
private String tax = "tax";
public Dog(String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
if (breed.equals(tax)) {
this.tailLenght = 3.7;
} else {
this.tailLenght = (age*weight) / 10;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed(){
return breed;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int newAge(){
return age = age + 1;
}
public double getWeight(){
return weight;
}
public double getTailLenght(){
return tailLenght;
}
public String toString()
{ return String.format("%s, %s, %d years old, %.1f kg, "
+ "tail lenght %.1f cm", name, breed, age, weight, tailLenght);
}
}
So in this code you're finding the Dog by its name. Which is great.
public void increaseAge() {
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
Inside of your Dog class you have a method which returns the age, what you want to do is modify it to:
public int newAge(){
this.age++; // This will take the current age of the dog and add one to it
}
Now going back to the increaseAge() method you want to modify the for loop to look like:
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
dogs.get(i).newAge(); // This will update the Dogs age by 1 year
System.out.println("Dog " + dogs.get(i).getName() + " is now " + dogs.get(i).getAge());
return;
}
Where are you incrementing the age ? Call the newAge() method as you have defined in the Dog class.`
Dog dog = dogs.get(i);
dog.setAge(dog.newAge());
dogs.set(i,dog);`
We've fetched the particular dog who's details matched. Then we incremented it's age and set it back in the list at that position.
I am writing a Java program that I need:
A method to read the customer names and id and store them in an array. (Read a sequence of zero or more lines each containing the name and id of one customer. Instantiate one Customer object per line and store each object in an array of objects. The array need not be more than 10 elements long. The sequence of name and id will end with an empty line).
Main
import java.util.Scanner;
public class CustomerTest {
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
int numItem;
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
int numItem = 0;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
} else {
input[numItem] = name; //error
input[numItem] = id; //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i <numItem && !found) { //error
if (customers[i].equals(id)) { //error
changeBalance(double value);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(customers[i].toString()); //error
}
}
}
Can you please check if this works.
I dont know whether I understood your question.And I just cleared the error.
public class CustomerTest {
static int numItem = 0;
public static void main(String[] args) {
Customer[] customers = new Customer[10];
Scanner myScanner = new Scanner(System.in);
readCustomer(myScanner, customers); //not sure about this calling
readNameAmount(myScanner, customers); ////not sure about this calling
}
public static void readCustomer(Scanner myScanner, Customer[] input) {
boolean streamEnded = false;
while (!streamEnded && myScanner.hasNext()) {
String name = myScanner.nextLine();
String id = myScanner.nextLine();
if (name.length() == 0 && id.length() == 0) {
streamEnded = true;
}
else {
input[numItem].getName();
input[numItem].getId(); //error
}
numItem++;
Customer customerTest = new Customer(name, id);
}
}
public static void readNameAmount(Scanner myScanner, Customer[] input) {
while (myScanner.hasNext()) {
String id = myScanner.nextLine();
Customer cust = new Customer();
double amount = myScanner.nextDouble();
int i = 0;
boolean found = false;
while (i < numItem && !found) { //error
if (input[i].equals(id)) { //error
cust.changeBalance(amount);//error
}
found = true;
i++;
}
}
}
public static void print(Customer[] input, int numItem) {
for (int i = 0; i < numItem; i++) {
System.out.println(input[i].toString()); //error
}
}
}
Let me know your thoughts.
Customer.java
public class Customer {
private String name;
private String id;
private double balance;
public Customer(){
}
public Customer(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public void changeBalance(double value) {
balance = balance + value;
}
public String toString() {
return "name " + name + " id " + id + " balance " + balance;
}
}