I have an array with 5 random numbers. Like this:
int correct[] = {11,23,54,13,5};
I have another array, the user's guesses. Like this:
int userGuesses[] = {23,5,5,11,50};
I want to find how many times the user guessed the lotter numbers correctly, so it cannot repeat.
Like if userGuesses has 2 same numbers and user guessed correctly, but correct[] has only one value, not two, then the program shouldn't count that.
This is what I have so far.
public static void main(String[] args) {
int correct = 0;
int good[] = {1,2,3,4,5};
int bad[] = {2,1,5,5,12,3};
for (int i = 0; i < 5; i++) {
if(good[i] == bad[i]){
correct++;
}
}
System.out.println(correct);
}
Try something like this:
int correct = 0;
int good[] = {1, 2, 3, 4, 5}; // correct answers
int bad[] = {2, 1, 5, 5, 12, 3}; // user guesses
for (int i = 0; i < good.length; i++) {
for (int j = 0; j < bad.length; j++) {
if (good[i] == bad[j]) {
correct++;
break;
}
}
}
System.out.println(correct);
Ok, I wrote a small Java program and it actually works. The actual answer should be 4, because user guessed (assume the 'bad' array is user's guesses) numbers: 1,2,3 and 5, and we do not count it twice.
Copy the values to be tested into a temporary array. Then, change the values in the temporary array when a match is found.
int correct = 0;
int[] temp_array = bad.clone();// copy values to be tested into temp array
for(int i = 0; i < good.length; i++)
{
for(int j = 0; j < bad.length; j++)
{
if(good[i] == temp_array[j])// match found
{
correct++;// increment correct
temp_array[j] = -999;// change value to out-of-range
break;
}
}
}
System.out.println("number correct is " + correct);
Related
For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}
if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!
Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections
My goal is to move the elements in the ar[] array into the sorted[] array and sort them from least to greatest. I'm having trouble with that part though because my loop is supposed to find the smallest element in the array and then replace the element with a large number. I think I have most of the code down but when I run the program, every element in the sorted[] array is 2. What am I doing wrong here?
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
ar[i] = 1000000;
}
// print sorted array:
for (int i=0; i<sorted.length; i++)
{
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
What about something like this?
Short and sweet:
import java.util.Arrays;
public class Lab1
{
public static void main(String argv[])
{
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = ar.clone();
Arrays.sort(sorted);
System.out.println("Original array: " + Arrays.toString(ar));
System.out.println("Sorted array: " + Arrays.toString(sorted));
}
}
Output:
Original array: [7, 5, 2, 8, 4, 9, 6]
Sorted array: [2, 4, 5, 6, 7, 8, 9]
I don't have my pc now but I think the problem is that once you set the variable smallest with 2 the first time, it remains 2 forever and there is no other number smaller. So I think you are executing the internal if just once and the value is always 2.
Edit. I think that moving the smallest inizialization below the fist for should work.
You didn't do any action when this condition is not true.
if (ar[n] < smallest)
So just smallest element can pass this check and goes on new array.
Also you can sort your array in better shape like this
List<Integer> ar = Arrays.as list ( *your numbers here*);
Collections.sort(ar):
oops, there is a problem inside your loop,
which copy the smallest in ar[] into sorted[], which is 2,
so you are getting 2 in every element inside sorted[].
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n]; <----YOU ALWAYS GET 2 HERE
smallestindex = n;
}
}
sorted[i] = smallest; <---- AND SET 2 TO YOUR sorted[] HERE
ar[i] = 1000000;
}
I don't know if you want a solution or solve it yourself since your question is asking what's wrong, but here it is
for (int i=0; i<ar.length; i++)
{
for (int n=0; n<ar.length; n++)
{
if (ar[n] < smallest)
{
smallest = ar[n];
smallestindex = n;
ar[n] = 1000000; <----CHANGE THE SMALLEST ITEM HERE RATHER THAN OUTSIDE
}
}
sorted[i] = smallest;
}
btw, to make a sorted copy in a easier way:
Firsy make a copy:
int[] sorted = ar.clone();
Then, sort it using Java Util:
Arrays.sort(sorted);
Just 2 lines you get what you want.
I just can't understand, why do we require this, like sorting into another array. You can sort within the array using Arrays.sort() method, or if you want to sort in a different array, you can take following steps:
Copy the array to new array.
Sort the new array and then sort.
If you still want to go with your implementation, then I have refactored your code. Now your code works fine and looks like:
public class Prog1 {
public static void main(String[] args) {
int ar[] = { 7, 5, 2, 8, 4, 9, 6 };
int sorted[] = new int[ar.length];
int smallest = ar[0];
int smallestindex = 0;
for (int i = 0; i < ar.length; i++) {
for (int n = 0; n < ar.length; n++) {
if (ar[n] < smallest) {
smallest = ar[n];
smallestindex = n;
}
}
sorted[i] = smallest;
//Your mistake was here.
ar[smallestindex] = 1000000;
smallest=ar[0];
smallestindex=0;
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
}
}
Your mistake was that you were not reassigning 'smallest' variable. As it was pointing to the smallest element of array so it doesn't get updated in next run because no element in array is less than this variable. Hope you get it. If any questions, you still have, please ask.
Because each time you crush old value (big value) and you don't save it for shifting
smallest = ar[n]; smallestindex = n; You need to add another variable to change values between cells ,or use arraylist for easy way.
int ar[] = {7, 5, 2, 8, 4, 9, 6};
int sorted[] = new int[ar.length];
int smallest = ar[0];
for (int i = 0; i < ar.length ; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) {
smallest = ar[j]; //save small value
ar[j] = ar[i];//transaction between two comparables cells
ar[i] = smallest;//set small value as first
}
sorted[i]=ar[i]; //set first small value
}
}
// print sorted array:
for (int i = 0; i < sorted.length; i++) {
System.out.println("sorted[" + i + "] = " + sorted[i]);
}
It seems you want to sort by using an algorithm called 'Selection Sort', but your code is a poorly implement.
You can learn from this brother's question and check the answers below that:
Selection Sort Example
I'm almost new at Java! I want to control if there are 4 consecutive elements in an array with 5 elements. Is there any way to do that? Can someone help me with that? Thanks! Consecutive like {2, 3, 4, 5}. If there is {3, 4, 2, 5} for example this is not consecutive.I want just a simple example if someone can help me.
I did this but I think this is incorrect:
public int katerTeNjepasnjeshme()
{
int[] numrat=new int[zar.length];
for(int i=0;i<zar.length;i++)
numrat[i]=zar[i].getValue();
int shuma=0;
for(int i=0;i<zar.length-1;i++)
{
if(zar[i+1].getValue()==(zar[i].getValue()+1))
Joptionpane.showMessageDialog(null,"Tere are cons elements");
}
Here's the general idea:
Keep a counter (initialized appropriately), to keep track of the number of consecutive elements as you iterate over the elements.
If the counter reaches 4, you have found 4 consecutive elements.
If you encounter an element that is not consecutive, then reset the counter to 1, and proceed to check the next element.
Here is a sample code snippet:
public static void findConsecutive()
{
int[] array = {1,2,3,5,6,7,8,10};
int counter = 1;
int i = 1;
for (i = 1; i < array.length; i++)
{
if (array[i] == (array[i-1] + 1))
{
counter++;
if (counter == 4)
{
System.out.println("Consecutive elements are at array index: " + (i - 3) + " to " + i);
break;
}
}
else
{
counter = 1;
}
}
}
i think something like that should work:
int[] mylist = new int[10];
for (int i = 0; i < myList.length; i++) {
int k = 1;
for (int j = 1; j < 5 j++) {
if (mylist[i] == mylist[i+j]-j) {
k++;
}
if (k=5) System.out.println("found");
}
}
As soon as you need to compare two elements of the array you should use proper bounds in the loop, otherwise you will get ArrayIndexOutOfBoundsException
boolean consequtive = true;
for (int i = 0; i < zar.length - 1; i++)
if (zar[i+1].getValue() != zar[i].getValue() + 1) {
consecutive = false;
break;
}
if (consequtive)
Joptionpane.showMessageDialog(null,"Tere are cons elements");
Have a program where the user inputs 10 int values into the array. Lastly I need to pull out the distinct values and display them. Added my second for loop which would determine if the the value is distinct (i.e. meaning if the number appears multiple times it is only displayed once).
For instance, let say I pass in the numbers: 1, 2, 3, 2, 1, 6, 3, 4, 5, 2 the distinct array should only contain numbers {1, 2, 3, 6, 4, 5}
import java.util.Scanner;
import java.io.*;
public class ArrayDistinct {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numbers.length; i++) {
int temp = numbers[i];
int tempTwo = numbers[i + 1];
if (tempTwo == temp) {
count++;
distinctArray[i] = temp;
}
}
// Print out results
} // end main
} // end class
Try this :
Set<Integer> uniqueNumbers = new HashSet<Integer>(Arrays.asList(numbers));
uniqueNumbers will contain only unique values
In Java 8
Stream< T > distinct()
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream. For ordered streams, the
selection of distinct elements is stable (for duplicated elements, the
element appearing first in the encounter order is preserved.) For
unordered streams, no stability guarantees are made.
Code:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
Stream.of(array)
.distinct()
.forEach(i -> System.out.print(" " + i));
Output:
5,10,20,58
Read More About distinct function
Try this code.. it will work
package Exercises;
import java.util.Scanner;
public class E5Second
{
public static void main(String[] args)
{
Scanner In = new Scanner(System.in);
int [] number = new int [10];
fillArr(number);
boolean [] distinct = new boolean [10];
int count = 0;
for (int i = 0; i < number.length; i++)
{
if (isThere(number,i) == false)
{
distinct[i] = true;
count++;
}
}
System.out.println("\nThe number of distinct numbers is " + count);
System.out.print("The distinct numbers are: ");
displayDistinct(number, distinct);
}
public static void fillArr(int [] number)
{
Scanner In = new Scanner(System.in);
System.out.print("Enter ten integers ");
for (int i = 0; i < number.length; i++)
number[i] = In.nextInt();
}
public static boolean isThere(int [] number, int i)
{
for (int j = 0; j < i; j++)
if(number[i] == number[j])
return true;
return false;
}
public static void displayDistinct(int [] number, boolean [] distinct)
{
for (int i = 0; i < distinct.length; i++)
if (distinct[i])
System.out.print(number[i] + " ");
}
}
One possible logic: If you're supposed to only sort out "unique" numbers, then you'll want to test each number as it's entered and added to the first array, and loop through the array and see if it's equal to any of the numbers already there; if not, add it to the "unique" array.
Sets in java doesn't allow duplicates:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
HashSet<Integer> uniques = new HashSet<>(Arrays.asList(array));
That's it.
Something like this should work for you:
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
Set<Integer> set = new HashSet<Integer>();
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
set.add(input.nextInt());
}
for(Integer i : set)
{
System.out.println("" + i);
}
This will only add unique values to the set.
int a[] = { 2, 4, 5, 3, 3, 3, 4, 6 };
int flag = 0;
for (int i = 0; i < a.length; i++)
{
flag = 0;
for (int j = i + 1; j < a.length; j++)
{
if (a[i] == a[j])
{
flag = 1;
}
}
if (flag == 0)
{
System.out.println(a[i]);
}
}
I am making an Array that is 10 integers long, so that each place 0-9 contains a different integer 0-9.
I am having trouble figuring out how to check if the array already contains a certain number, and if so, regenerating a new one.
So far I have:
for (int i = 0; i < perm.length; i++)
{
int num = (int) (Math.random() * 9);
int []
perm[i] = num;
}
Arrays.asList(perm).contains(num)
from How can I test if an array contains a certain value?
for (int i = 0; i < perm.length; i++)
this is not enough to loop like this, if collision happens some slots would have been not initalized.
Overall, for this task you better initialize array with values in order and then shuffle it by using random permutation indexes
here is a complete answer
int[] array = {3,9, 6, 5, 5, 5, 9, 10, 6, 9,9};
SortedSet<Integer> s = new TreeSet();
int numberToCheck=61;
for (int i = 0; i < array.length; i++) {
s.add(array[i]);
}
System.out.println("Number contains:"+!(s.add(numberToCheck)));
System.out.println("Sorted list:");
System.out.print(s);
Adding both string and integer to check is exist or not.
public class existOrNotInArray {
public static void elementExistOrNot() {
// To Check Character exist or not
String array[] = { "AB", "CD", "EF" };
ArrayList arrayList = new ArrayList<>();
String stringToCheck = "AB";
for (int i = 0; i < array.length; i++) {
arrayList.add(array[i]);
}
System.out.println("Character exist : " + arrayList.contains(stringToCheck));
// To Check number exit or not
int arrayNum[] = { 1, 2, 3, 4 }; // integer array
int numberToCheck = 5;
for (int i = 0; i < arrayNum.length; i++) {
arrayList.add(arrayNum[i]);
}
System.out.println("Number exist :" + arrayList.contains(numberToCheck));
}
public static void main(String[] args) {
elementExistOrNot();
}
}