Fill an array with doubles from scanner in Java - java

Im looking to fill an array with doubles from the user using Scanner. However, I am having difficulties because of Java's inability to alter array size. I need to get around this somehow. My idea for getting around this was to first have the user enter how many doubles he will be putting into the array.
System.out.print("How many numbers would you like to put in the array?: ");
int num = in.nextInt();
while(num >= 0) {
double[] array[] = new double[num][];
System.out.println("Enter the " + num + " numbers now.");
}
This is what I have so far but it is clear that it will not function as intended.

You need to:
Decrement num or option (3)
Initialize your array outside the loop
Start saving numbers from array position 0
Here is how that would be done:
System.out.print("How many numbers would you like to put in the array?: ");
int num = in.nextInt();
int position = 0;
double[] array = new double[num];
while(position < num) {
System.out.println("Enter the " + num + " numbers now.");
array[position++] = in.nextDouble();
}

As you already know how many numbers the user will provide, Consider Using an ArrayList
ArrayList<Double> list = new ArrayList<Double>();
for(int i = 0;i< num;i++){
//Ask for a value
//add that value to the list
}
Using a simple for loop, you can ask each value, an add it to the list.

Related

Inserting user input in Java lottery program

Here is a code ive completed a long time ago. However, im trying to revisit my Java coding knowledge and even enhance my knowledge using 2D arrays. Ive been trying to improve my code to a new level using 2D arrays, and would like someone to help me how please. Here is what I want to add:
-Allow the user to choose how many tickets they will be generating (ive already done that).
-Randomize to generate the tickets from 1-50. These will be stored in 2d array
-Program will generate 6 numbers for the winning number stored in a 1D array.
-The program will check each ticket to check how many winning numbers there were and store that as in the last position of the 2D array (so 7 locations [x][7])
If you take a look at the do-while loop, this is where im having trouble incorporating into my program with array.
Your assistance is appreciated!
Scanner entry=new Scanner(System.in);
int ticketAmnt;
do
{
System.out.println("How many tickets will you be generating?");
ticketAmnt = entry.nextInt();
}
while(ticketAmnt<1 || ticketAmnt>100);
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++)
{
// Random number created here.
randomNum = (int) (Math.random() * 50);
for (int x = 0; x < i; x++)
{
// If random number is same, another number generated.
randomNum = (int) (Math.random() * 50);
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
To retrieve user input in java:
import java.util.Scanner; // Import the Scanner class
Scanner scanner = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter a number: "); // print something just before the input prompt to guide the user if needed
String input = scanner.nextLine(); // Read user input
int number = Integer.parseInt(input); // Need to parseInt because it is read in as a string
scanner.close(); // close the scanner object
ref: https://www.w3schools.com/java/java_user_input.asp
If you need to read multiple inputs then you can put the scanner.nextLine() in a loop
Does this solve your problem?

How to fix this loop for sorting packages by weight

I need to create a program that asks the customer how many packages they have (after the input it creates an array of that size) which then ask the customer to enter the weights of them. It then has to sort the packages into small, medium, or large and then prints how many of each size package there is.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int small = 0;
int medium = 0;
int large = 0;
int size = 0;
int[] intArray = {size};
System.out.printf("Please enter the number of weights to enter: ");
size = scan.nextInt();
for (double i = 0; i < intArray.length; i++){
if (i < size)
System.out.print("Please Enter weight1: ");
double weights = scan.nextInt();
System.out.println("\nPackage Weights");
System.out.print(weights);
if (weights <= 5)
small = 1 + small;
if (weights <= 10 && weights >= 6)
medium = 1 + medium;
if (weights >= 11)
large = 1 + large;
System.out.println("\n\nSmall: " + small);
System.out.println("Medium: " + medium);
System.out.println("Large:" + large);
}
}
}
I got the sorting to work, but I can only get it to ask for one package, which means my array and loop aren't working. Just now learning arrays / loops so i'm kinda stuck on this.
It only asks for one package because you initialize intArray as an array containing exactly one element. Instead of pointlessly initializing it in its declaration, before you even know how large it needs to be, create and assign the needed array after you input its length. At your option, you can move the whole declaration there:
// ...
size = scan.nextInt();
int[] intArray = new int[size];
Inasmuch as that's the case, I'm inclined to doubt your claim that you had the sorting part working -- you don't have a suitable place to store the weights that are entered. Perhaps you cut that part out of the code you presented. Indeed, if your program ever had any semblance of sorting then you must have performed quite a hack job on it.
The problem is the time at which your intArray is initialised.
It gets initialised just after size is initialized with the value of 0.
Therefore you end up with a single Element in your array.
All you have to do is move the initialisation of your intArray after the user input:
int[] intArray;
System.out.printf("Please enter the number of weights to enter: ");
size = scan.nextInt();
intArray = new int[size]; //<-- initialization of the array after the user input
for (double i = 0; i < intArray.length; i++){

Adding numbers to an array each loop

I made a quick program recently to have the computer guess a number you input. I was just using it to show a friend an example of a While loop. I decided I wish to make it more complicated but I'm not sure how to do it.
I wish to add each random guess to an array so that it doesn't guess the same number more than once.
Scanner scan = new Scanner (System.in); // Number to guess //
Random rand = new Random(); // Generates the guess //
int GuessNum = 0, RandGuess = 0;
System.out.println("Enter a number 1 - 100 for me to guess: ");
int input = scan.nextInt();
if (input >= 1 && input <= 100)
{
int MyGuess = rand.nextInt (100) + 1;
while ( MyGuess != input)
{
MyGuess = rand.nextInt (100) + 1;
GuessNum++;
}
System.out.println ("I guessed the number after " + GuessNum + " tries.");
}
You might want to use an ArrayList(A dynamically increasing array)
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(num);
If you want to see if that number is already added into the arraylist
if(list.contains(num))
{
System.out.println("You already tried " + num);
}
A Set is also considerably better option. It is the same as a ArrayList but doesn't allow duplicates.
HashSet<Integer> set = new HashSet<Integer>();
set.add(num);//returns true if the num was not inserted before else return false
if(!set.add(num))//set also has a contains method
{
System.out.println("You already entered " + num);
}
A Set is an appropriate container for that functionality. You would define it like this :
Set<Integer> previous = new HashSet<>();
And to get a random number that you haven't previously tried
while (previous.contains(MyGuess))
MyGuess = rand.nextInt(100) + 1;
previous.add(MyGuess);
This will get new random numbers from rand object until one is found that isn't in previous. Then that is added to previous for the next iteration.
Arrays in Java are of fixed size. Once you have allocated an array, adding elements is allowed only up to the number of elements that you have allocated upfront. This wouldn't be a big issue in your situation, because the values are limited to 100, but you have better alternatives:
Java library offers collections that grow dynamically. In your case a HashSet<Integer> would be a good choice:
HashSet can grow to an arbitrary size as you go
Checking HashSet for a number is a quick operation
Another solution would be to make an array of 101 booleans:
boolean[] seen = new boolean[101];
Now you can check if the number has been seen before by testing seen[myGuess] to be false, and set seen[myGuess] = true when you see a new number. This approach is also very fast. However, you need to keep track of how many available numbers you have, because the range from 1 to 100 will get exhausted after 100 guesses, so trying to generate an additional number would become an infinite loop.
Use a HashSet<Integer> to do this. The values in a Set are unique so this is an easy way to store the already guessed values.
The contains(...) method is how you find out if you've guessed this number before
A very simple example would be:
public static int[] randomArray(){
int number = Integer.parseInt(JOptionPane.showInputDialog("How many numbers would you like to save?: ")); //Get Number of numbers from user
int[] array = new int[number]; //Create the array with number of numbers (by User)
for(int counter = 0; counter < number; counter++){ //For loop to get a new input and output every time
int arrayString = (int) (Math.random() * 10);
array[counter] = arrayString;
System.out.println("Number " + (counter + 1) + " is: " + array[counter]); //Print out the number
}
return array;
}
This example adds numbers every time the loop repeats, just replace the random with the number you want.
The easiest way would be to add an ArrayList and just to check if the list contains the random value:
Ar first you make and new ArrayList:
ArrayList<Integer> myGuesses = new ArrayList();
The second step is to add the random value to the list:
ArrayList<Integer> myGuesses = new ArrayList();
Now you only have to check if if the List cotains the value bevore generating a new one and counting your trys:
if(myGuesses.contains(MyGuess))
{
//your code
}
I applied this to your code:
Scanner scan = new Scanner(System.in); // Number to guess //
Random rand = new Random(); // Generates the guess //
int GuessNum = 0, RandGuess = 0;
ArrayList<Integer> myGuesses = new ArrayList();
System.out.println("Enter a number 1 - 100 for me to guess: ");
int input = scan.nextInt();
if (input >= 1 && input <= 100) {
int MyGuess = rand.nextInt(100) + 1;
while (MyGuess != input) {
if(myGuesses.contains(MyGuess))
{
MyGuess = rand.nextInt(100) + 1;
GuessNum++;
myGuesses.add(MyGuess);
}
}
System.out.println("I guessed the number after " + GuessNum + " tries.");
}
I hope that helps!

Using arrays in Java

Im working on an assignment for a beginners Java course, and Im having a problem with printing out an array the way that its asking for. The problem is as follows:
"Write a program that asks the user "How many numbers do you want to enter?" With that value, create an array that is big enough to hold that amount of numbers (integers). Now ask the user to enter each number and store these numbers into the array. When all the numbers have been entered, display the numbers in reverse order from the order in which they were entered."
I have everything except the last part, displaying the numbers in reverse order.
Any help on this would be appreciated.
Heres What I have so far:
import java.util.Scanner;
public class ArraysNickGoldberg
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to enter?");
final int NUMBER_OF_ELEMENTS = input.nextInt();
int[] myList = new int[NUMBER_OF_ELEMENTS];
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.println("Enter a new number: ");
myList[i] = input.nextInt();
}
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++){
System.out.print(myList[i] + " ");
}
}
}
try
for( int i = NUMBER_OF_ELEMENTS - 1; i >= 0; i--){
System.out.print(myList[i] + " ");
}
You may also want to look at
Java Array Sort
to print it in reverse order, you just need to simply reverse your for loop :)
so instead of
for(int i=0; i< NUMBER_OF_ELEMENTS; i++){
}
use this instead:
for(int i=NUMBER_OF_ELEMENTS - 1; i >= 0; i--){ //remember to minus 1 or else you'll get index of out of bound
}

Taking the average of an Array

I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)

Categories