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.
Related
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'm trying to read a file that has student record(first name, last name, and grade).
I have written a simple code to accomplish this task but the code fails after reading two lines from the text file. Here is my code:
public class Student {
private final String first,last;
final int MAXGRADE = 100;
final int LOWGRADE = 0;
private final int grade;
public Student(String firstname,String lastname, int grade){
this.first = firstname;
this.last = lastname;
this.grade = grade;
}
#Override
public String toString(){
return first + " " + last + "\t" + grade;
}
}
and the driver has this code
public class driver {
public static void main(String[] args) throws FileNotFoundException {
String first_name ,last_name;
int grade;
Scanner fileInput = new Scanner(new File("data1.txt"));
while (fileInput.hasNextLine())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name,grade);
System.out.println(st);
}
}
}
the compiler is pointing to this
grade = fileInput.nextInt();
as the source of the error.
This code is working for me. Make Sure
The location of text file correctly given,
Integer value given at 3rd position in each line (like:- steve smith 22)
If you are using Java 8, then functional way of doing this would be:
String filePath = "C:/downloads/stud_records.txt"; // your file path
/*
* Gives you a list of all students form the file
*/
List<Student> allStudentsFromFile = Files.lines(Paths.get(filePath)).map(line -> {
String[] data = line.split("\\s+"); //Split on your delimiter
Student stud = new Student(data[0], data[1], Integer.parseInt(data[2]));
return stud;
}).collect(Collectors.toList());
Note: I've made an assumption that this:
FirstName LastName Grade
is the input file format.
From the comment you post "#AxelH each line represents a single student first, last name and grade" we can see the problem.
Your actual loop to read a line
while (fileInput.hasNextLine())
{
first_name = fileInput.next();
last_name = fileInput.next();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name,grade);
System.out.println(st);
}
Is reading 3 lines, one per fileInput.nextXXX();. What you need to do is
Read a line as a String : `String line = fileInput.nextLine();
Split that line base on the delimiter : `String[] data = line.split(" "); //Or your delimiter if not space (carefull with some names...)
Set the value from this array (parse are need for integer)
EDIT :
I have made a mistake since I am used to use nextline and not next, I can't delete the answer as it is accepted so I will update it to be more correct without changing the content.
The code is indeed correct, next will take the following input until the next delimiter, \\p{}javaWhitespace}+, but using the given solution would give you more solution to manage composed names as it could be Katrina Del Rio 3.
I'm trying to print the test data used in webdriver test inside a print line in Java
I need to print multiple variables used in a class inside a system.out.print function (printf/println/whatever).
public String firstname;
public String lastname;
firstname = "First " + genData.generateRandomAlphaNumeric(10);
driver.findElement(By.id("firstname")).sendKeys(firstname);
lastname = "Last " + genData.generateRandomAlphaNumeric(10);
driver.findElement(By.id("lastname")).sendKeys(lastname);
I need those print in a print statement as:
First name: (the variable value I used)
Last name: (the variable value I used)
Using something like below gives the exact result.
But I need to reduce the number of printf lines and use a more efficient way.
System.out.printf("First Name: ", firstname);
System.out.printf("Last Name: ", lastname);
Thanks!
You can do it with 1 printf:
System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);
Or try this one:
System.out.println("First Name: " + firstname + " Last Name: "+ lastname +".");
Good luck!
System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);
or
System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));
You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.
This is a sample
Main
public class Main {
public static void main(String[] args) {
Person person = generatePerson();
String personStr = personToString(person);
System.out.println(personStr);
}
private static Person generatePerson() {
String firstName = "firstName";//generateFirstName();
String lastName = "lastName";//generateLastName;
return new Person(firstName, lastName);
}
/*
You can even put this method into a separate util class.
*/
private static String personToString(Person person) {
return person.getFirstName() + "\n" + person.getLastName();
}
}
Person
public class Person {
private String firstName;
private String lastName;
//getters, setters, constructors.
}
I prefer a separate util method to toString(), because toString() is used for debug.
https://stackoverflow.com/a/3615741/4587961
I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.
Suppose we have variable date , month and year then we can write it in the java like this.
int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);
output of this will be like below:
15/4/2016
I'm puzzled as to why my program prints statements in a certain order?
I have a Student class, inside which is an Inner Class of Address. The idea of the program is to first assign a Home Address to a Student Object, but then also assign a University / Term Time Address by utilizing the Inner Address Class.
The code is as follows:
Student Class (with Inner Address Class)
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() {
return name;
}
public Address getHomeAddress() {
String s = "n/a";
if (homeAddress != null) {
return homeAddress;
} else {
// System.out.println(s);
return null;
}
}
public void setUniAddress(int num, String add) {
uniAddress = new Address(num, add);
}
public Address getUniAddress() {
String s = "n/aa";
//If uniAddress isn't set,
// then "n/aa" gets printed before anything else i/e toString() method - WHY?
if (uniAddress == null) {
System.out.println(s);
return null;
} else {
return uniAddress;
}
}
#Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress();
}
// Inner Class
public class Address {
private int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
#Override
public String toString() {
//return name + "\n" + number + " " + street;
return number + " " + street;
}
}
} // more Student methods .. }
The TestStudent Class (with main method)
public class TestStudent {
public static void main(String[] args) {
//Home Address
Student s1 = new Student("Cathy", 21, "Smithfield Drive");
//Uni Address
s1.setUniAddress(72, "Nottingham Drive");
Student.Address anotherAddress = s1.new Address(8, "Deerfield Way");
// note the use of new
System.out.println(s1.toString());
}
}
The output is:
n/aa
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: null
(all on new lines)
If I do not assign a Uni Address to the Student (i.e. If I comment out the appropriate line in the main method - that calls the setUniAddress() method), I am curious then, as to why 'n/aa' from the getUniAddress() method is printed before the toString() method? (as above)
If I do call the setUniAddress() method the out put is:
NAME: Cathy
HOME ADDRESS: 21 Smithfield Drive
TERM TIME ADDRESS: 72 Nottingham Drive
(all on new lines)
Which seems to work as intended.
I'm also wondering how, instead of printing 'null' to the TERM TIME ADDRESS: (when setUniAddress() method isn't called), I could return the 'n/aa' in it's place - that is what I was attempting to do?
Thanks.
getUniAddress() is called from the toString() which is why the n/aa is printed first.
If you want to print "n/aa" as a default value - set it as a default value, for example, change the declaration to:
private Address homeAddress, uniAddress = "n/aa";
#Override
public String toString() {
return "NAME: " + getName() + "\n"
+ "HOME ADDRESS: " + getHomeAddress() + "\n"
+ "TERM TIME ADDRESS: " + getUniAddress(); // <-- here you call getUniAddress() which
// is why "n/aa" is printed first
}
in getUniAddress() you have the following line which prints "n/aa":
System.out.println(s);
When the return statement in the toString() method is executed the get*() methods are called. Then a string is created and returned by the toString() method.
So the 'n/aa' is printed while calculating the string to return from the toString(), then the toString() method returns the string and the main method prints the output generated from toString().
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.