Integer.toString(argument) or toString(argument) - java

I've written up some code for a Credit card class, pasted below. I have a constructor that takes in the said variables, and am working on some methods to format these variable's into strings such that the end output will be something along the lines of
Number: 1234 5678 9012 3456
Expiration date: 10/14
Account holder: Bob Jones
Is valid: true
(Won't format correctly - I'm unsure how to do it, would be greatful of someone can edit for me :) )
My question is, in the line
String shortYear = Integer.toString(expiryYear).substring(2,4);
Why won't the following work:
toString(argument).substring(2,4)
I would have imagined it wound have worked (expiryYear is essentially declared as an instance variable of type int). I've consulted my book (The official Java Tutorial also found online), and can't seem to find anything. I didn't even know about Integer.toString, a friend told me about that after trying to play with toString(), so it would be even more greatly appreciated if someone could also tell me where I can find these sorts of methods (I don't think they're in my book)
public class CreditCard {
private int expiryMonth;
private int expiryYear;
private String firstName;
private String lastName;
private String ccNumber;
public CreditCard(int expiryMonth, int expiryYear, String firstName, String lastName, String ccNumber) {
this.expiryMonth = expiryMonth;
this.expiryYear = expiryYear;
this.firstName = firstName;
this.lastName = lastName;
this.ccNumber = ccNumber;
}
public String formatExpiryDate() {
String shortYear = Integer.toString(expiryYear).substring(2, 4);
String expiryDate = expiryMonth + "/" + shortYear;
return expiryDate;
}
public static void main(String[] args) {
CreditCard cc1 = new CreditCard(10, 2014, "Bob", "Jones", "1234567890123456");
System.out.print(cc1.formatExpiryDate());
}
}

Try String.valueOf(expiryYear).substring(2,4)

Related

Why can't I access the Object's properties from another class? (even when the Object was passed to the class that is trying to access the properties)

I hope you are able to help me.
My question is:
When passing an instance of an object that is in an arraylist, and I pass that arraylist to another class, how do I access it's atributes?
I can access the attributes before passing it to another class.
The "Main" class, passes on the data, to the "Employees" class.
Employees employees = new Employees();
employees.addEmployee("Orlando", "Silva", 111111111, "St. King's Street", 111111111, 11111111111111L, employees.getMinimumWage(), employees.getDayShift());
employees.addEmployee("Rui", "Guilherme", 111111111, "St. King's Street", 111111111, 11111111111111L, employees.getMinimumWage(), employees.getNightShift());
employees.addEmployee("Marco", "Alberto", 111111111, "St. King's Street", 111111111, 11111111111111L, employees.getMinimumWage(), employees.getNightShift());
The "Employees" class receives the data, adds it to an array, and from that array goes to the "AllStaff" class
Notice, that I have access to the atributes, in the method "addToAllStaff()"
public class Employees {
// Atributes
public String name;
private String lName;
private int nID;
private String address;
private int phNum;
private long nSocialSecNum;
private double minimumWage = 740.83;
private double employeeWage;
private String dayShift = "Day shift", afternoonShift = "Afternoon shift", nightShift = "Night shift";
private String shift;
private ArrayList<Employees> employeesArrayList = new ArrayList<Employees>();
private AllStaff allStaff = new AllStaff();
//---------------------
// Constructors
public Employees(){
}
public Employees(String name, String lName, int nID, String address, int phNum, long nSocialSecNum, double minimumWage, String shift){
this.name = name;
this.lName = lName;
this.nID = nID;
this.address = address;
this.phNum = phNum;
this.nSocialSecNum = nSocialSecNum;
this.employeeWage = minimumWage;
this.shift = shift;
//----------------
extraWage();
}
//---------------------
public void addEmployee(String name, String lName, int nID, String address, int phNum, long nSocialSecNum, double minimumWage, String shift){
Employees employee = new Employees(name, lName, nID, address, phNum, nSocialSecNum, minimumWage, shift);
employeesArrayList.add(employee);
addToAllStaff();
}
void addToAllStaff(){
System.out.println("(Class Employees) employees size: " + employeesArrayList.size());
for (int i = 0; i < employeesArrayList.size(); i++){
System.out.println("Employee names: " + employeesArrayList.get(i).getName());
System.out.println("Employee names: " + employeesArrayList.get(i).name);
}
allStaff.addEmployees(employeesArrayList);
}
}
In the class "AllStaff", is where I don't have access to the attributes
public class AllStaff {
static ArrayList <AllStaff> employeesArrayList;
public AllStaff(){
}
public void addEmployees(ArrayList listOfEmployees){
System.out.println("List of employees size: " + listOfEmployees.size());
for (int i = 0; i < listOfEmployees.size(); i++){
System.out.println("Employee names: " + listOfEmployees.get(i).getName());
System.out.println("Employee names: " + listOfEmployees.get(i).name);
}
this.employeesArrayList = listOfEmployees;
}
For the whole code, please visit this link: https://github.com/OrlandoVSilva/test-to-github/tree/master/test-to-github/src/mercado
I hope this question has everything you need.
Thanks
When using a List (or any object that can be generic), it's a good practice to specify the type of List you're dealing with. In your case, the method addEmployees(ArrayList listOfEmployees) takes in parameter an ArrayList, which could be an ArrayList of literally any object. It could be an ArrayList of Employees, Strings, Integers, whereas you just want it to be an ArrayList of Employees.
the solution is to change your ArrayList into a ArrayList<Employees> listOfEmployees
public void addEmployees(ArrayList<Employees> listOfEmployees){
System.out.println("List of employees size: " + listOfEmployees.size());
for (int i = 0; i < listOfEmployees.size(); i++){
System.out.println("Employee names: " + listOfEmployees.get(i).getName());
//The above should work just fine :)
System.out.println("Employee names: " + listOfEmployees.get(i).name);
//This one will work too as the "name" attribute is public but as you have a getName() method, you probably should make it private :D.
}
this.employeesArrayList = listOfEmployees;
}
To explain it quickly without too much details, when you're using a List object, you must specify the List's type by putting <> around it. If you don't, the default type is Object which is the parent of every types in java.
Also, i guess your static ArrayList <AllStaff> employeesArrayList; is meant to be your list of employees. So replacing it with static ArrayList <Employees> employeesArrayList; seems to be what you want to do :D
You missed generics type in AllStuffs addEmployees() method argument. That is the problem. It should be like this:
public void addEmployees(ArrayList<Employees> listOfEmployees){

Print ArrayList from another Class

Evening everyone,
I am writing a code to allow students to search for internships. I have a class for Semesters, a class for Students(where student input is taken and stored into an ArrayList and the actual iSearch class. My code is basically doing everything I need it to do, except I have hit a brain block in trying to figure out the best way to output my ArrayList from the Student class out at the end of my program in the iSearch Class.
I am fairly new to Java, so if I haven't explained this correctly please let me know. I am trying to get the ArrayList's of student information to output at the end of the while loop in the iSearch Class.....so
To make this easy. Is it possible to print an Arraylist from another class.
A better way to solve this is to create a Student object for each student. In your current class the ArrayLists you are creating are deleted after every method call, since it is not referenced anymore.
Here is how I would do it:
Student Class:
public class Student {
String firstName;
String lastName;
String interest;
public Student(String firstName, String lastName, String interest) {
this.firstName = firstName;
this.lastName = lastName;
this.interest = interest;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getInterest() {
return interest;
}
}
In your iSearch class you create an ArrayList of students, which lets you add your students:
ArrayList<Student> students = new ArrayList<Student>();
do {
String firstName = input.next();
String lastName = input.next();
String interest = input.next();
students.add(new Student(firstName, lastName, interest));
} while (YOUR_CONDITION);
Then you can display each student by iterating through the ArrayList and accessing the getter and setter methods:
students.foreach(student -> {
System.out.println(student.getFirstName());
System.out.println(student.getLastName());
System.out.println(student.getInterest());
});
Editing this a little will help you to solve your problem, but this is the basic solution.

How to reconstruct a name with a split String in Java?

First some info about my project,
I'm following a tutorial task where the main goal is to learn to work with error handling,
but I'm not at that part quite yet, I am working with establishing the main classes.
Thats what I need a little help and guidance with,(but errors are supposed to come up and be detected
so that I can learn to fix them later, but that's not the main question here, just information.)
Here's 3 of the classes which I've completed.
Student with two private fields: Name name and CourseCollection course.
Name with two fields String firstName and String surname.
CourseCollection with ArrayList courses.
(Info: Later, I will work with class UserDatabase to collect and load a collection of students,
+ class DatavaseFormatException which will represent errors, but I think it would be easier to finish those 3 classes above first? Correct me if
I'm wrong.)
QUESTION:I need a little help with class Name, I don't think my work is correct.
My main issue is with the method String encode, and constructor Name(String encodedIdentity)
where I want to return the names, split by a ;. Here's what I have
enter code here
public class Name
//instanciating the persons first and last name as Strings.
private String firstName;
private String surname;
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
//Here, the name is supposed to be coded as a text value, with the first
//and last names split with a ;
this.encodedIdentity=encodedIdentity;
//I am getting my first error here
}
//getters for firstname and surname here
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
//Could I use a split String here? If so how?
return firstName + ";" + surname;
}
}
I can guarantee I will need further help with my work. Thanks in advance, I find
people on StackOverflow to be very helpful as I don't have anyone (other than my books)
to ask for help. (I know you guys are not free teachers. But if anyone would voulenteer to help me outside of this I would highly appreciate it.
(Sorry if that's not allowed to ask for!))
EDIT: Thanks to you guys, my class is now compiling. I am not sure how to test it yet, but this is what I have now. Does it look correct?
public class Name
{
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
String names = firstName + surname;
String[] fullname = names.split( "\\;");
if(fullname.length != 2 )
{
System.out.println(fullname);
}
}
/**
* Getting the firstname of the person
* #return firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* Getting the surname of the person
* #return surname
*/
public String getSurname()
{
return surname;
}
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
String encode = (firstName + ";" + surname);
return encode;
}
}
If you are given an "encoded id", split it to get the names:
public Name(String encodedIdentity){
String[] names = split( ";", encodedIdentity );
if( names.length != 2 ) throw new IllegalArgumentError("...");
firstName = names[0];
surname = names[1];
}
One does not store all the variants with which an object's attributes may be specified. Therefore, there shouldn't be a field encodedIdentity.
First correct your name constructor with two fields
replace this
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
with
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
Also, can you paste the error from console here. so that it will be easier to find the exact problem.

increasing "count" every time an object is created and added to an array

I created a constructor with methods to create "student" objects and part of it is supposed to assign a student number to each student and increase that number by one with each student created.. mine aren't increasing.
this is the constructor
String firstNameInput;
public Student(String fName, String lName, String maj, double gpa)
{
this.firstName = fName;
this.lastName = lName;
this.major = maj;
this.gpa = gpa;
sNumber = 1234567;
}
Here's the method that returns the student number
public int getsNumber() {
return sNumber + count++;
}
here's my toString method
public String toString()
{
return sNumber + " " + firstName + " " + lastName + " " + major + " " + gpa;
}
and here's where a student gets added.
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student s1 = new Student("Terra", "Ramey", "EE", 3.4);
list.add(s1);
Let me know if I need to include all of my code to figure out where the problem is, but I think it's with one of these
count++ is located inside the method getsNumber(). There are two problems with that:
The method is never called (at least, not in the code you've shown), hence you don't see the number increase.
You would presumably call this method whenever you want to know the student number of a student - so every time you try to figure that out, the number will increase.
Since this looks like homework, I won't tell you where to place count++, but here's a strong hint: which method is run each time a new student is created (and never otherwise)?
Also, see the other posters' advice about static (you haven't shown the declaration of count, so we can't tell if you're already using it). However, please make sure that you understand what static does and how a static variable is different from a nonstatic one (a lot of new programmers end up throwing static around, thinking it's magic and hoping it will solve their problems).
Add a static variable to the class. Something like the following :
private static int count = 0;
private int studentNumber;
Then in the constructor add the following :
public Student(String fName, String lName, String maj, double gpa)
{
this.firstName = fName;
this.lastName = lName;
this.major = maj;
this.gpa = gpa;
sNumber = 1234567;
count = count +1; // to keep the count
this.getStudentNumber = count;
}
Also add the following method to the Student class:
public int getStudentNumber(){
return this.studentNumber;
}
Then in your main you can access the count by :
Student student = new Student(//parameters);
System.out.println(Student.count);
System.out.println(student.getStudentNumber());
If you are allowed to use static fields to store the current count, I think you'll find adding a private static int currentCount to the class and then assigning the field sNumber = count++; might work for you.
Make sure that you use an AtomicInteger instead of just an int. That way, your constructor can be called by several threads simultaneously safely.

Issue with String as parameter

First of, sorry for my bad English.
I'm pretty new to java and we are learning it in School at the moment. In my Program I want to use String as a parameter but when I try to build an object I can't type anything in for the Parameter. Here's my bytecode:
public String gender;
public Waage(String pGender)
{
gender = pGender;
}
As you can see I want the user to type in their gender, the variable gender will then be set to be the same as the parameter pGender. If I want to create an object with Bluej now, I just get the error that it cannot find symbol - variable x (for example female). Could someone please explain to me what I'm doing wrong or how to fix it? Thank you!
Also this is my first question here so if I did any big mistakes just tell me.
Edit:
My full code:
public class Waage
{
public String gender;
public Waage(String pGender)
{
gender = pGender;
}
public void changeGender(String pGender)
{
gender = pGender;
}
public String giveGender()
{
return gender;
}
}
And the Error Message is If I would type in female :
Error: cannot find symbol - variable female
In the constructor,
public Waage(pGender)
{
gender = pGender;
}
pGender is local variable of the constructor, that is taking String argument, and it is missing datatype. Edit that as below and it'll compile.
public Waage(String pGender)
{
gender = pGender;
}
One of the cause is not passing string in double quotes in constructor call.
You must be creating your class's object like this:
Waage waage = new Waage(female);
Either use :
Waage waage = new Waage("female");
or:
String gender = "female";
Waage waage = new Waage(gender);

Categories

Resources