Storing object in array in Java - java

Here is a simple program. I am assigned to store the objects in an array. But as I am a beginner student so i dont know how to store objects in array. Could somebody please help me with this question?
import java.util.Scanner;
public class MainExample {
public static void main(String[] args) {
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
if ("yes".equals(input))
repeat = true;
else
repeat = false;
}
}
}

you would need to create a class to hold the attributes like so. Create a constructor to initialize these values.
public class Room{
double length;
double width;
double price_per_sqyd;
double price_for_padding;
double price_for_installation;
String input;
double final_price;
boolean repeat = true;
}
then in your main method/driver class create an array with the type of this class and store relevant objects.
Room arr=new Room[100];
int count=0;
while (repeat)
{
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
keyboard.nextLine();
System.out.println( "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
arr[count]=new Room(length,width,price1,price2,price3,price4);//call to the constructor
if ("yes".equals(input))
repeat = true;
count++;
else
repeat = false;
}
}

Although not very elegant, a quick solution for this toy program would be to make a "Room" class with the various properties like "length", "width", "price_per_sqft" etc. Then you can set specific property of each room object and store the "room" objects in an array of "Room".

What are you trying to store in an array? The different final_price values?
Regardless, because you don't know how many times your loop will run, you probably need an ArrayList. You could create this by adding ArrayList <Double> prices = new ArrayList <Double> ();
Then, add a line at the end of your loop that stores the correct variable to the ArrayList. For example: prices.add(final_price);
If final_price is not what you are trying to store, then just replace it with the variable you do want to store.
Also, don't forget that if you do use an ArrayList, you will need the correct import statement at the top of your code: import java.util.ArrayList;

Related

How to store the data on every instance of do-while loop in Java?

I am currently studying Java and I need to add the values of every instance in my do-while loop. Is there some way to store the values so it won't be overwritten every loop?
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
int itemQty = input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
You can define a variable for the totalSum outside of the loop and then everytime the user enters a number, add itemQty to it.
int totalSum = 0;
do {
...
int itemQty = input.nextInt();
totalSum += itemQty;
...
} while (...);
// Here totalSum is the sum of all user inputs
you can update your program like this below -
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char userChar;
int itemQty = 0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty += input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
totalQty+=itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
As suggested by Lino, Keep itemQty outside the loop and initialize it to zero.
Do you also want to store the value of itemQty for every loop iteration?
If yes then use ArrayList.
ArrayList<int> valuesList = new ArrayList<int>();
and change your loop code to
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
valuesList.add(itemQty*10);//New line to be added
totalQty += itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
And then after the loop ends, display the values in each stage.
for (int i = 0; i < valuesList.size(); i++) {
System.out.println("The value of Qty in stage "+(i+1)+" is $"+valuesList.get(i));
}
And this will be your final output
Apples are $10
How many do you want?
10
Do you wish to buy more? (y/n)
y
Apples are $10
How many do you want?
5
Do you wish to buy more? (y/n)
n
The total is: $150
The value of Qty in stage 1 is $100
The value of Qty in stage 2 is $50

Using ellipse or ellipsis gone wrong

I'm creating a simple program that gets name, age and favorite number/s. The problem is that this exception appears when user chooses to input more than 1 favorite number.
Please help me to solve this problem that still uses ellipse in testing class --> favnum2 method.*
testing class
import java.util.Scanner;
public class testing{
public static Scanner input;
public static void main(String[] args){
boolean choicerepeat=true;
int favnumoftimes;
while(choicerepeat==true){
input = new Scanner(System.in);
testing2 obj1 = new testing2();
String name="";
int age=0;
favnumoftimes=0;
double favnum=0, favnumarr[]=new double[999];
boolean choice1;
System.out.print("What is your name? ");
name = input.nextLine();
System.out.print("What is your age? ");
age = input.nextInt();
obj1.message1(name);
obj1.message2(age);
System.out.print(name+" do you only have one favorite number? (If yes type 'true' else 'false' - NOTE: lowercase only) ");
choice1 = input.nextBoolean();
if(choice1==true)
favnum1();
else{
System.out.println("How many favorite numbers do you have "+name+"? ");
favnumoftimes = input.nextInt();
for(int a=0;a<favnumoftimes;a++){
System.out.print("Enter favorite number "+ (a+1) +": ");
favnumarr[a]=input.nextDouble();
}
for(int a=0;a<favnumarr.length;a++){
favnum2(favnumoftimes, favnumarr[a]);
}
}
System.out.println();
System.out.println("Do you want to restart the program? (true(Yes) else false(No)) ");
choicerepeat = input.nextBoolean();
}
}
public static void favnum1(){
System.out.print("Enter favorite number: ");
double favnumholder1 = input.nextDouble();
System.out.println("Your favorite number is "+favnumholder1+" ." );
}
public static double favnum2(int favnumoftimesholder,double...favtemphold2){
System.out.print("Your favorite numbers are ");
for(int a=0;a<=favnumoftimesholder;a++){
System.out.print(favtemphold2[a]+", ");
}
return 0;
}
}
testing2 class
public class testing2{
public static String message1(String nameholder){
for(int a=0;a<nameholder.length();a++){
char strholder = nameholder.charAt(a);
if(Character.isDigit(a)){
System.out.println("Names don't have numbers... ");
break;
}
else continue;
}
System.out.println("\nHi "+nameholder+"! Welcome to my simple program. ");
return nameholder;
}
public static int message2(int ageholder){
System.out.println("Your age is "+ageholder+" years old? Oh my goodness. ");
System.out.println();
return ageholder;
}
}
The problem is that varargs create new arrays with a length equal to the number of parameters passed. Thus double...favtemphold2 will create a new array favtemphold2 and since you only pass 1 element (favnum2(favnumoftimes, favnumarr[a]);) that array will have length 1.
You might want to either pass more elements or the entire array, i.e. favnum2(favnumoftimes, favnumarr);. Since double... is basically syntactic sugar for double[] they are equal and passing a double array for a double vararg will work.
A warning for future use of varargs though: be carefull with Object... since arrays are objects as well.

JAVA using assigned values from an array in a calculation

This is a very basic question but I have just started out with JAVA and have hit a bit of a bump with regards to arrays.
What I am trying to do is populate an array with 6 pieces of information from the user:
Number of employees to be input,
An alphanumeric employee number,
A first name,
A last Name,
the number of hours they have worked,
a number input corresponding to Pay Scale.
So far I have gotten these inputs into an array in JAVA however what I wanted to do was use corresponding number input to select a constant within the Pay Scale array and then use that constant to calculate the wages of each employee.
for instance employee 1 worked 10 hours at scale 0 so that would be 10*4.50
and employee worked 10 hours at scale 1 which would be 10*4.62
import java.util.Arrays; //imports Array utility
import java.util.Scanner; //imports Scanner utility
public class test1 {
static Scanner keyb = new Scanner(System.in); //Adds a keyboard input
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
for (int i = 0; i < Employee.length; i++) {
System.out.print("Enter Employee Number: ");
Employee[i] = scanner.next();
System.out.print("Enter Employee's First name: ");
FirstName[i] = scanner.next();
System.out.print("Enter Employee's Last name: ");
LastName[i] = scanner.next();
System.out.print("Enter Employee's Hours worked: ");
HoursWorked[i] = scanner.nextDouble();
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
}
for (int i = 0; i < HoursWorked.length; i++) {
System.out.println("Employee " + Employee[i] + " " + FirstName[i] + " " + LastName[i] + " has "
+ HoursWorked[i] * PayScale[0]);
}
}
}
}
Am I even close to a solution on this?
Is what I'm asking possible in JAVA?
Maybe I'm just looking at this the wrong way, but any help regarding this would be greatly appreciated.
edit
OK I added the extras array into the code
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of Employees: ");
int employees = scanner.nextInt();
String[] Employee = new String[employees];
String[] FirstName = new String[employees];
String[] LastName = new String[employees];
double[] HoursWorked = new double[employees];
int[]PayScale2 = {0,1,2,3,4};
double[] PayScale = {4.50,4.62,4.90,5.45,6.20};
I'm just unsure as to where I'd index the original PayScale array with the
PayScale[PayScale2[i]]
would it go into the for statement codeblock? (I have tried putting it in there however I get an error that it's not a statement :/
change
+ HoursWorked[i] * PayScale[0]);
to
+ HoursWorked[i] * PayScale[i]);
apart from that seems to me like you're doing what you're saying you should be doing..
you already have the payscales from here: double[] PayScale = {4.50,4.62,4.90,5.45,6.20}; so the following doesn't make a lot of sense:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale[i] = scanner.nextDouble();
First of all, if you want to keep this number (Number 0 to 4) separately, you should use another Array, not the one where you keep the Payscales, then you could index to the first array which keeps the different rates.. or else you could directly use the first array if you know the pay scale for every employee.. in the end it has to do with what you want to do and how you want to do it, but the logic and the tools are there. If you call the 2nd array PayScale2 for example:
System.out.print("Enter Employee's Payscale (Number 0 to 4): ");
PayScale2[i] = scanner.nextDouble();
then you can index to the first array for example:
PayScale[PayScale2[i]]
in which case if the user inputs 0 then PayScale2[i] would be 0 then PayScale[PayScale2[i]] would be PayScale[0] or 4.5 or whatever you set the value equal to at the first array

How to end a while Loop via user input

package cst150zzhw4_worst;
import java.util.Scanner;
public class CST150zzHW4_worst {
public static void main(String[] args) {
//Initialize Variables
double length; // length of room
double width; // Width of room
double price_per_sqyd; // Total carpet needed price
double price_for_padding; // Price for padding
double price_for_installation; // Price for installation
String input; // User's input to stop or reset program
double final_price; // The actual final price
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
//User Input
System.out.println("\n" +"What is the length of the room?: ");
length = keyboard.nextInt();
System.out.println("What is the width of the room?: ");
width = keyboard.nextInt();
System.out.println("What is the price of the carpet per square yard?: ");
price_per_sqyd = keyboard.nextDouble();
System.out.println("What is the price for the padding?: ");
price_for_padding = keyboard.nextDouble();
System.out.println("What is the price of the installation?: ");
price_for_installation = keyboard.nextDouble();
final_price = (price_for_padding + price_for_installation + price_per_sqyd)*((width*length)/9);
keyboard.nextLine(); //Skip the newline
System.out.println("The possible total price to install the carpet will be $" + final_price + "\n" + "Type 'yes' or 'no' if this is correct: ");
input = keyboard.nextLine();
}
}
}
How would I make it so when the user says yes the program stop and if the user says no then the program just repeats? I don't know why I'm having so much trouble. I've searched for well over 4 hours. I am only supposed to use a while loop, I think.
You have to assign repeat in your while-loop so it becomes false if the user says yes:
repeat = !input.equalsIgnoreCase("yes");
You just need to set repeat to true or false based on user input. So in the end, compare input with yes or no. Something like this would work for you :
if ("yes".equals(input))
repeat = true; // This would continue the loop
else
repeat = false; // This would break the infinite while loop
boolean repeat = true;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
while (repeat)
{
-----------------------
-------------------------
System.out.println("Do you want to continue:");
repeat = keyboard.nextBoolean();
}
you also if you want your code to be more systematic , go and search about the interrupt , specially thread interrupt , these answers above is correct , find the more organic code and implement it
You can use a break statement to exit a while loop.
while (...) {
input = ...;
if (input.equals("Y")) {
break;
}
}

JAVA beginner help needed string input in a loop

im a beginner in Java, and i have a problem to do:
the problem prompts the user 5 times to enter, the Name of a stock then the Share Price then the number of shares owned and we should calculate the sum of all the stock values, i wrote it using only two prompts using a loop, but my issue is that, in the second prompt time the loop Skips the String input for the second Name of stock instead of promting...bellow is the code:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sharePrice =0,stockPrice = 0, temp = 0 ;
int i = 0;
double sum=0;
String name;
while (i < 2) {
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
stockPrice = sharePrice * (double)(numberOfshares);
sum += stockPrice;
i++;
}
System.out.println("the total stockprice owned is: " + sum );
}
}
And this is the output i get:
Enter the Name of the Stock
nestle
Enter the Share price
2
Enter the number of owned shares
4
Enter the Name of the Stock
Enter the Share price
What makes the input skip during the second loop?
Again as per my comment the problem is that your code doesn't handle the End Of Line (EOL) token when calling nextInt() or nextDouble().
The solution is to use input.nextLine() after getting your int and double in order to swallow the EOL token:
sharePrice = input.nextDouble();
input.nextLine(); // add this
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
input.nextLine(); // add this
stockPrice = sharePrice * (double)(numberOfshares);
The problem is that the last time you call
int numberOfshares = input.nextInt();
in the first iteration of the loop your first passes a carriage return as the next stock name. You could instead use:
double sharePrice = Double.parseDouble(input.nextLine());
and
int numberOfshares = Integer.parseInt(input.nextLine());
You should readout the newline characters after reading the share price and number of shares:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sharePrice = 0, stockPrice = 0;
int i = 0;
double sum = 0;
String name;
while (i < 2)
{
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
// Read out the newline character after the share price.
input.nextLine();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
// Read out the newline character after the number of shares.
input.nextLine();
stockPrice = sharePrice * (double) (numberOfshares);
sum += stockPrice;
System.out.println(String.format("Name: %s, Price: %f, Shares: %d, Total: %f",
name,
sharePrice,
numberOfshares,
stockPrice));
i++;
}
System.out.println("the total stockprice owned is: " + sum);
}
See the lines with comments above:

Categories

Resources