Print out customer name, id, balance - java

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

Related

Program only reading title of file and nothing else

My program is only reading the name of the file and none of the contents inside. I get an ElementDoesNotExist error every time. The file is in the same folder, and I have no idea why it won't read the contents. I understand that this program is inefficient, and it's my first time using File IO in Java.
import java.util.*;
import java.io.*;
public class Project4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: ");
int fileYear = input.nextInt();
String userFile = "";
if (fileYear == 2001)
{
userFile = "BabyNames2001.txt";
}
else if (fileYear == 2002)
{
userFile = "BabyNames2002.txt";
}
else if (fileYear == 2003)
{
userFile = "BabyNames2003.txt";
}
else if (fileYear == 2004)
{
userFile = "BabyNames2004.txt";
}
else if (fileYear == 2005)
{
userFile = "BabyNames2005.txt";
}
else if (fileYear == 2006)
{
userFile = "BabyNames2006.txt";
}
else if (fileYear == 2007)
{
userFile = "BabyNames2007.txt";
}
else if (fileYear == 2008)
{
userFile = "BabyNames2008.txt";
}
else if (fileYear == 2009)
{
userFile = "BabyNames2009.txt";
}
else if (fileYear == 2010)
{
userFile = "BabyNames2010.txt";
}
File theFile = new File(userFile);
ArrayList<BabyName> theBabies = loadNames("BabyNames2001.txt", fileYear);
System.out.print("Enter the gender: ");
String babyGender = input.next();
System.out.print("Enter the name: ");
String babyName = input.next();
findName(babyName, fileYear, theBabies);
}
private static ArrayList<BabyName> loadNames(String fileName, int checkYear)
{
ArrayList<BabyName> babies = new ArrayList<BabyName>();
int currentYear = checkYear;
String chooseFile = fileName;
Scanner reader = new Scanner(chooseFile);
while (reader.hasNext())
{
BabyName boy = new BabyName();
BabyName girl = new BabyName();
boy.setYear(currentYear);
girl.setYear(currentYear);
boy.setGender("M");
girl.setGender("F");
String currentRank = reader.next();
boy.setRank(currentRank);
String boyName = reader.next();
int boyTotal = reader.nextInt();
String girlName = reader.next();
int girlTotal = reader.nextInt();
girl.setRank(currentRank);
boy.setName(boyName);
girl.setName(girlName);
boy.setTotal(boyTotal);
girl.setTotal(girlTotal);
babies.add(boy);
babies.add(girl);
}
return babies;
}
private static BabyName findName(String name, int year, ArrayList<BabyName> babies)
{
ArrayList<BabyName> theBabies = babies;
BabyName tempBaby = new BabyName();
String findName = name;
int findYear = year;
for (int baby = 0; baby < 2000; baby++)
{
if (findName == theBabies.get(baby).getName())
{
tempBaby = theBabies.get(baby);
}
}
return tempBaby;
}
}
class BabyName
{
private String rank;
private int year;
private String name;
private String gender;
private int total;
BabyName()
{
}
public String getRank()
{
return rank;
}
public int getYear()
{
return year;
}
public String getName()
{
return name;
}
public String getGender()
{
return gender;
}
public int getTotal()
{
return total;
}
public void setRank(String newRank)
{
this.rank = newRank;
}
public void setYear(int newYear)
{
this.year = newYear;
}
public void setName(String newName)
{
this.name = newName;
}
public void setGender(String newGender)
{
this.gender = newGender;
}
public void setTotal(int newTotal)
{
this.total = newTotal;
}
}
Your problem is here:
Scanner reader = new Scanner(chooseFile);
The Scanner class has multiple overloaded constructors. chooseFile is a String, so you are calling Scanner(String) when what you probably want is Scanner(File). Because of this your code does not read any files, it is reading the literal string "BabyNames2001.txt".
The solution is to simply pass a File instead of a String, or something along the lines of:
Scanner reader = new Scanner(new File(chooseFile));

How to sort content of a csv file in java

I have a big csv file that looks like this
Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology
I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far
package project1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
int choice=0;
boolean flag = true;
while (flag) {
System.out.println("Enter 1 to display data.");
System.out.println("Enter 2 to sort data.");
System.out.println("Enter 3 to idk.");
System.out.println("Enter 0 to exit.");
System.out.print("Your choice: ");
choice = input.nextInt();
if (choice ==1) {
File inputFile = new File("dataToLoad.csv");
String line;
String delimiter = ",";
Scanner in = new Scanner(inputFile);
int numberOfLines = 0;
int numberOfColumns = 0;
while (in.hasNextLine()){
line = in.nextLine();
numberOfLines++;
}
in.close();
String[][] data = new String[numberOfLines][8];
in = new Scanner(inputFile);
int currentRow = 0;
while (in.hasNextLine()){
line = in.nextLine();
String[] parts = line.split(delimiter);
numberOfColumns = parts.length;
for (int i = 0; i<numberOfColumns; i++) {
data[currentRow][i] = parts[i];
}
currentRow++;
}
in.close();
System.out.println(Arrays.deepToString(data));
for (int row=0; row<numberOfLines; row++) {
for (int col=0; col<numberOfColumns; col++) {
System.out.printf("%-20s", data[row][col]);
}
System.out.println();
}
}
else {
if (choice ==2) {
}
else
if (choice==0) {
System.out.println("Good bye!");
flag = false;
}
else System.out.println("I am sorry, this is not a valid option. Please try again.");
}
}
}
}
As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.
Stop reinventing the wheel; use a csv open source library (for example, opencsv).
Create a class that represents one row of data in your csv file; I'll refer to this as RowClass.
Read the CSV file one row at a time. Each row will arrive as a String[].
Create and populate one instance of RowClass per row of the CSV file.
Store the RowClass objects in a List; I'll call this rowList.
Sort rowList using a Comparator that you create. Create one Comparator for each sort option.
Implement RowClass.toString() to display one row.
This should help, I believe that you will figure out what's going on here
Main.java
package pkg;
import java.util.Arrays;
import static pkg.Order.OrderBuilder;
public class Main {
private static Order[] orders = new Order[3];
private static OrderBuilder orderBuilder = new OrderBuilder();
public static void main(String[] args) {
Order order1 = orderBuilder.createNewOrder().withId(10).withCustomerName("John").withPrice(1.23f).withPriority("high").build();
Order order2 = orderBuilder.createNewOrder().withId(20).withCustomerName("Lee").withQuantity(3.4f).build();
Order order3 = orderBuilder.createNewOrder().withId(30).withCustomerName("Someone").withPriority("low").build();
orders[0] = order3;
orders[1] = order1;
orders[2] = order2;
System.out.println("Before sorting");
for(int i = 0; i < orders.length; i++) {
System.out.println(orders[i].getId());
}
Arrays.sort(orders);
System.out.println("After sorting");
for(int i = 0; i < orders.length; i++) {
System.out.println(orders[i].getId());
}
}
}
Order.java
package pkg;
public class Order implements Comparable<Order> {
private int id;
private String priority;
private float quantity;
private float price;
private String shipMode;
private String customerName;
private String customerSegment;
private String productCategory;
private void setId(int id) {
this.id = id;
}
int getId() {
return this.id;
}
private void setPriority(String priority) {
this.priority = priority;
}
private void setQuantity(float quantity) {
this.quantity = quantity;
}
private void setPrice(float price) {
this.price = price;
}
private void setShipMode(String shipMode) {
this.shipMode = shipMode;
}
private void setCustomerName(String customerName) {
this.customerName = customerName;
}
private void setCustomerSegment(String customerSegment) {
this.customerSegment = customerSegment;
}
private void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
#Override
public int compareTo(Order o) {
return this.id - o.getId();
}
static class OrderBuilder {
private Order order;
OrderBuilder withId(int id) {
order.setId(id);
return this;
}
OrderBuilder withPriority(String priority) {
order.setPriority(priority);
return this;
}
OrderBuilder withQuantity(float quantity) {
order.setQuantity(quantity);
return this;
}
OrderBuilder withPrice(float price) {
order.setPrice(price);
return this;
}
OrderBuilder withShipMode(String shipMode) {
order.setShipMode(shipMode);
return this;
}
OrderBuilder withCustomerName(String customerName) {
order.setCustomerName(customerName);
return this;
}
OrderBuilder withCustomerSegment(String customerSegment) {
order.setCustomerSegment(customerSegment);
return this;
}
OrderBuilder withProductCategory(String productCategory) {
order.setProductCategory(productCategory);
return this;
}
OrderBuilder createNewOrder() {
order = new Order();
return this;
}
Order build() {
return order;
}
}
}

Searching an arraylist for the index of an object with a specific value

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

Java Object Array printing null?

I have 3 classes, Movie which is used to add Movie objects to an in MovieDatabase but it keeps printing null.
When I add 2 Movies its like the first Movie is erased and it prints null instead. Also is there a way to check if the position in the array is empty and not print if it is empty?
Here is my Movie class
public class Movie {
private String name;
private String director;
private double fileSize;
private int duration;
private int moviecount;
public Movie()
{
name = null;
director = "";
fileSize = 0;
duration = 0;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDirector(String newDirector)
{
director = newDirector;
}
public String getDirector()
{
return director;
}
public void setfileSize(double newfileSize)
{
fileSize = newfileSize;
}
public double getfileSize()
{
return fileSize;
}
public void setDuration(int newDuration)
{
duration = newDuration;
}
public int getDuration()
{
return duration;
}
and here my MovieDatabase class:
public class MovieDatabase
{
private Movie[] mov;
private int i;
public int count=0;
public MovieDatabase()
{
mov = new Movie[4];
i=0;
}
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
public void printNames()
{
for (int i = 0; i < mov.length; i++)
{
System.out.println(mov[i].getName());
}
}
}
import java.util.*;
public class Interface {
Scanner console = new Scanner(System.in);
MovieDatabase m = new MovieDatabase();
private void run()
{
int option;
do{
System.out.print("Add Movie(0), Delete Movie(2),Show Movies(3),Movie Count(4) \n");
option = console.nextInt();
switch(option)
{
case 0: addMovie();
break;
case 3: printMovies();
break;
}
}
while(option!=9);
}
public static void main(String[] args){
Interface intFace = new Interface();
intFace.run();
}
public void addMovie()
{
String name, director;
double fileSize;
int duration;
System.out.println("Movie Name: ");
name = console.next();
System.out.println("Movie Director: ");
director = console.next();
System.out.println("Movie File Size: ");
fileSize = console.nextDouble();
System.out.println("Movie Duration: ");
duration = console.nextInt();
System.out.print("Movie Added!");
m.addData(name,director,fileSize,duration);
}
public void printMovies()
{
m.printNames();
}
}
I tried to include only the relevant parts but majority of what I have done so far is relevant.
The problem is in these lines
....
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
...
Each and every time you're adding a new data, you're erasing all previous records by assigning new movie object to every element in array. This erases all previous data.
You should instead move these 2 lines in MovieDatabase constructor. Or a better option would be to initialize them when you're setting data.
...
public void addData(String name, String director, double fileSize, int duration)
{
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i] = new Movie(); //++ edit
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
...
Also is there a way to check if the position in the array is empty and not print if it is empty?
You can create a method in Movie class which checks whether this movie object is empty or not and returns appropriate result.
public class Movie {
...
...
public boolean isEmpty() {
if(
this.name.isEmpty() &&
this.director &&
this.fileSize == 0 &&
this.duration == 0 &&
this.moviecount == 0
)
return true;
else
return false;
}
...
...
}
Now you can check whether this movie object is empty or not using:
if(mov[i].isEmpty()) {
//empty movie object
...
}
In setData you always set the value of mov[0]. The class member i will never change (loop variable hides it). You do not use the parameter m to set the data.
Change your setData to
m.setName(name);
m.setDirector(director);
m.setfileSize(fileSize);
m.setDuration(duration);

Stuck after trying to false check after getter method

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
}
}}

Categories

Resources