So arrayLists are a first for me, and as far as I know I've been doing everything correctly and following the examples provided to me by my online course. HOWEVER, for some reason or other I have a line underlined red...which I will get to in a moment after a brief explanation of this program.
This program allows you to input an employee information and after pressing the 'list' button (listButton) it outsput in the employeeField etc etc. That basically sums up this program.
public class EmployeeView extends FrameView {
class Company { //this is the class to allow me to put 'company' in the arrayList...
String ID, firstName, lastName, annualSal, startDate, mileage;
Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
ID = _ID;
firstName = _firstName;
lastName = _lastName;
annualSal = _annualSal;
startDate = _startDate;
}
}
/** Define the ArrayList */
ArrayList <Company> inventory = new ArrayList <Company>();
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
String c;
String ID, firstName, lastName, annualSal, startDate;
ID = IDField.getText(); //all this stuff grabs info from the Fields...which will then be stored in the array
firstName = firstNameField.getText();
lastName = lastNameField.getText();
annualSal = annualSalField.getText();
startDate = startDateField.getText();
The two lines below this is the culprit. I suppose "new" is't nessisary but it was there in the example so that's why I am using it...however when I get rid rid of it only 'company' is underlined and the 'c' in the 2nd line is underlined instead of having the entire line underlined. Anyways I hope this is making sense...since its (from what I know of) my only problem.
c = new Company(ID, firstName, lastName, annualSal, startDate);
inventory.add(c);
}
private void ListActionPerformed(java.awt.event.ActionEvent evt) {
String temp="";
for (int x=0; x<=inventory.size()-1; x++) {
temp = temp + inventory.get(x).ID + " "
+ inventory.get(x).firstName + " "
+ inventory.get(x).lastName + " "
+ inventory.get(x).annualSal + " "
+ inventory.get(x).startDate + "\n";
}
employeeTArea.setText(temp);
}
You've declared c to be a String; you can't assign a Company directly to a String.
Change your declaration of c to be Company.
c is declared as a String above. It should be type Company instead.
Related
I am trying to convert an array that has three pieces of customer information in each bin:
String[] csv = {" jimmy ,johnson,jjohnson#gmail.com",
"Joe,Donald,Joe_Donald#donald.org",
"ARTHUR,THOMPSON,ARTHUR#thompson.org"};
I have a class (Customers) that includes a constructor to make a customer with the first name, the last name, and an email.
String customerList = "";
for (int i = 0; i < csv.length; i++) {
customerList += csv[i];
}
String[] customers = customerList.split(",");
Customer[] customs = new Customer[(customers.length / 3)];
for (int i = 0; i < customers.length / 3; i += 3) {
customs[i] = new Customer(customers[i], customers[i + 1], customers[i + 2]);
}
System.out.println(customs[0].getFirst_name());
System.out.println(customs[0].getLast_name());
System.out.println(customs[0].getEmail());
This gets me almost to where I need to be, however there is one small problem-- when the information is being stored in the array, it does not consider the comma in the original array as one of the commas I am trying to use as a split. Here is what the code above gives me:
Email Creator
=========================
jimmy
johnson
jjohnson#gmail.comJoe
As you can see, the first bits of information is correct, but Joe (the first name of the second person) is lumped in with the first customer.
Calling
customerList += csv[i];
will give you a String that looks like
jimmy ,johnson,jjohnson#gmail.comJoe,Donald,Joe_Donald#donald.orgARTHUR,THOMPSON,ARTHUR#thompson.org
There's probably multiple ways to fix it, but I would try adding a comma after you concatenate each entry from the csv array:
customerList += csv[i] + ",";
Why do you need String customerList = "";?
You can get the customs array like this:
String[] csv = {" jimmy ,johnson,jjohnson#gmail.com",
"Joe,Donald,Joe_Donald#donald.org",
"ARTHUR,THOMPSON,ARTHUR#thompson.org"};
Customer[] customs = new Customer[csv.length];
for (int i = 0; i < csv.length; i++) {
String[] splitted = csv[i].split(",");
customs[i] = new Customer(splitted[0].trim(), splitted[1].trim(), splitted[2].trim());
}
I think this was what you wanted to achieve,
String[] csv = {" jimmy ,johnson,jjohnson#gmail.com",
"Joe,Donald,Joe_Donald#donald.org",
"ARTHUR,THOMPSON,ARTHUR#thompson.org"};
Customer[] customs = new Customer[csv.length];
for (int i = 0; i < csv.length ; i++) {
String[] customerDetails = csv[i].split(",");
customs[i] = new Customer(customerDetails[0].trim(), customerDetails[1].trim(), customerDetails[2].trim());
}
System.out.println(customs[0].getFirst_name()));
System.out.println(customs[0].getLast_name());
System.out.println(customs[0].getEmail());
Using Streams?
List<Customer> customer = Arrays.stream(customerList).map(
s->{
String[] items = s.split(",");
return new Customer(items[0], items[1], items[2]);
}
}.collect(Collectors.toList());
I would start by overriding toString in Customer. You didn't post your version of Customer, but that might look like
public class Customer {
private String firstName;
private String lastName;
private String email;
public Customer(String first, String last, String email) {
this.firstName = first.trim();
this.lastName = last.trim();
this.email = email.trim();
}
#Override
public String toString() {
return String.format("first: %s, last: %s, email: %s", firstName, lastName, email);
}
}
Then you might use String.split and Arrays.stream and map your entries to Customer instances like
String[] csv = { " jimmy ,johnson,jjohnson#gmail.com", "Joe,Donald,Joe_Donald#donald.org",
"ARTHUR,THOMPSON,ARTHUR#thompson.org" };
List<Customer> customs = Arrays.stream(csv).map(s -> s.split("\\s*,\\s*"))
.map(t -> new Customer(t[0], t[1], t[2])).collect(Collectors.toList());
for (Customer c : customs) {
System.out.println(c);
}
And I get
first: jimmy, last: johnson, email: jjohnson#gmail.com
first: Joe, last: Donald, email: Joe_Donald#donald.org
first: ARTHUR, last: THOMPSON, email: ARTHUR#thompson.org
Here's a suggestion for you, a couple of things to point out:
I'm using a List instead of an array, a list can grow dynamically
and you don't need to specify the size up front, it's also a bit
easier to work with than an array.
Use a foreach loop instead of standard for, you don't need the index
so a foreach is perfect
When splitting the line, just check you get the expected number of
parts, perhaps treat the others as errors, so safeguard yourself
later when you expect to find certain things in certain spots.
The trim lets you get rid of whitespace, it's always good to clean
the data as soon as you can so you don't get junk filtering through
your application.
Consider using Lombok, it gives you nice annotations to generate
accessor methods, toString etc
sample code:
public static void main(String[] args) throws IOException {
String[] csv = {
" jimmy ,johnson,jjohnson#gmail.com",
"Joe,Donald,Joe_Donald#donald.org",
"ARTHUR,THOMPSON,ARTHUR#thompson.org"
};
// use a List rather than array, so it can grow dynamically
List<Customer> customers = new ArrayList<Customer>();
for (String line : csv) {
System.out.println("Processing line: " + line);
String[] parts = line.split(",");
if (parts.length != 3) {
System.out.println("Expected to find 3 parts in the line, but got " + parts.length);
}
// construct the customer, notice the .trim() to remove any whitespace
Customer customer = new Customer(parts[0].trim(), parts[1].trim(), parts[2].trim());
customers.add(customer);
}
System.out.println("Printing out customer list:");
// loop through the customers and print them out
for (Customer c : customers) {
System.out.println("firstName: " + c.firstName);
System.out.println("lastName: " + c.lastName);
System.out.println("email: " + c.email);
System.out.println("\n");
}
}
static class Customer {
// accessors removed, consider using Lombok for #Data, #Getter, #Setter etc
String firstName;
String lastName;
String email;
public Customer(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
This is the output I get, which I believe is what you're looking for
Processing line: jimmy ,johnson,jjohnson#gmail.com
Processing line: Joe,Donald,Joe_Donald#donald.org
Processing line: ARTHUR,THOMPSON,ARTHUR#thompson.org
Printing out customer list:
firstName: jimmy
lastName: johnson
email: jjohnson#gmail.com
firstName: Joe
lastName: Donald
email: Joe_Donald#donald.org
firstName: ARTHUR
lastName: THOMPSON
email: ARTHUR#thompson.org
Good luck!
I think your best bet here is to treat each element of your csv array as a distinct customer. There's no need to concatenate them all into one big string.
String[] csv = {" jimmy ,johnson,jjohnson#gmail.com",
"Joe,Donald,Joe_Donald#donald.org",
"ARTHUR,THOMPSON,ARTHUR#thompson.org"};
Customer[] customs = new Customer[csv.length];
for (int cidx = 0; cidx < csv.length; cidx++) {
String[] fields = csv[cidx].split(",");
customs[cidx++] = new Customer(
fields.length>0 ? fields[0].trim() : null,
fields.length>1? fields[1].trim() : null,
fields.length>2? fields[2].trim() : null);
}
for (Customer custom : customs) {
System.out.println("first="+custom.getFirst_name() + ", last="+custom.getLast_name()+", email="+custom.getEmail());
}
I'm asked to do the following tasks:
Five private variables to store the Name, Surname, Gender, age,
AmountPayout
Include an Object Instantiation that has two methods called. The one methods is called Info(), this will use a GUI to retrieve Name,
Surname, Gender, age, AmountPayout
Create another method called ReportPayment(), this will use a GUI to display the information of the user. Within this methods create
another method called PaymentCalculator that parse a parameter of the
amount to be paid.
Use the amount to deduct 15% tax, and return the final amount to be displayed.
My code returns:
required string string int double
public static void main(String[] args) {
Details det = new Details();
det.info();
det. ReportPayment();
}
class Details
{
private String name;
private String surname;
private String gender;
private int age , age1;
private double AmountPayout , SubPayout;
void info()
{
String name = JOptionPane.showInputDialog(null,"Enter the Patient Name :");
String surname = JOptionPane.showInputDialog(null,"Enter the Patient Surname :");
String age = JOptionPane.showInputDialog(null,"Enter the age of the patient :");
int age1 = Integer.parseInt(age);
String gender = JOptionPane.showInputDialog(null,"Enter the Patient gender :");
String AmountPayout = JOptionPane.showInputDialog(null,"Enter the Patient payout :");
double SubPayout = Double.parseDouble(AmountPayout);
}
void ReportPayment(String name, String surname, int age, double AmountPayout)
{
JOptionPane.showMessageDialog(null,"Victim of Listeriosis" + "\n"
+ "Patient Name:" + name + "" + surname + "\n"
+ "Age:" + age + "\n"
+ "Payout:" + AmountPayout);
}
}
First of all you should remove c# from tags, this has nothing to do with it.
Then take look at your ReportPayment method, as you can see in method signature you have 4 parameters that you must past once you call method.
So instead of writing det.ReportPayment();
You should write det.ReportPayment("name","surname", 10, 30); to make it work
But that isn't what you really want, because you are supposed to use class attributes you don't need to pass them to method, so you should change method to something like this:
// Note that we don't have parameters anymore
void reportPayment() {
JOptionPane.showMessageDialog(null,"Victim of Listeriosis" + "\n"
+ "Patient Name:" + name + "" + surname + "\n"
+ "Age:" + age + "\n"
+ "Payout:" + AmountPayout);
}
Last issue with your code is that you are not following conventions, this doesn't affect how your code works but it affects other people reading your code, whenever using some language make sure to get familiar with standard conventions in other to make code more understandable for other developers that will look at it.
In Java standard for naming is Camel case notation, with difference between class names and variable/method names being that classes always start with UPPERCASE letter while variable and method names start with lowercase.
Class name - StringBuilder
Method name - reportPayment
Variabl name - amountPayout
Another convention in Java is that { bracket comes just after method signature not on next line.
Finally in other to learn more about above mentioned things and many others I suggest you to buy/borrow some good Java introduction book, there are many out there.
2 issues with your code:
First issue: you forget the parameters in the call to det.reportPayment(); (note the lowercase r).
I assume you want to use the attributes stored in Details.
You have two options:
Pass the attributes as parameters:
det. ReportPayment(det.name, det.surname, det.age, det.AmountPayout);
Note this will not works without more modification as those attributes are privates. You have to either make them public or add getters (and then replace det.name with det.getName(), etc.)
Remove the parameters and use the Detail attribute directly in the method as the method is in the same class (best solution).
void reportPayment() {
JOptionPane.showMessageDialog(null, "Victim of Listeriosis" + "\n" + "Patient Name:" + this.name + "" + this.surname
+ "\n" + "Age:" + this.age + "\n" + "Payout:" + this.AmountPayout);
}
Second issue: you never set your class attribute.
In info()method, you ask the user to give values. Those values are stored in temporary variables but not in the class attributes.
For example, push the values in this.name instead of creating a new String name.
this.name = JOptionPane.showInputDialog(null, "Enter the Patient Name :");
this.surname = JOptionPane.showInputDialog(null, "Enter the Patient Surname :");
and so on.
Unrelated: have a look at java naming convention
Adding "this" in the info() method made the name , surname and gender work but the age and AmountPayout still returns a null
public static void main(String[] args) {
Details det = new Details();
det.info();
det.reportPayment();
}
}
class Details {
private String name;
private String surname;
private String gender;
private int age , age1;
private double AmountPayout , SubPayout;
void info()
{
this.name = JOptionPane.showInputDialog(null,"Enter the Patient Name :");
this.surname = JOptionPane.showInputDialog(null,"Enter the Patient Surname :");
String age = JOptionPane.showInputDialog(null,"Enter the age of the patient :");
int age1 = Integer.parseInt(age);
this.gender = JOptionPane.showInputDialog(null,"Enter the Patient gender :");
String AmountPayout = JOptionPane.showInputDialog(null,"Enter the Patient payout :");
double SubPayout = Double.parseDouble(AmountPayout);
}
Reworked the answer:
I tried to run the code myself and with a little tweaking it works perfectly fine. We are getting there. I think thi is the whole thing you should need!
This should now fix your error aswell as fit the requirements you have.
I changed:
renamed ReportPayment() to reportPayment()
removed te space inbetween
"det." and "ReportPayment() in the main class
Rewrote your attributes
rewrote the info() method
added the calculation for taxes as required
Main.java
public class Main {
private static boolean running = true;
public static void main(String[] args) {
Details det = new Details();
det.info();
det.reportPayment();
}
}
Details.java
import javax.swing.JOptionPane;
class Details {
private String name;
private String surname;
private int age;
private String gender;
private double AmountPayout;
void info() {
this.name = JOptionPane.showInputDialog(null, "Enter the Patient Name :");
this.surname = JOptionPane.showInputDialog(null, "Enter the Patient Surname :");
String rawAge = JOptionPane.showInputDialog(null, "Enter the age of the patient :");
this.age = Integer.parseInt(rawAge);
this.gender = JOptionPane.showInputDialog(null, "Enter the Patient gender :");
String rawPayout = JOptionPane.showInputDialog(null, "Enter the Patient payout :");
this.AmountPayout = Double.parseDouble(rawPayout);
}
void reportPayment() {
paymentCalculator();
JOptionPane.showMessageDialog(null, "Victim of Listeriosis" + "\n" + "Patient Name:" + name + " " + surname
+ "\n" + "Age:" + age + "\n" + "Payout:" + AmountPayout);
}
private void paymentCalculator() {
this.AmountPayout = this.AmountPayout * 0.85;
}
}
I want to know how to print a List in Java where in each position there is a String and an int.
List pasajeros = new ArrayList();
I insert the data like this:
public void insert(List a) {
System.out.print("Name: ");
name= sc.nextLine();
System.out.print("Number: ");
number= sc.nextInt();
ClassName aero = new ClassName(name, number);
a.add(aero);
}
}
And it seems to work like this, but in the syso gives me an error.
So you have a list of ClassName.
To print them, you can simply use a for loop:
List<ClassName> pasajeros = new ArrayList<>();
// + insert elements
for (ClassName cn : pasajeros) {
System.out.println("Name: " + cn.getName() + ", number: " + cn.getNumber());
}
You are printing an object without overriding the toString method..
list.Aerolinea#154617c means you are printing the objects hashcode..
so your problem is not at inserting, is at printing out the objects that the list is holding, in this case your Aerolinea class must override properly the toString method.
something like:
class Aerolinea {
private String nombre;
private String apellido;
#Override
public String toString() {
return "Aerolinea [nombre=" + nombre + ", apellido=" + apellido + "]";
}
}
Try like put method toString in your class...
public class Aerolinea {
String nombre;
.......
.......
public String toString() {
return "nombre" = nombre;
}
}
Ok I fixed it finally, it was silly...
I forgot to write < ClassName> in the method. Here is the final code
public void vertodo(List<Aerolinea> a) {
for (Aerolinea cn : a) {
System.out.println("Name: " + cn.name+ " ID: " + cn.id);
}
}
since I had created it like List pasajeros = new ArrayList();, then I changed it to List<Aerolinea> pasajeros = new ArrayList();.
Although I can't write the final <> empty after ArrayList as some have recommended.
Right now I am making a small program which should create an email adress and username out of the users actual name. For example, Peter Anderson types his first and last name in two separate text fields, and the program should then return a username and an email adress in two separate textfields, once you press the save button. For example, Peter Anderson gets the username "a13petand" and the email adress "a13petand#test.com" a = autumn, 13 = 2013. It should only take the first 3 letters from first & last name. It should then append the first name, last name, username and email adress to the text area. This is how my code currently looks like;
package test5;
import javax.swing.JOptionPane;
public class Test5 extends javax.swing.JFrame {
String[][] Users = new String[20][4];
int counter;
public Test5() {
initComponents();
}
private void savebtnActionPerformed(java.awt.event.ActionEvent evt) {
if (counter < Users.length) {
Users[counter][0] = Firstnametf.getText();
Users[counter][1] = Lastnametf.getText();
Users[counter][2] = Usernametf.getText();
Users[counter][3] = Emailtf.getText();
jTextArea1.append(Users[counter][0] + ", " + Users[counter][1] + ", " + Users[counter][2] + ", " + Users[counter][3] + "\n");
counter++;
} else {
JOptionPane.showMessageDialog(null, "The array is full!");
counter = Users.length;
}
}
How should I continue from here? How do I make it generate "a13" and then take the first 3 letters in the first and last name? That is my main problem. All I know is that I should use the String class method substring to pick the first 3 letters out of first & last name. And then use the Calendar class to get the correct year. But I don't know how to make it work with my current code, which is the problem.
Date date = Calendar.getInstance().getTime();
String result = "";
result += new SimpleDateFormat("MMM").format(date).substring(0,1).toLowerCase();
result += new SimpleDateFormat("yy").format(date);
result += Firstnametf.getText().subString(0,3);
result += Lastnametf.getText().subString(0,3);
you should use
firstName = Firstnametf.getText().subString(0,3);
lastName = Lastnametf.getText().subString(0,3);
currentYear = Calendar.getInstance().get(Calendar.YEAR);
voila = firstName.concat(lastName).concat(currentYear);
or
voila = firstName + lastName + currentYear.toString ;
I'll try to explain this as clearly as I can. I am trying to narrow down my code for an assignment by turning three of the classes used into a package that the program will access through an import statement. Here is my original code:
import javax.swing.JOptionPane;
public class AssignmentTen
{
public static void main (String[] args)
{
System.out.println();
int num = Integer.parseInt(args[0]);
int eNumber;
String input2;
String input3;
String input4;
String input5;
String input6;
int input7;
int input8;
int input9;
int input10;
Employee[] employees = new Employee[num];
for (int i = 0; i < num; i++)
{
eNumber = getInt ("Enter Employee Number:");
input2 = getString ("Enter Employee First Name:");
input3 = getString ("Enter Employee Last Name:");
input4 = getString ("Enter Employee Street:");
input5 = getString ("Enter Employee City:");
input6 = getString ("Enter Employee State (Initials):");
input7 = getInt ("Enter Employee Zip Code (5 Digits):");
input8 = getInt ("Enter Employee Hire Month (MM):");
input9 = getInt ("Enter Employee Hire Day (DD):");
input10 = getInt ("Enter Employee Hire Year(YYYY):");
Name name = new Name(input2, input3);
Address address = new Address (input4, input5, input6, input7);
Date hireDate = new Date (input8, input9, input10);
employees[i] = new Employee (eNumber, name, address, hireDate);
System.out.println("#" + employees[i].empNumber + "\n" + employees[i].empName + "\n" + employees[i].empAddress + "\nHire Date: " + employees[i].empHireDate + "\n\n");
}
}
public static int getInt(String paramString)
{
String str = JOptionPane.showInputDialog(paramString);
return Integer.parseInt(str);
}
public static String getString(String paramString)
{
String str = JOptionPane.showInputDialog(paramString);
return str;
}
}
class Employee
{
Number empNumber;
Name empName;
Address empAddress;
Date empHireDate;
public Employee(Number empNumber, Name empName, Address empAddress, Date empHireDate)
{
this.empNumber = empNumber;
this.empName = empName;
this.empAddress = empAddress;
this.empHireDate = empHireDate;
}
}
class Name
{
String firstName;
String lastName;
Name(String first, String last)
{
firstName = first;
lastName = last;
}
public String toString()
{
return firstName + " " + lastName;
}
}
class Address
{
String eStreet;
String eCity;
String eState;
int eZipCode;
Address(String street, String city, String state, int zipCode)
{
eStreet = street;
eCity = city;
eState = state;
eZipCode = zipCode;
}
public String toString()
{
return eStreet + " " + eCity + " " + eState + " " + eZipCode;
}
}
class Date
{
int month;
int day;
int year;
Date(int eMonth, int eDay, int eYear)
{
month = eMonth;
day = eDay;
year = eYear;
}
public String toString()
{
return month + "/" + day + "/" + year;
}
}
I need to take the Name class, the Address class, and the Date class and put them into a package called util. First of all, I organize all of my java programs in a folder called My Java Programs (C:\MyJavaPrograms) as I was instructed to do so. To create what I think is supposed to be the package, I copied each class and put them into their own individual file, I put the statement 'package.util' at the top, and then I named them Name.java, Address.java, and Date.java and I put them in a folder called util, which is located in C:\MyJavaPrograms.
Afterwards, I put the statement 'import util.*;' at the top of my original code and put it in C:\MyJavaPrograms. For one reason or another, the file won't compile. I've already done a lot of googling for my problem, including reading up on this, which doesn't help me, at least to the extent that I understand what is wrong.
I suspect that there is a problem with my classpath, although I do not have any idea what I can do to fix it. If it helps with figuring out the problem, I do know that I can't use the javac command in the command prompt without going to this thread and typing in one of the responses.
Ideally, I would want to compile my new assignment and have it do exactly what the code I posted at the top of this question would do now, except it does it while utilizing a pacakage with the extra classes. I would really appreciate it if someone could send me in the right direction.
Check your package definition (the first line in each .java file). It should be 'package util;' not 'package.util'.
Are the classes in your util package marked as public?
1) Breaking classes into separate files, and organizing the files into a package, is a Good Thing.
2) Suppose you wanted to break your classes into "Assignment10.java" and "Util.java". They could both be in package "com.myclass". You'd do the following:
a) Create the files Assignment10.java and Util.java
b) Put "package com.myclass;" at the top of both
c) Create a new directory "com\", and subdirectory "myclass\"
d) Copy both *.java files into com\myclass
e) Compile and run from your root directory
3) If you were using an IDE (like Eclipse or Netbeans), it will automatically create the directories for you
Here are a couple of good tutorials:
http://web.cs.wpi.edu/~cs2102/b12/Assignments/making-packages.html
Java Package Vs Folder-Structure? what is the difference
----------------------------- ADDENDUM -----------------------------
To compile and run a Java program with packages from the command line:
1) Create package folder:
mkdir myclass\util
2) Create .java files
cd myclass\util
notepad AssignmentTen.java =>
package myclass.util;
public class AssignmentTen {
public static void main (String[] args) {
System.out.println ("In main...");
Name name = new Name("Jack", "Torrance");
System.out.println ("Exiting main.");
}
}
notepad Name.java =>
package myclass.util;
public class Name {
public Name (String first, String last) {
System.out.println ("My name is " + first + " " + last + "...");
}
}
3) Compile
javac *.java
dir =>
10/04/2013 10:38 AM 589 AssignmentTen.class
10/04/2013 10:36 AM 248 AssignmentTen.java
10/04/2013 10:38 AM 593 Name.class
10/04/2013 10:35 AM 177 Name.java
4) Execute
cd ..\..
java myclass.util.AssignmentTen =>
In main...
My name is Jack Torrance...
Exiting main.