Taking User Input for an Array - java

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.

your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Related

JOptionPane Descending Array Program Issues

So, I don't see any errors prior to running the program. Basically it's an array program in which the user enter 10 numbers. Once the user types the number of Arrays, it then just pops up a GUI where it says type in an Array of 10. It only lets you do it once, and it just repeats the same number the user typed 10 times. It's all jacked up and it doesn't help that I've only been doing it for several weeks while doing 12 hr shifts. If anyone can point me in the right direction, that'd be awesome!
package Array;
import javax.swing.JOptionPane;
public class Array {
public static void main(String[] args) {
String response;
response = JOptionPane.showInputDialog("Enter the numbers : ");
int n = Integer.parseInt(response);
int[] a=new int[n];
int i,j,temp=0;
JOptionPane.showInputDialog("Enter "+n+" Array Elements : ");
for(i=0;i<n;i++){
a[i]=Integer.parseInt(response);
}
JOptionPane.showMessageDialog(null,"\nArray Elements Are : ");
for(i=0;i<n;i++) {
JOptionPane.showMessageDialog(null," "+a[i]);
}
for(i=0;i<n;i++) {
for(j=i+1;j<n;j++) {
if(a[i]<a[j]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
JOptionPane.showMessageDialog(null,"\nArray Elements in Descending Order : ");
for(i=0;i<n;i++) {
JOptionPane.showMessageDialog(null," "+a[i]);
}
}
}
The core issue is, you're just not asking the user to enter a value for each element in the array and simply parsing the last response, which is the number of elements for the array.
I stripped back your solution and removed the JOptionPane as it's probably not the best solution to the immediate problem. It wouldn't, however, take much to replace Scanner with JOptionPane as generally they are doing the same things
Scanner input = new Scanner(System.in);
System.out.print("Number of elements: ");
String response = input.nextLine();
int numberOfElements = Integer.parseInt(response);
int[] values = new int[numberOfElements];
for (int index = 0; index < numberOfElements; index++) {
System.out.print("Element " + index + ": ");
response = input.nextLine();
int value = Integer.parseInt(response);
values[index] = value;
}
for (int i = 0; i < numberOfElements; i++) {
for (int j = i + 1; j < numberOfElements; j++) {
if (values[i] < values[j]) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
System.out.println("Sorted:");
for (int index = 0; index < numberOfElements; index++) {
System.out.println(values[index]);
}

Random Shuffling an array of integers in Java [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
This is my first time with arrays.
I should prompt the user to enter 5 array values and then display them in random order.
I am quite confused, since it's my first time doing this.
Anyway, my code is here.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length - 1; i--) {
int j = (int) (Math.random() * (i + 1));
myArray[i] = input.nextInt();
System.out.println("The numbers are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
System.out.println("The numbers, shuffled, are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
}
}
}
Thank you everyone for your support.
A - Explanation
Let's say you take the input values in order as {'1','2','3','4','5'}. What shuffling is corrupting the order randomly, so you have to change the position of elements randomly.
In the demo code,
swapArrayElement swaps the elements those that positions are passed as parameters.
getRandom returns a random value between 0 and the range which passed to the method as a parameter.
shuffleArray shuffles the array by changing the positions of elements randomly. Please notify that there is an additional boolean isShuffled[] array and it is boolean because we have to keep the track of positions whether they are shuffled or not.
isArrayShuffled method, checks that if all positions are shuffled or not.
B - Demo Code
import java.util.Scanner;
public class Test {
public static final int ARRAY_LENGTH = 5;
public static void main(String[] args) {
int myArray[] = new int[ARRAY_LENGTH];
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 numbers: ");
for(int i = 0; i < myArray.length; i++)
myArray[i] = input.nextInt();
System.out.println("\nThe numbers are: ");
printIntArray(myArray);
shuffleArray(myArray);
System.out.println("\nThe numbers, shuffled, are: ");
printIntArray(myArray);
input.close(); // no memory leaks!
}
// method for printing array
public static void printIntArray(int[] array) {
for(int i = 0; i < array.length; i++)
System.out.printf("%2d ", array[i]);
System.out.printf("%n"); // use %n for os-agnostic new-line
}
// method for shuffling array
public static void shuffleArray(int[] array) {
int range = array.length;
boolean isShuffled[] = new boolean[range]; // store which positions are shuffled
while(!isArrayShuffled(isShuffled)) {
int positionSrc = getRandom(range);
int positionDst = getRandom(range);
swapArrayElement(array, positionSrc, positionDst);
isShuffled[positionSrc] = true;
isShuffled[positionDst] = true;
}
}
public static int getRandom(int maxRange) {
return (int)(Math.random()*maxRange);
}
public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static boolean isArrayShuffled(boolean[] isShuffled) {
for(int i = 0; i < isShuffled.length; i++)
if(isShuffled[i] == false)
return false;
return true;
}
}
C - Demo Output
Please enter 5 numbers:
1 2 3 4 5
The numbers are:
1 2 3 4 5
The numbers, shuffled, are:
4 2 5 1 3
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void shuffle(int[] arr) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter " + (i + 1) + ". number: ");
myArray[i] = input.nextInt();
}
System.out.println("The numbers are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
shuffle(myArray);
System.out.println("The numbers, shuffled, are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
}
}

About saving and printing distinct numbers in an array

before you help me this is a homework assignment, i have most of all of it done but there is one thing that i cant figure out, 0 doesn't get detected at all. This means if i input 0-9 into the array it will tell me there is only 9 distinct numbers when really there should be 10 and it will print out all the numbers but 0. Can anyone see the problem and please explain it to me becuase i need to understand it.
package javaproject.pkg2;
import java.util.Scanner;
public class JavaProject2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[10];
int d = 0;
System.out.println("Enter Ten Numbers: ");
for(int i = 0; i < numArray.length; i++){
int num = input.nextInt();
if(inArray(numArray,num,numArray.length)){
numArray[i] = num;
d++;
}
}
System.out.println("The number of distinct numbers is " + d);
System.out.print("The distinct numbers are: ");
for(int i = 0; i < d; i++){
System.out.print(numArray[i] + " ");
}
}
public static boolean inArray(int[] array, int searchval, int numvals){
for (int i =0; i < numvals; i++){
if (searchval == array[i]) return false;
}
return true;
}
}
You can use a set to identify distinct values:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> distinctNumbers = new LinkedHashSet<>();
System.out.println("Enter ten Numbers: ");
for (int i = 0; i < 10; i++) {
int number = input.nextInt();
distinctNumbers.add(number);
}
System.out.println("The number of distinct numbers is " + distinctNumbers.size());
System.out.print("The distinct numbers are: ");
for (Integer number : distinctNumbers){
System.out.print(number + " ");
}
}
If a value already exists in a set, it can't be added again. Arrays are not the best fit for your problem, since they must be initialized with a fixed size and you don't know how many distinct values the user will inform.
Take a look at numArray after int[] numArray = new int[10]; - it is initialized with zeros.

Stop and print array from user input

I am new at java programming and am working on an exercise where the user is to input ints into an array and then stop the user input by entering a negative int value. All works well except the array prints 0 beyond the user input. So if a user enters 5 values and then one negative value only the five values should print not the user input values and 95 0s.
Any assistance would be greatly appreciated.
Here is my code:
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array [i] < 0)
{
break;
}
}
for (int i =0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
When you declare an int in Java, it will default to 0 if you do not specify a value for it. When you declare your array,
int array[] = new int [100];
You are essentially making an array of 100 0's. You can see a small example of this by running the following code:
public static void main(String[] args) throws Exception {
int array[] = new int [1];
System.out.println("The value of i is: " + array[0]);
}
What you could do, is store the negative value into your array, and then stop printing if you reach that value.
for (int i =0; i<array.length; i++){
if(array[i]<0){
break;
}
System.out.println(array[i]);
}
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
int totalValuesEntered = 0;
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array[i] < 0)
{
totalValuesEntered = i;
break;
}
}
System.out.println("Your entries are:");
for (int i =0; i<totalValuesEntered; i++)
{
System.out.println(array[i]);
}
}
You are looping 100 times no matter what on the last loop, and you are saving the userinput no matter what they enter.
In order to achieve what you want. Declare a new integer enteredValues to count how many values the user entered before exiting.
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System. in );
int array[] = new int[100];
System.out.println("Enter values up to 100 values, " +
"enter a negative number to quit");
int enteredValues = 0;
for (int i = 0; i < array.length; i++) {
int userInput = scan.nextInt(); //save nextInt to a variable
if (userInput >= 0) {
array[i] = userInput;
enteredValues++;
} else{
break;
}
}
for (int i = 0; i < enteredValues; i++) {
System.out.println(array[i]);
}
}

Java: Unable to get Median calculated with code

I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!

Categories