double array won't print - java

I did some more work on this program, but now I am stuck because the string array prints, but i cant for the life of me get the double array to print. Any help would be appreciated!
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Double;
import java.util.Scanner;
public class inventoryTracker
{
private static Scanner sc;
private static double itemCost;
public static void main(String[] args)
{
System.out.println("Welcome to the Inventory tracker"
+ "\nThis program will accept the names and costs for 10 stocked items."
+ "\nThe program will then output a table with the names, costs and,"
+ "\nprices of the items."
+ "\nPrices are calculated with a 30 percent markup on cost.");
sc = new Scanner(System.in);
String[] product = new String[10];
Double[] itemCost = new Double[10];
for (int i = 0; i < itemCost.length; i++ ){
System.out.print("Enter the item cost :");
itemCost [i]= sc.nextDouble();
}
for (int i = 0; i < product.length; i++){
System.out.print("Enter the product name :");
product[i] = sc.next();
}
System.out.println(Arrays.toString(product));
}
}

That's because you are assigning a string to a string array in your two for loops.
product= sc.toString();
should be
product[i] = sc.toString();
and the same goes for itemCost.

That's because you are assigning a string to a string array in your two for loops. Also you are doing sc.toString() that is not correct.
product= sc.toString();
and
itemCost= sc.nextDouble();
should be changed to
product[i] = sc.nextLine();
and
itemCost[i] = sc.nextDouble();
and the same goes for itemCost.

You need to use index to set a value like:
product[index] = value;
Also you are using sc.toString() to get string from user. It wont work you need to use next() method to get string from user.
Loop should be like:
for (int i = 0; i < product.length; i++){
System.out.print("Enter the product name :");
product[i] = sc.next();
}
for (int i = 0; i < itemCost.length; i++ ){
System.out.print("Enter the item cost :");
itemCost [i]= sc.nextDouble();
}

Related

My arraylist size is a zero even though I've added items to the it

So I tried looking up this error (Exception in thread "main" java.lang.ArithmeticException: / by zero)
and figured that my arraylist size in the code below is zero. I can't understand why it is zero or how to solve it. Does it have to do something with the capacity of the array? I can't seem to figure out what's wrong with my code.
Btw, this code is for computing the average of all the elements in an arraylist and letting the user know what the average is.
I'm still a beginner at Java so I apologize if this may seem silly. Any help is appreciated!
import java.util.*;
public class ClassStuff {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList <Integer> ();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
for (int i = 1; i <= myArray.size(); i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
int result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static int computeAvg(List <Integer> myArray) {
int sum = 0;
int avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
return avg = sum/myArray.size();
}
}
I'm assuming the lines:
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
gets the amount of elements you want to add to the arraylist, which we later add to the list through the for loop. In that case keep it in another variable called list_length, since userInput constantly changes in the for loop.
System.out.println("Please enter a number: ");
list_length = scan.nextInt();
Then change the for loop after this input to something like:
for(int i = 1; i <= list_length; i++) {
userInput = scan.nextInt();
myArray.add(userInput);
}
This is because you changed the end of the for loop to myArray.size(), but remember that it was already 0, so the for loop ends since 1 >= 0. What you probably wanted to do was to add list_length amount of numbers into the arraylist
I found your problem.
The problem was your for loop because somehow the arrayList didn't catch any of the elements during the loop.
I also made some adjustment for the method so it counts the average correct.
Here's an example
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList <Integer> myArray = new ArrayList<>();
int userInput = 0;
String userConf = "";
while ((!userConf.equalsIgnoreCase("y"))) {
System.out.println("Please enter a number: ");
userInput = scan.nextInt();
myArray.add(userInput);
scan.nextLine();
System.out.println("Are you done entering numbers? (y/n): ");
userConf = scan.nextLine();
}
System.out.println(myArray);
double result = computeAvg(myArray);
System.out.println("Average is: " + result);
}
public static double computeAvg(List <Integer> myArray) {
double sum = 0;
double avg = 0;
for (int i = 0; i < myArray.size(); i++) {
sum = sum + myArray.get(i);
}
avg = sum / myArray.size();
return avg;
}
Output
myList = [4,5]
average = (4 + 5) / 2 (myArray.size())= 4.5
Hope it was useful!

Shopping Cart - Array not storing a value

I have been trying to create a shopping cart where the user can enter the number of items he/she has purchased and the price for each item.
I am having problems with the array. I am not able to store the price for each product. How can I store the second value (the price) in an array to match each item?
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[][] itemsCart;
int itemsInTheCart=0;
int itemsPrice = 0;
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
for(int i = 0; i < itemsInTheCart; i++){
System.out.print("Enter the price for item " + (i+1) + ": ");
itemsPrice = scan.nextInt();
itemsCart = new int[itemsPrice][itemsPrice];
// System.out.println(itemsCart.length);
}
}
An array needs to be declared with its size before it can be used.
Also in your example you do not need a 2D array, a 1D array is fine.
Also you need to initialize your array outside the loop other wise it will get overridden in each iteration
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
int [] itemsCart = new int [itemsInTheCart];
for (....) {
itemsCart[i] = itemsPrice;
}
Instead Use ArrayList
for example create a object class
class ShoppingDetails{
private String itemName;
private Integer price;
public ShoppingDetails(String itemName, Integer price) {
this.itemName = itemName;
this.price = price;
}
//add getter and setter if you want
}
Now you can use the it in
ArrayList<ShoppingDetails> shoppingCart=new ArrayList<>();
shoppingCart.add(new ShoppingDetails("item1",100);
By this way you can map price to items.
As mentioned by #"Scary Wombat", your approach is better suited for a 1D array than a 2D one. However since you are looking to use a 2D array I would like to point your where you code could be better. Also mentioned by him to need to declare the size before using the 2D array
Your line "itemsCart = new int[itemsPrice][itemsPrice];" would be better as itemsCart = new int[i][itemsPrice]; as this will ensure that the new indexes are filled with the appropriate values.
I have made some edits to your main. Feel free to as me if you don't understand
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[][] itemsCart;
int itemsInTheCart=0;
int itemsPrice = 0;
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
itemsCart= new int[itemsInTheCart][2];
for(int i = 0; i < itemsInTheCart; i++){
System.out.print("Enter the price for item " + (i+1) + ": ");
itemsPrice = scan.nextInt();
itemsCart[i][1] = itemsPrice;
}
// for testing
for (int i=0;i<itemsInTheCart;i++){
System.out.println("Item: "+(i+1)+" for price: "+ itemsCart[i][1] );
}
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int itemsInTheCart=0;
System.out.print("Please enter the number of items in your cart: ");
itemsInTheCart = scan.nextInt();
int[] itemsCart = new int[itemsInTheCart];
for(int i = 0; i < itemsInTheCart; i++){
System.out.print("Enter the price for item " + (i+1) + ": ");
itemsCart[i] = scan.nextInt();
}
for(int i = 0; i < itemsInTheCart; i++){
System.out.println(itemsCart[i]);
}
}
}

Name and age application with specific output using arrays and output

For my university lab work we have to finish 4 tasks. I'm currently on 6 of 9 and have for the most part completed it, but I'm having difficulty in completing the final parts of it. This is the description of what we must do:
Write a program that defines two arrays - one of strings and one of integers, both of size 10.
Your program should then ask the user to enter the a string representing a persons name,
and an integer representing their age. It should continue to do this until either the user
enters ‘done’ instead of a name, or until the array is full (that is, 10 pairs of names and ages
have been entered). It should then print out the names and ages as well as the names of the
youngest and oldest.
Hint: One tricky part is making sure that once you’ve typed ‘done’ to Finish entering names,
your program does not then ask you for the age of the person with name ‘done’ - be careful
about this.
I've highlighted the issues I'm having above in bolded text. Below is the code I currently have, but I'm not sure how to properly accomplish the bolded text.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class nameAge {
public static void main(String[] args){
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
System.out.println("Please enter the name of a person and then their age. Do this for up to 10 people and once finished, type 'done'");
name[0] = in.nextLine();
System.out.println(AGE_REQUEST);
age[0] = in.nextInt();
System.out.println(NAME_REQUEST);
name[1] = in.next();
System.out.println(AGE_REQUEST);
age[1] = in.nextInt();
System.out.println(NAME_REQUEST);
name[2] = in.next();
System.out.println(AGE_REQUEST);
age[2] = in.nextInt();
System.out.println(NAME_REQUEST);
name[3] = in.next();
System.out.println(AGE_REQUEST);
age[3] = in.nextInt();
System.out.println(NAME_REQUEST);
name[4] = in.next();
System.out.println(AGE_REQUEST);
age[4] = in.nextInt();
System.out.println(NAME_REQUEST);
name[5] = in.next();
System.out.println(AGE_REQUEST);
age[5] = in.nextInt();
System.out.println(NAME_REQUEST);
name[6] = in.next();
System.out.println(AGE_REQUEST);
age[6] = in.nextInt();
System.out.println(NAME_REQUEST);
name[7] = in.next();
System.out.println(AGE_REQUEST);
age[7] = in.nextInt();
System.out.println(NAME_REQUEST);
name[8] = in.next();
System.out.println(AGE_REQUEST);
age[8] = in.nextInt();
System.out.println(NAME_REQUEST);
name[9]= in.next();
System.out.println(AGE_REQUEST);
age[9] = in.nextInt();
System.out.println(NAME_REQUEST);
int size = name.length;
int sizeN = age.length;
for (int i=0; i < size; i++) {
System.out.println("Name: " + name[i]);
System.out.println("Age: " + age[i]);
}
int smallest = age[0];
int largetst = age[0];
for(int i=1; i< age.length; i++)
{
if(age[i] > largetst)
largetst = age[i];
else if (age[i] < smallest)
smallest = age[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
}
}
You have to take a look on loop doc in java
this code may help you
public static void main(String[] args) {
int youngest =0,older=0;
String[] name = new String[10];
int[] age = new int[10];
String NAME_REQUEST = ("Please enter name");
String AGE_REQUEST = ("Please enter age");
for(int i=0 ; i< 10;i++){
Scanner in = new Scanner(System.in);
System.out.println(NAME_REQUEST);
String tmpName = in.nextLine();
if(tmpName.equalsIgnoreCase("done"))
break;
name[i] = tmpName;
System.out.println(AGE_REQUEST);
age[i] = in.nextInt();
if(age[i] > age[older])
older = i;
if(age[i] < age[youngest])
youngest = i;
}
System.out.println("OLDER is : " + name[older]);
System.out.println("Younger : " + name[youngest]);
}
Try this out, I have tested it and it's working fine. Hope that helps. Happy coding.
package com.pearson.nextgen.aggregatedsessionservice;
import java.util.Scanner;
public class NameAgeTest {
public static void main(String[] args) {
String[] name = new String[10];
int[] age = new int[10];
Scanner in = new Scanner(System.in);
String NAME_REQUEST = "Please enter name";
String AGE_REQUEST = "Please enter age";
int count = 0;
while (count < 10) {
System.out.println(NAME_REQUEST);
String nameInput = in.next();
if (nameInput.equalsIgnoreCase("done")) {
break;
}
name[count] = nameInput;
System.out.println(AGE_REQUEST);
age[count] = in.nextInt();
count++;
}
int[] minAndMaxIndex = findMinAndMaxIndex(age, count);
System.out.println("Youngest Person: " + name[minAndMaxIndex[0]]);
System.out.println("Oldest Person: " + name[minAndMaxIndex[1]]);
}
private static int[] findMinAndMaxIndex(int[] inputArray, int count) {
int min, max = 0;
int minIndex = 0, maxIndex = 0;
max = min = inputArray[0];
for (int i = 0; i < count; i++) {
if (inputArray[i] > max)
maxIndex = i;
else if (inputArray[i] < min)
minIndex = i;
}
return new int[] { minIndex, maxIndex };
}
}

how do i add 3 salaries using array index?

I need help getting total amount for salary using printf statement
numbers/salary i need to add to get total salary;
salary 1: 120000.00
salary 2: 200500.00
salary 3: 175000.50 total
payroll amount is $495501.49
I need help getting total and the code to get the total payroll amount
This is my code:
import java.util.Scanner;
public class LabSeven {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] playerName = new String[3];
Double []dollarSalary= new Double[3];
double sum= 0;
for(int i=0; i<3 ; i++){
System.out.print("Enter player name: ");
playerName[i]=input.next();
System.out.print("Enter Salary: ");
dollarSalary[i]=input.nextDouble();
}
double total= sum + dollarSalary;
System.out.printf("Total payroll amount is: %7.2f\n", sum);
for(int i=0; i<=3; i++) {
System.out.printf(" %s %7.2f\n", playerName[i], dollarSalary[i]);
}
input.close();
}
}
After this line:
dollarSalary[i]=input.nextDouble();
Add this line:
sum += dollarSalary[i];
This way you will be accumulating the sum in the sum variable.
And, delete this line, as you cannot add an array to a double value, this statement made no sense:
double total= sum + dollarSalary;
Finally, you have one more bug, here:
for(int i=0; i<=3; i++) {
The problem is that i will take values 0, 1, 2, 3, but the size of the arrays is 3, so the only valid values are 0, 1, 2. Change the condition to < instead of <=:
for(int i=0; i<3; i++) {
Extra tips
Don't use a Double[]. A double[] is enough for your purpose here
Don't write the number 3 repeatedly. Define a constant, for example private static final PLAYERS_NUMand use this everywhere instead. That way if you want to change the number of players later, you can do it in one place instead of 4
Format your code nicely. Use an IDE like IntelliJ or Eclipse, and use their auto-format features
Putting it together
With the above suggestions applied, your program becomes:
public class LabSeven {
private static final int PLAYERS_NUM = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] playerName = new String[PLAYERS_NUM];
double[] dollarSalary = new double[PLAYERS_NUM];
double totalSalary = 0;
for (int i = 0; i < PLAYERS_NUM; i++) {
System.out.print("Enter player name: ");
playerName[i] = input.next();
System.out.print("Enter Salary: ");
double salary = input.nextDouble();
dollarSalary[i] = salary;
totalSalary += salary;
}
System.out.printf("Total payroll amount is: %7.2f\n", totalSalary);
for (int i = 0; i < PLAYERS_NUM; i++) {
System.out.printf(" %s %7.2f\n", playerName[i], dollarSalary[i]);
}
input.close();
}
}
Use this line in your for-loop and remove your total variable you don't need this.
sum += input.nextDouble();
or
sum += dollarSalary[i];
You can't add an array to a variable like you're doing.
Do something like this to add the salaries from your array. In your for after you add an individual salary to your dollarSalary add it to your sum variable as well.
for(int i=0; i<3 ; i++){
System.out.print("Enter player name: ");
playerName[i]=input.next();
System.out.print("Enter Salary: ");
dollarSalary[i]=input.nextDouble();
sum += dollarSalary[i]
//sum += input.nextDouble(); This expects another input from the user. We should not be doing this.
}
//double total= sum + dollarSalary; You dont need this line anymore
System.out.printf("Total payroll amount is: %7.2f\n", sum);

Basic Arrays in a Java Program

I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}

Categories