Inserting user input in Java lottery program - java

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?

Related

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++){

Array search using Java

So I am extremely new to Java and my assignment has me creating an array 10 indexes in size, copying it, and sorting the copy. These parts I have functioning properly. What they want me to do is prompt the user for a value they wish to search for, and if found, return the index and which array it was found in. This last search part is really messing me up. My code is very sloppy I know, but I am not very good at this yet. The book of course has an example, but it uses a driver class and I'm not entirely sure if that's required in this situation. Thanks for any replies and my apologies if I posted this incorrectly.
http://imgur.com/a/T8t3Q - This is an example of the final output required.
public class MJUnit1Ch9 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
double[] numList; //list of random numbers
double[] numListSorted; //sorted copy of array
int numSearch; //array search
int numSearchIndex; //position in array
numList = new double[10]; //creation of size 10 array
for (int i = 0; i < 10; i++) { //create random numbers between 1 and 20
numList[i] = (int) (Math.random() * 20 + 1);
}
numListSorted = Arrays.copyOf(numList, numList.length); //copy original array
Arrays.sort(numListSorted); //sort copy by API
System.out.printf("%7s%7s\n", "Unsorted Array", "Sorted Array");
for (int i = 0; i < numList.length; i++) {
System.out.printf("%7.2f%7.2f\n", numList[i], numListSorted[i]);
}
//*************************************************************************
//*************************************************************************
System.out.print("Please enter number to search for:");
}
}
You can read number using scanner object
stdIn.nextInt()
And for searching you can use Binary search method of Arrays class by passing the number which you read from scanner object

Fill an array with doubles from scanner in 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.

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