I need to create an array that allows the user to enter no more than 10 pieces of data (in this case number of shirts purchased). The user can enter -1 to finish if < 10 pieces of data or count will terminate at 10. For the output I need to create a Table that shows the user the # in one column and the # shirts purchased in the other, both need a header. I also need the average of the shirts purchased.
If the user enters 0 for shirts purchased I need the system to provide a statement but then continue with the loop.
Below is what I have so far. I am very new to this so any dumb downed explanations would be extremely helpful.
import java.util.Scanner;
public class Arrays
{
private static int number;
public static void main(String[] args)
{
final int ARRAY_SIZE = 9;
int[] shirtsPurchased = new int[ARRAY_SIZE];
int count = 0;
int sum = 0;
double average = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of shirts purchased or -1 to quit: ");
number = keyboard.nextInt();
while (number != -1 && count < ARRAY_SIZE)
{
shirtsPurchased[count] = number;
count++;
System.out.print("Enter the number of shirts purchased or -1 to quit: ");
number = keyboard.nextInt();
}
}
}
You have the lions share of what you need to do already done (I'm not familiar with Java, some syntax errors may be present, but I don't really see any). From what you've described, all I can see that you still have to do are the message if the number of shirts is zero, and the average calculation. While I won't give you the code, I'm sure you can find out how to go about it.
As far as the zero is concerned, you have the input, all you need to do is compare it to zero and output a message if necessary. A simple if statement would take care of that.
To calculate the average, all you'll need is another while loop to sum up all of the numbers of shirts purchased, and divide the result by the number of data elements. Something similar to...
while( count is less than number of total shirts ) sum += shirtsPurchased[count];
average = sum / count;
Related
I am really new to java and I signed up for an AP class which is being taught very badly, and so I have no idea of how to do this part of the assignment. It prampts you to add code that will do the following
Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., βSalesperson 3 had the highest sale with $4500.β Note that you donβt need another loop for this; you can do it in the same loop where the values are read and the sum is computed.
the code we are given is the following
import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
final int salesPeople = 5;
int[] sales = new int[salesPeople];
int sum;
Scanner scan = new Scanner(System.in);
for (int i=0; i<sales.length; i++) {
System.out.print("Enter sales for salesperson " + i + ":");
sales[i] = scan.nextInt();
}
System.out.println("\nSalesperson Sales");
System.out.println("------------------");
sum = 0;
for (int i=0; i<sales.length; i++) {
System.out.println(" " + " " + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
System.out.println("Average sale " + sum/salesPeople);
}
}
I really do not know what to do and would appreciate a nudge in the right direction as to how to find the max and the id of the person who produced the max.
Please help this is homework!
Because it's your homework, I won't give you the direct answer, but instead give you some hints. If you add two variables, say,
int heighestSale = -1; // assume the sales are not negative or at least one sale is not negative
int heighestPerson = -1;
then you update the two variables based on the current sale value in one of the loops and print out them at the end.
One possible strategy for finding a max value of an unsorted array is to go through the array (using a for loop, perhaps), and keeping track of the maximum value as you go through it.
I don't want to do your homework, but that might look like:
max = Integer.MIN (the smallest possible integer value)
for item in array
if item is greater than max
store item in max
This strategy should find the max value -- hope this helps you! Model the for loops and the print statements like the previous ones you've shown.
The key here is to remember that the sum of all sales and max number of sales can be calculated each time a new salesman's entry is inputted. On the first entry, for example, salesman 0 has N sales -- therefore the sum is N and the max is N. On each consecutive entry, you can update the sum by adding the value to it, and you can update the max if the entry's value is greater than the currently known maximum.
I need to complete this task. But I am not entirely sure how to get the range into the array. I think I am supposed to use a loop somehow but I do not get it to work.
This is what I have so far:
import java.util.*;
public class A2_1
{
static Scanner x = new Scanner(System.in);
public static void main(String[] args)
{
int [] myArray = new int [1000000];
int x;
for ( x = 0; x <= 100; x++)
{
myArray [x] = x+1;
}
System.out.println(myArray);
}
}
This is the task:
"Create a program that generates 1,000,000 integer random values in the range of [1,..,100] and for any given x (between 1 and 100) taken from the user input computes "(πππ‘ππ ππ’ππππ ππ πππππππ‘π πππ π π‘βππ ππ πππ’ππ π‘π π₯)/1,000,000".
This value must be comparable to the CDF of a uniform distribution U[1,100] at point x."
Im not going to give you the answer since this sounds like homework but I will help you break it down into manageable chunks.
First, generate 1000000 random numbers between 1 and 100. You were on the right track and combine it with Dawnkeepers hint. int[] randoms = new int[1000000]; is an int array with a size of 1000000. Now iterate over each index and assign it a random number(see above). Now you have an array with a million random numbers. Generating a million randoms can be a lengthy procedure depending on you machine, so yea.
Next, use the Scanner class to get the users input.(pro tip: dont use the same variable name for your scanner as your variable in the for loop lol). Now do an if check to make sure they enter a number between 1 and 100. if(val > 0 && val <= 100). If this passes, move on, else quit or prompt for user to give a new input. Using the scanner is pretty trivial so I wont go into this.
Finally, iterate through your list of randoms and keep a counter of how many numbers less then or equal to x.
int counter = 0;
for(int i = 0; i < randoms.length; i++) {
//if randoms[i] is less then or equal x, counter++
}
Take that counter and do your math, int final_answer = counter/randoms.length;
That's all that is to it. There are more efficient ways of doing this but I tried to make it simple to follow. If I misread the question, sorry.
I have been beating my head against the wall with my code. I finally got my code to allow me to input whatever numbers the user desires depending on how many rows and columns they want, but for some reason whenever I try to type in a larger column number than row number, I get an error. I've read over my loop tens of times, inserting -1 where I think the program is over counting, but it still won't work. I'm assuming this is the appropriate way to write a multidimensional array when it is completely dependent on the user, but if not, please tell me how to make my code more efficient. Thanks!
public class MultiPractice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompts user to insert desired rows and columns
System.out.print("Enter how many rows you want in your array: ");
int rowSize = input.nextInt();
System.out.print("Enter hwo many columns you want in your array: ");
int colSize = input.nextInt();
// Asks users to insert desired numbers for the multi-array
System.out.print("Enter " + (rowSize*colSize) + " integers: ");
// Creates the multidimensional array
int[][] multi = new int[rowSize][colSize];
// Runs the for loop to put numbers where they belong in array
for (int i = 0; i < multi.length; i++) {
for (int j = 0; j < multi[colSize].length; j++) {
multi[i][j] = input.nextInt();
System.out.print(multi[i][j] + " ");
}
System.out.println();
}
}
}
multi[colSize].length should be multi[0].length or multi[i].length (since you have a rectangular array, these have the same value).
multi[colSize].length is the length of row colSize. Therefore, if you have less than colSize+1 rows (since they start from 0), this is out-of-bounds.
It's .length that's screwing you up here. Multi[colSize].length is not the same as colSize; in fact, it's colSize + 1 (since length starts counting at 1).
My Solution: Instead of using multi.length, you can use i < rowSize. You can also swap out the multi[colSize] with < colSize.
I'm new to java and I have an assignment asking to prompt user for a number between 2 and 10 and it is supposed to print out multiples of that number. It is also supposed to use a for loop.
I think I have the general idea with the for loop I'm just trying to figure out how to do the multiples. Any help is greatly appreciated! This is where I am so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter a number between 2 and 10:");
for(int i = 2; i<= 100; i++){
System.out.println(+ i);
}
I suggest thinking about how you would go about doing the task mentally. When you're counting integers, you will add one each time (i++). When you're counting by, say threes, you will add three each time. You need to store your scanner's read value to a variable (don't try to read the scanner each time!) and adjust i++ in your loop to add the number you read from the scanner instead.
Begin with:
int step = in.nextInt();
if(step >= 2 && step <=10){
for(int i = 0; i <=100; ???){
System.out.println(+ i);
}
} else {
System.out.println("The step value was not between 2 and 10.");
}
I will leave you at this point as learning it for yourself is far more valuable than any Stack Overflow answer could ever be. If you are still stumped, I can guide you farther in the right direction.
You should ensure that the user can only enter numbers between 2 and 10, and you will need to store the input for use in your for loop. For example:
int num = 0;
Scanner in = new Scanner(System.in);
do
{
System.out.print("Please enter a number between 2 and 10:")
num = in.nextInt();
System.out.println();
} while((num < 2) || (num > 10));
Followed by your for loop.
A multiple of a number is that number times something.
So one multiple of i would be i * 13 (for example).
of course you need to get number from the Scanner "in" object
for (int i=2; i < 13; i++) {
System.out.println(" Multiple (" + i + ") = " + i*number;
}
I am trying to make a program that takes an input for #players and #dice and rolls the dice whatever number of times for each player. It then outputs the rolls and the total.
So far I've managed to develop a program that can roll as many dice as inputted and store these values in an array, which it then sums and outputs.
Unfortunately, I'm stuck as of now because I don't really have any clue what to do when trying to make the program do this again each time for a new player. I understand it would probably be with an incrementer, but I'm just really overwhelmed by the complexity and don't even know what I would look for online.
Here is my code:
package diceroll;
import java.util.ArrayList;
import java.util.Scanner;
public class DiceRoll {
public static void main(String[] args) {
int numplayers = 0, numdice = 0; // incrementers for #rolls and #players
// ArrayList<ArrayList> players = new ArrayList<ArrayList>();
// players.add(rolls); /// adding list to a list
// System.out.println(players);
ArrayList<Integer> rolls = new ArrayList<>();
System.out.println("Enter the number of players.");
Scanner scan = new Scanner (System.in);
numplayers = scan.nextInt();
System.out.println("Enter the number of dice.");
numdice = scan.nextInt();
while (numdice > 0 ) {
Die die1 = new Die();
die1.roll();
rolls.add(die1.getFaceValue());
numdice--;}
System.out.println(rolls);
// sum for array, but i cant access the arraylength
int total = 0;
for (int n : rolls) //what does the colon : do ?
{total += n;
System.out.println("Dice total:" + total);
}
}
}
There is also a basic Die.java class that assigns a random number to face value and has the roll method I use to randomize the die.
Output:
run:
Enter the number of players.
1
Enter the number of dice.
4
[5, 4, 6, 6]
5
9
15
The only problem is changing the number of players currently has no effect.
21
You may probably want to use another loop outside your while loop, if you want to repeat the #dice for all the players.
The for(int i:rolls) --> this statement is read as "for each integer 'i' in rolls" which means, for every iteration of the loop, the values in rolls are assigned to y:
And this is equivalent to
for(int j=0;j<rolls.size();j++){
i = rolls[j];
// Other statements goes here.
}