dont shows the values in the array - Java - java

i'm doing an exercise where i have that to store objects in the array, the problem is when i'm going to print the objects of the array, dont shows the values of type String, the output is:
AFGH
3
5
2
3
5
5
1
2
5
7
my code is:
public static void main(String[] args){
Bill[] billsList = new Bill[5];
Scanner scanner = new Scanner(System.in);
String productCode = " ";
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i++) {
System.out.println("Digit the code of the product: ");
productCode = scanner.nextLine();
scanner.nextLine();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
price = scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price);
billsList[i] = bills;
}
for(int i = 0; i < billsList.length; i++) {
System.out.println(billsList[i]);
System.out.println(billsList[i]);
System.out.println(billsList[i]);
}
}
the code of the class Bill is this:
public class Bill {
private String productCode;
private int kilosSold;
private int price;
public Bill(String productCode,int kilosSold,int price) {
this.productCode = productCode;
this.kilosSold = kilosSold;
this.price = price;
}
}

In Bill class, you have to override toString() method of the Object class.
Somewhat like:
#Override
public String toString() {
return "Product : " + productCode + " kilosold : " + kilosSold + "price : " + price;
}
or optionally you can use the #ToString of the lombok to avoid this boilerplate code.
Also, you can change your data members of class to final.
Somewhat like:
private final String productCode;
private final int kilosSold;
private final int price;

remove the nextLine and it would print fine:
System.out.println("Digit the code of the product: ");
productCode = scanner.next();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
in addition, you should override the toString method like what was answered above.

If you want to print a complete object array, and all the attributes you should use the Arrays class method "toString". If you only want one of the attributes, for example: the product code, you should use a getter method. Investigate about getter and setter methods, it will help you a lot.
public static void main(String[] args){
Bill[] billsList = new Bill[5];
Scanner scanner = new Scanner(System.in);
String productCode = " ";
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i++) {
System.out.println("Digit the code of the product: ");
productCode = scanner.nextLine();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
price = scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price);
billsList[i] = bills;
}
System.out.println(Arrays.toString(billsList));
}

Related

while loop with store value for next while loop in java

I'm a beginner in Java. I have an assignment that require me to take 3 input from user, then output the 3 at the same time.
here is my code. i have only get 1 output.
suppose look like this:
anyone could help, thx!
here is my code
Scanner sc = new Scanner(System.in);
int i = 0;
String classname = " ";
String rating = " ";
int plus = 0;
while(i < 3){
System.out.print("What class are you rating? ");
classname = sc.nextLine();
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus = Integer.parseInt(rating);
i++;
}
System.out.print(classname + ": ");
while (plus > 0){
System.out.print("+");
plus --;
}
System.out.println();
The very first thing I would do is create a Course POJO (Plain Old Java Object). It should have two fields, name and rating. And I would implement the display logic with a toString in that Course POJO. Like,
public class Course {
private String name;
private int rating;
public Course(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rating; i++) {
sb.append("+");
}
return String.format("%s: %s", name, sb);
}
}
Then your main method simply involves filling a single array of three Course instances in one loop, and displaying them in a second loop. Like,
Scanner sc = new Scanner(System.in);
Course[] courses = new Course[3];
int i = 0;
while (i < courses.length) {
System.out.print("What class are you rating? ");
String className = sc.nextLine();
System.out.printf("How many plus signs does %s get? ", className);
int classRating = Integer.parseInt(sc.nextLine());
courses[i] = new Course(className, classRating);
i++;
}
i = 0;
while (i < courses.length) {
System.out.println(courses[i]);
i++;
}
You overwrite your variables classname and rating in each loop. You need to store each iteration in a field of an array.
Scanner sc = new Scanner(System.in);
int i = 0;
String[] classname = new String[3]; //create array
String rating = " "; //rating can be overwritten, it is not needed after the loop
int[] plus = new int[3];
while(i < 3){
System.out.print("What class are you rating? ");
classname[i] = sc.nextLine(); //name[index] to read/write fields of an array
//index starts at 0
System.out.print("How many plus signs does " + classname +" get? ");
rating = sc.nextLine();
plus[i] = Integer.parseInt(rating);
i++;
}
for(i = 0;i<3;i++){ //iterate over all elements in the array
System.out.print(classname[i] + ": ");
while (plus[i] > 0){
System.out.print("+");
plus[i] --;
}
System.out.println();
}

Why is the loop printing the same thing from the array of objects?

When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members

How to add two values in an array?

We are just starting to learn about arrays in my Java course, so I'm having problems. I want to multiply "quantity" by "cost" so it will print out the total cost, but right now it prints out 0 for the totalCost. Here is the driver:
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args){
String purchase, date;
double quantity, cost;
Scanner myScanner = new Scanner (System.in);
System.out.println("How many different types of items are you purchasing?");
int answer = myScanner.nextInt();
myScanner.nextLine(); // pick up the enter key
Basket[] myBasket = new Basket[answer];
for(int j = 0; j < answer; j++) {
System.out.println("Please enter the item you purchased.");
purchase = myScanner.nextLine();
System.out.println("Please enter the date.");
date = myScanner.nextLine();
System.out.println("Please enter the quantity.");
quantity = myScanner.nextFloat();
System.out.println("Please enter the cost.");
cost = myScanner.nextFloat();
myScanner.nextLine(); // pick up the enter key
myBasket[j] = new Basket(purchase, date, quantity, cost);
}
for (int i = 0; i< answer; i++)
{
System.out.println(myBasket[i]);
}
}
}
Here is the Basket class:
import java.text.NumberFormat;
public class Basket {
private String purchase, date;
private double quantity, cost, totalCost;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
public Basket(String purchase, String date, double quantity, double cost)
{
this.purchase = purchase;
this.date = date;
this.quantity = quantity;
this.cost = cost;
}
public void Calculations()
{
totalCost = cost * quantity;
}
public String toString()
{
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
}
Add Calculations(); to toString()
public String toString()
{
Calculations();
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
OR since the calculations method is public you can call it from the main method with myBasket[j].Calculations();
after
myBasket[j] = new Basket(purchase, date, quantity, cost);
If you want totalCost to be populated, you could call Calculations method when you are creating the instance of Baskets like:
myBasket[j] = new Basket(purchase, date, quantity, cost);
myBasket[j].Calculations();
This will now calculate the total cost and save it in in stance variable which you can print later on.
After last line in main(), add the below code,
float total=0.0;
for (int i = 0; i< answer; i++)
{
//System.out.println(myBasket[i]);
total+=myBasket[2]*myBasket[3];
}
System.out.println("total cost:"+total);
Your ”Calculations” method is not being invoked.
I thing you wanted to invoke it in the last line of the constructor.
By the way - java convention is lower case at the beginning of a method name, and it's better to name it by what it does - ”calculateTotalCost” for example

Java: creating an array inside of an object class?

I'm attempting to save an x amount of integers inside of an object class. I'm trying it via an array but am not sure if this is possible and as of now eclipse is giving me two errors. One asking me to insert an Assignment operator inside of my Gerbil() class and another saying that I can't make a static reference to to the non-static field food. The result I'm looking for is food 1 = first input; food 2 = second input; until it hits the total amount of food.
Here's my code so far:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public int[] food;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[]; // I'm not sure what I should put here. This is where I want to store
} // the different integers I get from the for loop based on the
// total number of foods entered. So if totalFoods is 3, there should
// be 3 integers saved inside of the object class based on what's typed
// inside of the for-loop. Or if totalFoods = 5, then 5 integers.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil();
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
food[j] = keyboard.nextInt();
}
}
}
}
You need to pass the number of food in the Gerbil constructor :
public Gerbil(int totalFood) {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
this.food[] = new int[totalFood];
}
And then in the loop will look like this :
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(totalOfFood);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
GerbilArray[i].food[j] = keyboard.nextInt();
}
}
Or something like that should do it.

Using default and non default constructors in my application

I'm new to java and have a question about default and non default constructors. My professor wants us to use the default constructor for creation of object BOOK1, and then use the non default constructor for BOOK2, BOOK3 and BOOK4. I know a constructor is used with the creation of an object, but I guess I don't understand how i'm supposed to differentiate between the two. My class code is as follows, where I have both a default and non default constructor:
import java.text.DecimalFormat;
public final class BOOKItem {
DecimalFormat intFormat = new DecimalFormat("000");
DecimalFormat doubleFormat = new DecimalFormat("$#,##0.00");
private int bookID;
private int numberInStock;
private double price;
private double totalValueOfStock;
private int code;
private String genre = "";
public BOOKItem() {
bookID = 0;
numberInStock = 0;
price = 0;
code = 0;
}
public BOOKItem(int newID, int newStock, double newPrice, int newCode) {
setID(newID);
setStock(newStock);
setCode(newCode);
setPrice(newPrice);
}
public void setStock (int newStock) {
if (newStock >= 1 && newStock <=5000) {
numberInStock = newStock;
}
else {
numberInStock = 0;
}
}
public void setCode (int newCode) {
if (newCode > 0) {
code = newCode;
}
}
public void setID (int newID) {
if (newID >=11 && newID <= 111111) {
bookID = newID;
}
else {
bookID = 0;
}
}
public void setPrice (double newPrice) {
if (newPrice >= 1.0 && newPrice <=150.0) {
price = newPrice;
}
else {
price = 0;
}
}
public int getID () {
return bookID;
}
public int getNumberInStock () {
return numberInStock;
}
public int getCode () {
return code;
}
public double getPrice () {
return price;
}
public double calcTotalValue () {
totalValueOfStock = numberInStock * price;
return totalValueOfStock;
}
public double getTotalValue () {
return totalValueOfStock;
}
public void display() {
switch (code)
{
case 1:
genre = "Romance";
break;
case 2:
genre = "Adventure";
break;
case 3:
genre = "Sci-Fi";
break;
case 4:
genre = "Mystery";
break;
}
System.out.println("Display:");
System.out.println("Book ID: " + bookID + " NumInStock: " + numberInStock + " Code: " + genre + " Price: " +
price + " TotalStockValue: " + calcTotalValue());
}
}
Here is my application that uses the constructors(sorry about the break in the class code, i dunno why its doing that):
import java.util.Scanner;
public class Project7 {
public static void main(String[] args) {
int bookID;
int numberInStock;
double price;
int code;
Scanner keyboard = new Scanner(System.in);
BOOKItem BOOK1, BOOK2, BOOK3, BOOK4;
BOOK1 = new BOOKItem();
BOOK2 = new BOOKItem();
BOOK3 = new BOOKItem();
BOOK4 = new BOOKItem();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD ID(<11 or >111111)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK1.setID(bookID);
BOOK1.setStock(numberInStock);
BOOK1.setCode(code);
BOOK1.setPrice(price);
BOOK1.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD STOCK(>5000)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2.setID(bookID);
BOOK2.setStock(numberInStock);
BOOK2.setCode(code);
BOOK2.setPrice(price);
BOOK2.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD PRICE(>150.0)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK3.setID(bookID);
BOOK3.setStock(numberInStock);
BOOK3.setCode(code);
BOOK3.setPrice(price);
BOOK3.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use ALL GOOD DATA");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK4.setID(bookID);
BOOK4.setStock(numberInStock);
BOOK4.setCode(code);
BOOK4.setPrice(price);
BOOK4.display();
}
}
Am I doing something incorrect with the creation of my objects? How do I use the non default constructor for BOOK2, BOOK3 and BOOK4? I created it, but perhaps i'm using it incorrectly. Any feedback would be greatly appreciated.
When you use
BOOK1 = new BOOKItem();
You are calling the default constructor (Construction without having any arguments)
After taking user input you would call the Non Default Constructor
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2 = new BOOKItem(bookID, numberInStock, price, code);
Use the above code to use the Parameterized Constructor (Non Default constructor)
This is called constructor overloading.
So for the objects you want to assign default values you call the default constructor
For the object you have information available with variables you sent them in the constructor that you have defined with parameters, To assign that value

Categories