trying to print out array from random numbers from another class - java

I have basically finished this piece of code, but when I print out the numbers from the array in the lottery class, I get a bunch of seeming gibberish. How can I fix the problem?
import java.util.Scanner;
public class Hw5pr2
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int[] rand = new int[5];
System.out.println("please enter 5 number");
for (int a = 0; a<rand.length; a++)
{
rand[a] = kb.nextInt();
}
Lottery k = new Lottery();
System.out.print("your number are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(rand[a]+",");
}
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+",");
}
System.out.println("you have " + k.RanInput(rand) + " matching number!!");
}
}
import java.util.Random;
public class Lottery
{
private int[] lotteryNumbers = new int[5];
public Lottery()
{
Random rand = new Random();
for (int a = 0; a<lotteryNumbers.length; a++)
{
lotteryNumbers[a] = rand.nextInt(9)+1;
}
}
public int RanInput(int[] Inran)
{
int b = 0;
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
}
public int[] getArray()
{
return lotteryNumbers;
}
}

for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()+","); //k.getArray() which returns you an entire array
}
You are trying to print the entire array. That's why it may show you the reference instead. You can store the array in a temp array and print the contents of that array.
You may try doing something like this:
int[] winningNum = k.getArray();
for (int a = 0; a < winningNum.length; a++)
System.out.print(winningNum[a] + ",");

try something like
System.out.print("The Winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]+",");
}
note here
for (int a = 0; a<lotteryNumbers.length; a++)
{
if (lotteryNumbers[a] == Inran[a])
{
b++;
}
}
return b;
this is always return lotteryNumbers.length-1; beacause always two arrays are same

When you print out the array, to the best of my knowledge, it calls the toString method.
This returns a hash of the object, not the values it contains. You can call the static method toString from the Arrays class also to print the string values of the array.
System.out.print(Arrays.toString(k.getArray())+",");
or use a for loop
for (int a = 0; a < k.getArray().length; a++)
{
System.out.print(k.getArray()[a]+",");
}

A few things to note:
As others have mentioned, if you want to print the elements of an array, a simple way to do it is with a for loop. Your code won't work the way you want it to unless you access each element of k's lotteryNumbers array separately:
System.out.print("The winning numbers are: ");
for (int a = 0; a < rand.length; a++)
{
System.out.print(k.getArray()[a]); //make sure to include the [a]
if(a != rand.length - 1) //added to help make prints more readable
System.out.print(", ");
}
Secondly, your RanInput function won't behave the way you want it to, assuming you wanted to see how many of the user's numbers match the lottery numbers. Currently, it just checks if the nth number inputted matches the nth lotto number chosen, which is unlikely to be true. Instead, you should do something like this:
public int RanInput(int[] Inran)
{
int count = 0;
for (int i = 0; i<lotteryNumbers.length; i++)
{
for(int j = 0; j < lotteryNumbers.length; j++) {
if (lotteryNumbers[j] == Inran[i])
{
count++;
}
}
}
return count;
}
It compares each of the inputted numbers with each of the lotto numbers. There are more efficient ways to do this than the code above, but I think it should be good enough for now.
I don't think the code you use to generate the lottery numbers account for duplicates (e.g. the numbers might be 1, 2, 2, 1, 3) so you should fix that.
Finally, here's some error checking you should implement if you want to be thorough:
make sure the user inputs exactly 5 numbers
all positive integers
are below some upper bound (say, 100)

Related

How to accept integers into 2 different int arrays simultaneously and form a new array in java in the same order?

If you are accepting integers simultaneously one after another for a different array each time an int is accepted, then how do you form a third array with the digits of the 2 other arrays in the order in which they are accepted?
import java.util.Scanner;
class Integer_Acceptor
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
for (int i = 0; i < 10; i++)
{
if (i%2 != 0)
{
c[i] = a[i];
c[i+1] = b[i];
}
}
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
}
}
This is the program I made but obviously it doesn't work (ArrayOutofBounds) as the integer in array increases by 2 every time. How do I make this program give the combined integers of both arrays in the order in which they are accepted?
The idea of separating the inputs is interesting, but it seems to be giving you more problems than solutions when trying to join them together later.
Why not just accept everything into a single array, and when reading it, you test its index to see where it should go? If you have two possible uses for your numbers, odd and even positions will get you there; if three, multiples of 3 plus or minus one, and so on.
This seems to be a simpler solution, and both the input and data storage are as straightforward as can be.
The code you provided will give an ArrayOutofBounds error as you mentioned because c[10] does not exist. (In the second for loop when i = 9, you will be trying to set c[10] which does not exist).
From what I understand, you want array c to contain the following elements:
c = { a[0], b[0], a[1], b[1], a[2], b[2], a[3], b[3], a[4], b[4] }
What I did was to create two separate indices that will help navigate through array a and array b and set c[i] according to whether i was even or odd and then incrementing the respective aIndex or bIndex. I wrote this code below that works the way I described
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
// Fixed code snipped
int aIndex = 0;
int bIndex = 0;
for (int i = 0; i < 10; i++)
{
// even index
if(i%2 == 0){
c[i] = a[aIndex];
aIndex++;
}
else
{
c[i] = b[bIndex];
bIndex++;
}
}
////
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
Let me know if you need further clarification on how this works so I can edit in a more in-depth explanation.

Moving specific elements of an array from one array to another of different size

I was asked to
Create a method with a single parameter, an array of integers, that will return an array of integers. Count how many odd values exists within the array. Create a new array with that many elements. Place all the odd values into this new array ( that is all odd values from the array passed through as a parameter ). Return this new array
but I am having some difficulty in transferring the odd values into the new array. I can get the correct size based on the number of odd values in the first array but right now they appear as zeros. Here is the code:
import java.util.Scanner;
public class Main {
public static int output(int[]beans){
int sum = 0;
for (int p = 0; p < beans.length; p++){
if(beans[p]%2 != 0){
sum++;
}
}
System.out.print("The number of odd vaules in this array are: "+sum);
System.out.println();
int[] notbeans = new int[sum];
System.out.print("The odd values within the first array are: ");
for (int index = 0; index < beans.length; index++){
if( beans [index] %2 != 0){
System.out.print(beans[index]);
}
}
System.out.println();
for (int g = 0; g < notbeans.length; g++){
System.out.print(notbeans[g]);
}
return notbeans[1];
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
output(array);
}
}
According to your question, method output needs to...
Return this new array
Hence method output needs to return int[] (and not int).
After counting the number of odd values in the array passed to method output and creating the array that the method needs to return, in order to populate the returned array, you need to maintain a second [array] index. You are using the same index to populate the returned array and to iterate the array parameter. The returned array may be smaller in size, i.e. contain less elements, than the array parameter so using the same index for both arrays may cause method output to throw ArrayIndexOutOfBoundsException. In any method, you should also always check whether the method parameters are valid.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int[] output(int[] beans) {
int sum = 0;
if (beans != null && beans.length > 0) {
for (int p = 0; p < beans.length; p++) {
if (beans[p] % 2 == 1) {
sum++;
}
}
}
int[] notBeans = new int[sum];
int j = 0;
for (int index = 0; index < beans.length; index++) {
if (beans[index] % 2 == 1) {
notBeans[j++] = beans[index];
}
}
return notBeans;
}
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[] array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
System.out.println(Arrays.toString(output(array)));
}
}
Your output function should return an array, so return type will not be int. It will be int[]. See the below code and let me know.
public class Main {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int[]array = new int[5];
for (int t = 0; t < array.length; t++){
System.out.print("Enter an integer: ");
array[t] = key.nextInt();
}
int[] arr=output(array);
for(int i=0;i<arr.length;i++){
int val=arr[i];
if(val!=0){
System.out.println(val);
}
}
}
public static int[] output(int[]beans){
int[] notBeans=new int[beans.length];
int i=0;
for(int v:beans){
if(v%2!=0){
notBeans[i]=v;
i++;
}
}
return notBeans;
}
}

What would be method to find count which contains only numbers one by one

I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.

My java program won't run properly i want it to input several numbers into an array and put the into another array in order from lowest to highest

I want to make a program in java that takes user input of several numbes and displays them to the screen in order from the highest to lowest
But it wont work and i don't know why.
Thanks in advance
Note (this my firs time posting anything here)
public class project {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr1 = new int[5];
int arr2[] = new int[5];
System.out.println("enter 5 numbers");
for (int i=0; i<=4; i++){
int Uinput = input.nextInt();
arr1[i] = Uinput;
}
for(int b = 0; b <= 4; b++){
for (int a = 0; a <=100;a++){
for(int j = 0; j <=4; j++){
if ( a== arr1[j]){
arr2[b]=arr1[j];
}
}
}
}
System.out.println(arr2 [0]);
System.out.println(arr2 [1]);
System.out.println(arr2 [2]);
System.out.println(arr2 [3]);
System.out.println(arr2 [4]);
}
}
The problem with your loops is that you are continuing with the comparison even after you have set your element in arr2. That is why they all end up as the highest number.
You only want to set each element once. You could try and put breaks into each for loop, but i the easier solution would be;
int b = 0;
while(b < 5) {
for (int a = 0; a <=100;a++){
for(int j = 0; j <=4; j++){
if (a == arr1[j]){
arr2[b]=arr1[j];
b++;
}
}
}
}
By incrementing b every time you set the element, you are making sure each element is only set once.
This said, KevinO is correct and there are other better ways to sort the numbers (for example, your current code can't handle numbers greater than 100). I would recommend checking out the link

How do I sort numbers from an array into two different arrays in java?

I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}

Categories

Resources