So I have created an Account class and i wanted to save the user details permenantly for future use. For example, should the user create an account, i would like him/her to be able to use his info including balance in the future.
Please help me!
package mini_project;
import java.util.Random;
import javax.swing.JOptionPane;
public class Account {
private String firstName, surname;
private short transactionNumber;
String input;
private int startingAmount;
public Account(String first, String sur, int amount){
firstName = first;
surname = sur;
startingAmount = amount;
}
public void setFirstName (){
input = JOptionPane.showInputDialog("What Is Your First Name?").toUpperCase();
firstName = input;
}
public String getFirstName (){
return firstName;
}
public void setSurname (){
input = JOptionPane.showInputDialog("What Is Your Surname?").toUpperCase ();
surname = input;
}
public String getSurname (){
return surname;
}
public void setTransactionNumber (){
Random rand = new Random ();
int randomNumber = rand.nextInt(1000)+1;
transactionNumber = (short) randomNumber;
}
public short getTransactionNumber(){
return transactionNumber;
}
public void setShares(){
input = JOptionPane.showInputDialog("How Many Shares Do You Currently Own?");
startingAmount = Integer.parseInt(input);
}
public int getShares(){
return startingAmount;
}
}
You could always make the account class implement Serializable. This will allow you to save and import the object's instance, in this case individual account objects. These instances can be saved into a text file. They can also be encrypted if your program requires more security.
If you want to save the data permanently, You need to use database.
You can make your instance variable static. It will save permanently unless you close the program.
private static String firstName, surname;
private static short transactionNumber;
private static int startingAmount;
Then get the setters and getters. But remove the static word in the functions of setters and getters. You only need static in an instance variable.
Related
I need help with a specific problem in my class project. The goal of the project is to create a program in which you can register how much shares you own. Information that's required is the company name, how many shares you own and their respective value. I created a GUI class and a class where the information is transferred to. The input comes from a private void. I'm having trouble finding a way to transfer the input from the private void to a an arraylist in a class outside it.
Here is how I initialized the arraylist in the GUI class.
public class GUISharePortfolio_1 extends javax.swing.JFrame {
ArrayList<SharePackage.Share> Package = new ArrayList<SharePackage.Share>();
Next is how I get the company name, number of shares and their value from the GUI. Since it is a private void I have to transfer that information to the SharePackage class.
private void CreatePortfolioButtonActionPerformed(java.awt.event.ActionEvent evt) {
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.CompanyName(name);
Package.NumberOfShares(number);
Package.ValueOfShare(value);
}
I'm getting an error saying "cannot find symbol" under the CompanyName, NumberOfShares and ValueOfShare.
The public class to which the info should be transferred is this:
package shareportfolio;
import java.util.ArrayList;
public class SharePackage
{
private ArrayList<Share> Package = new ArrayList<Share>();
public class Share
{
private String companyname;
private double numberofshares;
private double valueofshare;
Share(String companyname, double numberofshares, double valueofshare)
{
this.companyname = companyname;
this.numberofshares = numberofshares;
this.valueofshare = valueofshare;
}
public void setCompanyName(String name)
{
companyname = name;
}
public String getCompanyName()
{
return(companyname);
}
public void setNumberOfShares(double number)
{
numberofshares = number;
}
public double getNumberOfShares()
{
return(numberofshares);
}
public void setValueOfShare(double value)
{
valueofshare = value;
}
public double getValueOfShare()
{
return(valueofshare);
}
}
}
I would appreciate any help very much.
You have a field named Package, who's type is ArrayList. ArrayList doesn't have a method called CompanyName. What you're probably trying to do is something like:
Package.add(new SharePackage.Share(companyname, numberofshares, valueofshares));
You have two such fields named 'Package', so not sure which one you're trying to add to. Maybe you're under the impression the fields are somehow the same one. They are not.
BTW: Definitely learn Java coding style before submitting this to anyone. You are naming fields with UpperCamelCase which makes it very difficult for a java programmer to read your code.
user1207705 that was the answer. I modified it to:
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.add(new SharePackage.Share(name, number, value));
Thank you for your help and I will work on Java coding style.
So the specifications are: Create a BankAccount class. It should contain the following information, stored in instance variables.
I need to have a constructor: BankAccount(String firstName, String lastName, double openingBalance). And a public String firstName(), a public String lastName(), and a public double balance() that return the First Name, last name and balance respectively.
And I have this so far...
public class BankAccountAssignmentPart1 {
private String firstName;
private String lastName;
private double openBalance;
BankAccountAssignmentPart1 (String firstName, String lastName, double openBalance) {
firstName = "Alfred";
lastName = "Jones";
openBalance = 1408;
}
public String firstName() {
return firstName;
}
public String lastName(){
return lastName;
}
public double Balance(){
return openBalance;
}
public static void main(String[] args){
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1();
System.out.println(m.firstName());
System.out.println(m.lastName());
System.out.println(m.Balance());
}
}
So the problem I have is in the line BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1(); in Eclipse it says that the constructor is undefined and goes on to give suggestions to change the code such as removing the String String double or change the modifier to static which can't happen in instances....So I don't know what to do.
Please Help!
You need to specify parameters when you call your constructor:
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1("1","2",0);
Otherwise it tries to find BankAccountAssignmentPart1() constructor (with no parameters), which is indeed undefined.
I have these two files, personalinfo.java which defines the personalInfo class, and testpersonalinfo.java which tests the class. When I try to access my getter methods from testpersonalinfo.java I receive an error that these methods are undefined. Can anybody please tell me why?
personalinfo.java:
public class personalInfo {
private String name;
private String address;
private int age;
private long phoneNumber;
personalInfo(){
name = "Default Name";
address = "Default Address";
age = 100;
phoneNumber = 0000000000;
}
personalInfo(String nam, String add, int ag, int phone){
name = nam;
address = add;
age = ag;
phoneNumber = phone;
}
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getAge(){
return age;
}
public long getPhoneNumber(){
return phoneNumber;
}
public void setName(String nam){
this.name = nam;
}
public void setAddress(String add){
this.address = add;
}
public void setAge(int ag){
this.age = ag;
}
public void setPhoneNumber(long phone){
this.phoneNumber = phone;
}
}
testpersonalinfo.java:
import java.util.Scanner;
public class personalInfoExample {
public static void main(String[] args){
personalInfo[] pers = new personalInfo[3];
Scanner input = new Scanner(System.in);
String inName;
String inAddress;
int inAge;
long inPhoneNumber;
for(int i=0; i<3; i++){
pers[i] = new personalInfo();
System.out.printf("Please input the name for person %s: ", i );
inName = input.nextLine();
pers[i].setName(inName);
System.out.println(pers[i].getName);
System.out.printf("Please input the address for person %s: ", i );
inAddress = input.nextLine();
pers[i].setAddress(inAddress);
System.out.println(pers[i].getAddress);
System.out.printf("Please input the age for person %d: ", i );
inAge = input.nextInt();
pers[i].setAge(inAge);
input.nextLine();
System.out.println(pers[i].getAge);
System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i );
inPhoneNumber = input.nextLong();
pers[i].setPhoneNumber(inPhoneNumber);
System.out.println(pers[i].getPhoneNumber);
input.nextLine();
}
input.close();
}
}
The getters are functions, not fields; so to call them you need to use () (like in: pers[i].getAdress().
Also, class names should be capitalized, but it's not really important (just makes it easier to read.
As someone suggested in a comment, you should use an IDE, in case you are not doing it. The IDE will point you to the obvious little mistakes (both errors and convention mistakes) like the ones above, and save you a long time. If you don't know where to get started for that, search Eclipse or Netbeans. (Eclipse is my personal favourite).
EDIT: I just saw Eran commented the answer to your error, so if he posts it as an answer accept his first.
in all your sysout statements you are trying to access getter without () this.
please try this
System.out.println(pers[i].getName()); //change all your getters
instead of
System.out.println(pers[i].getName);
because getName() is a method not a Variable so always you need to use open-close braces () just after the method name
(either you defining or calling) .
please change all these methods (methods which raise an compile-time Error).
System.out.println(pers[i].getName);
System.out.println(pers[i].getAddress); //all these lines are causing of Compile time error.
System.out.println(pers[i].getAge);
System.out.println(pers[i].getPhoneNumber);
In case if you don't want to use getter method to access instance variable(Other than private variables) out side of the class defination, you can call instance variable-names directly on an instance object like
pers[i].name
For more on variables access control please refer java-doc
So I have been trying to figure out how to do this for a week now. I am behind in the class due to an accident at work so I have not been participating. I started a chemical inventory program using net-beans IDE and have several errors which I don't understand? The teacher is no help and I've read and viewed video on the subject to no avail. Can some one look at my code and tell me what is wrong please. Below is my code now be gentle as I am VERY new to this. Any help would be appreciated. And this is my first post. Below the code is the requirement for week 4. Thanks in advance!
package chemical.inventory;
import java.util.Scanner;
/**
*
* #author Chris
*/
public class ChemicalInventory {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Chemical[] chemical;
chemical = new Chemical[4];
chemical[0] = new Chemical("Sodium Hypochlorite","1084","1.29","5000");
chemical[1] = new Chemical("Caustic Soda","2010","1.25","5000");
chemical[2] = new Chemical("Sulfuric Acid","1098","2.10","3000");
chemical[3] = new Chemical("Lime","1010","0.93","2500");
double chemicalValue = 0.0;
System.out.printf("\nInventory value is: $%,2f\n",chemicalValue);
}
private static class Chemical {
private String sodium_Hypochlorite;
public Chemical() {
}
private Chemical(String sodium_Hypochlorite, String string, String string0, String string1) {
this.sodium_Hypochlorite = sodium_Hypochlorite;
}
}
}
class Chemical.Inventory
{
protected String chemicalName;
protected double chemicalPrice;
protected double chemicalStock;
protected double chemicalitemNumber;
public ChemicalInventory(String name, double price, double stock, double itemNumber);
static {
String name;
this.chemicalTitle = title;
double price = 0;
this.chemicalPrice = price;
double stock = 0;
this.chemicalStock = stock;
double itemNumber = 0;
this.chemicalitemNumber = itemNumber;
}
Chemical(String string, String string0, String string1, String string2) {
}
public void setChemicalName(String name)
{
this.chemicalName = name;
}
public String getChemicalName()
{
return chemicalName;
}
public void setChemicalPrice(double price)
{
this.chemicalPrice = price;
}
public double getChemicalPrice()
{
return chemicalPrice;
}
public void setChemicalStock(double stock)
{
this.chemicalStock = stock;
}
public double getChemicalStock()
{
return chemicalStock;
}
public void setChemicalitemNumber(double itemNumber)
{
this.chemicalitemNumber = itemNumber;
}
public double getChemicalitemNumber()
{
return chemicalitemNumber;
}
public double getValue()
{
return this.chemicalStock * this.chemicalPrice;
}
static {
System.out.println();
System.out.println( "Chemical Name:" + chemical.getChemicalTitle());
System.out.println("Chemical Price:" + chemical.getChemicalPrice());
System.out.println("Chemical gallons in stock:" + chemical.getChemicalStock());
}
Modify the Inventory Program to use a GUI. The GUI should display the information one product at a time, including the item number, the name of the product, the number of units in stock, the price of each unit, and the value of the inventory of that product. In addition, the GUI should display the value of the entire inventory, the additional attribute, and the restocking fee.
Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item should display.
Add a company logo to the GUI using Java™ graphics classes.
What is wrong with your code, a lot:
You defined Scanner input = new Scanner (System.in); and you never use it
Naming convention, field String sodium_Hypochlorite; i believe should be named name
class Chemical.Inventory dot is invalid character for names in java. If you want define your class to be inner class of other class, place it there, if you want it to be on some path, use packages.
constructor defined in class class Chemical.Inventory first does not have a body
Both constructors defined in class Chemical.Inventory has not matching names with class.
your first static initializer in class Chemical.Inventory is using this and some undefined variables. Logic from that block should be declared in constructor.
your second static initializer in class Chemical.Inventory is using variable chemical which wasnt defined anywhere.
I have asked this question before and followed the feedback as best as I could but I am still having one problem with storing the info that the user enters into the array.
Here is the first attempt:
OOP Java: Creating a stock inventory program
So I need to have in total three classes(That's required). The Stock, stock inventory and then the user interface. The purpose of this program is to ask the user to input the company's name, stock rating, price and the number of shares. Of course, I then have to do other things. I think I am okay with the rest, the problem is the stockInterface, the last bit of code that I post below.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
public class StockInterface() {
private static StockInventory stockPortfolio;
public static void main (String [] args){
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
This piece of code doesn't work.
stockPortfolio [0]= new Stock(stockName, stockRatings, stockPrice, numberShares)
Can somebody please show me the proper way to store the info into the array? Thank you very much.
Lots of compile errors...
You have defined stockRating as a String but yet return it as an int:
public int getStockRating() {
return stockRating;
}
The same is true for price.
You have extra parenthesis here:
public class StockInterface() {
^
Also in StockInventory, there are multiple statements in the class block They belong in a method.
console is not instantiated.
stockPortfolio is assigned as an array entry, yet it is a single object, and assigned to the Stock which is not a matching type.
So you've declared the stockPortfolio as an instance of StockInventory. StockInventory is a class not an array, so you can't use stockPortfolio [0] = ... because stockPortfolio is an instance of the class. You have a private member in StockInventory that is an array of Stock class instances. What you need is an accessor method to be able to manipulate it. So change StockInventory as follows:
public class StockInvetory {
/*
All the code you have now ...
*/
public Stock [] getStocks(){
return stocks;
}
public setStocks(Stock [] value){
//maybe some checking here ...
stocks = value;
}
}
Now just a slight change in using the class. You need to use the accessor methods as follows:
public class StockInterface {
/*
What you have just the following line changes ...
*/
stockPortfolio.getStocks()[0] = new Stock(stockName, stockRatings, stockPrice, numberShares);
}
I am assuming you are happy with the way you are initializing the array and that you have decided arrays are better than more dynamic data structures in collections for your specific project. If this is not true have a look at Java Collections they may bring you more joy.