Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The objective of this program is to take the two arrays x and y and then create and array list contain numbers that occur in both x and y and then to print out this array of matching numbers. When I go to compile it gives me the error class expected on line 19 and another error saying ";" expected on the same line which I'm guessing is due to the other error. Is it just an error on that line or is it a bigger issue?
import java.util.ArrayList;
import java.util.Arrays;
public class FindCommon {
public static void main (String[] args) {
ArrayList list = new ArrayList();
int[] x = {1, 4, 3, 0, 1, 2};
int[] y = {6, 4, 5, 0, 6, 1};
for (int i = 0; i < x.length ; i++){
int number = x[i];
if (y[].(contains(x[i])){ // Line 19
list.add(x[i]);
}
System.out.println(list);
}
}
}
if (y[].(contains(x[i])){
The above line is invalid for a various of reasons. The index for y array is missing. Also according to the requirement, you need to call the contains() method on the list and not the array. And there seems to be an extra pair of braces.
if (!list.contains(x[i])){
list.add(x[i]); // Add to the list if it doesn't contain the value already
}
You need to do the same for the elements of y too.
Better Solution: You can use a Set instead of a List. It'll eliminate the duplicates for you. All you need to do is just add elements to your set from both the arrays.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
public static int createArray(int theListSize)
{
ArrayList<Integer> possiblePrimeNum = new ArrayList<Integer>();
for (int i=0; i<=theListSize; i++) //simply creates the array
{
possiblePrimeNum.add(i, i+2);
}
return possiblePrimeNum;
}
I don't understand this code. I mean that I understand what I'm going to do, but I don't know why the array won't return. What's wrong here?
possiblePrimeNum=createArray(theListSize);
You declared this method as returning a single int value, a single number, and a primitive (not an object).
An ArrayList is a collection of numbers, Integer objects (not primitives).
You said:
Dynamic 1D Array
I do not know what you mean by "Dynamic".
An array in Java is not the same as an ArrayList. The first is a built-in basic type in Java. The second is a class found in the Java Collections Framework, bundled with all Java distributions.
Tutorial on arrays by Oracle
Tutorial on Collections by Oracle
You asked:
I mean that I understand what I'm going to do, but I don't know why the array won't return.
Change your method to return a List of Integer objects rather than a single int. Something like this.
public static List < Integer > possiblePrimes ( final int countOfPrimes )
{
List < Integer > possiblePrimes = new ArrayList < Integer >( countOfPrimes );
for ( int i = 0 ; i <= countOfPrimes ; i++ )
{
possiblePrimes.add( i , i + 2 );
}
return List.copyOf( possiblePrimes ); // Return a unmodifiable list, as a general best practice.
}
Call that method like this.
List < Integer > maybePrimes = App.possiblePrimes( 7 );
System.out.println( "maybePrimes = " + maybePrimes );
When run:
maybePrimes = [2, 3, 4, 5, 6, 7, 8, 9]
I think your algorithm for finding candidate primes needs some more work. 😵💫
If you really want an array, see:
How to convert an ArrayList containing Integers to primitive int array?
Convert ArrayList of Integer Objects to an int array?
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
The program is meant to invert the values in the array. When the program is run, the only values that show are 3 and 2, then it ends. I've been looking online but I can't figure out why this happens. Switching val[i] for temp in the SOP gives values of 0 and 1 then ends.
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length/2;i++)
{
temp=val[i];
val[i]=val[val.length - 1 - i];
val[val.length - 1 - i]=temp;
System.out.println(val[i]);
}
Because your for loop only iterate for values 0 and 1, then at the end it prints only 0th and 1st elements, try following
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length/2;i++) {
temp=val[i];
val[i]=val[val.length - 1 - i];
val[val.length - 1 - i]=temp;
}
for(int i=0;i<val.length;i++){
System.out.println(val[i]);
}
It makes sense to use val.lenth/2 to only traverse half of the array, swapping values as you go. It does not make sense to only traverse half of the array while trying to print the entire array. Try using another for loop to print out the contents of the ENTIRE array.
edit: I tried not to just give the answer
for(int i=0;i<val.length/2;i++)
val.length/2= 4/2 = 2 so that the for loop will only run twice. Thats why it prints only the 3 and 2.
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length;i++)
{
if(i<val.length/2){
temp=val[i];
val[i]=val[val.length- 1 - i];
val[val.length- 1 - i]=temp;
}
System.out.println(val[i]);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am new to this site and new to java so pleas help me out. If i have array of positive and negative numbers all are int,
how to sort all the positive ones in a new array and all negative in a other new array.
Asking a question in StackOverflow without any selfstudy on basics would attract downvotes. Kindly take time in doing your research. However to make you understand the way to solve I am providing you with a solution.
Step 1: You have an array of positive and negative values
Integer[] initialArray = new Integer[10];
//This contains the list of all values.
Step 2: Create two ArrayLists to save the negative and positive values in each of these.
ArrayList<Integer> positiveValues = new ArrayList<>();
ArrayList<Integer> negativeValues = new ArrayList<>();
Step 3: Iterate through initialArray and save the respective values in both lists.
for(int i =0; i< initialArray.length; i++) {
if(initialArray[i] < 0) {
negativeValues.add(initialArray[i]);
} else {
positiveValues.add(initialArray[i]);
}
}
Step 4: Now sort the values
Collections.sort(negativeValues);
Collections.sort(positiveValues);
Step 5: If Required If you need in arrays instead of ArrayList,
Integer[] negativeArray = new Integer[negativeValues.size()];
Integer[] positiveArray = new Integer[positiveValues.size()];
And cast these to get the array
I actually think this is a pretty good question. Here is an implementation you can try using Java 8 streams.
Given an integer array full of mixed negative/positive numbers:
int[] a = new int[] { 5, 6, 7, 4, -2, 5, -9, 2 };
One solution could be as follows:
int[] pos = Arrays.stream(a).filter(i -> i >= 0).sorted().toArray();
int[] neg = Arrays.stream(a).filter(i -> i < 0).sorted().toArray();
The pos[] array will have all the positive numbers sorted, and neg[] all the negative numbers sorted. The only thing I really dislike is that a[] is traversed twice, but at least it is short.
First seperate positive and negative numbers. I mean find size of positive numbers and create-set new positive numbers array. Then find size of negative numbers and create-set new negative numbers array.
Then just call sort method on both arrays.
Arrays.sort(array);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Good evening
i'm trying to solve a question which is :
You are given a int[] marks containing the grades you have received so far in a class. Each
grade is between 0 and 10, inclusive. Assuming that you will receive a 10 on all future
assignments, determine the minimum number of future assignments that are needed for you to
receive a final grade of 10. You will receive a final grade of 10 if your average grade is 9.5 or
higher.
Definition Class: AimToTen Method: need Parameters:
int[] Returns: int Method signature: int need(int[]
marks) (be sure your method is public) Examples 1)
{9, 10, 10, 9} Returns: 0 Your average is already 9.5, so no
future assignments are needed. 2) {8, 9} Returns:
4 In this case you need 4 more assignments. With each
completed assignment, your average could increase to 9, 9.25, 9.4
and 9.5, respectively
My attempt to solve is :
public int need(int[] marks) {
int i=0, sum = 0, avg = 0, k = 0, counter = 0, ToCompleteMarks[] = null;
for (i; i < marks.length; i++) {
sum = sum + marks[i];
ToCompleteMarks[i] = marks[i] + ToCompleteMarks[i];// To copy the array so when i add 10 later to the program the original array does not change > good ?
}
avg = sum / marks.length;
while (avg < 9.5)
ToCompleteMarks[i]; //I need to add the number 10 to the array then get back to calculate the avg . But no ideas how to do that ! .
counter++;
return counter;
}
if you could help me with that I would be really greatful
thanks
We can do the below mentioned steps:
1. Get the difference between the avg calculated and the desired average(9.5)
LEts say that the calculated average is 8.
Difference would be 9.5-8 = 1.5
Hence we can take the upper limit(ceiling value) of the difference using Math.ceil(difference). Here it would be 2. Thus we need to add two assignments to the array.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My assignment is to make "Yahtzee" game on Java Program.
I am almost done except the Small Straight method. (Cannot figure it out.)
Small Straight is when the dice got 4 straight number. (Ex. 12334, 23345, 34556, and etc.)
Here is my code of isSmallStraight method (This code is not completed!):
public static boolean isSmallStraight(List<Die> dice) {
boolean result = false;
List<Die> copy = new ArrayList<Die>(dice);
Collections.sort(copy);
List<Die> testCase1 = new ArrayList<Die>();
testCase1.add(new Die(1));
testCase1.add(new Die(2));
testCase1.add(new Die(3));
if(copy.containsAll(testCase1)) {
result = true;
System.out.println(result);
}
return result;
}
What I want to do in here is I passed 5 random numbers of dice from the main method (List dice) and put them into the "copy" object.
Since I need to use java.util.List.containsAll() method(requirement), I think I need to make one other object "testCase1" to compare with "copy". (If you have other method to solve this question, it is fine at least you use java.util.containsAll() method.)
However, what I don't know right now is if I use dice.add(new Die(3)), it means the program picks random numbers from 1,2, and 3. (Not die number 3) - Also, it gave me compile-time error.
So, I want to know how I can store dice specific number 1,2,3, and 4 for "testCase1", 2,3,4, and 5 for "testCase2", and 3,4,5, and 6 for "testCase3" and use copy.containsAll(testCase1) becomes true.
Please help me as soon as possible!
PS. Die class is already programmed by my professor. (So, cannot change any in the Die class).
Put the numbers into a TreeSet to get rid of duplicates and get sorting for free.
You have 4 straight dice if:
The set contains exactly 4 numbers
The difference between the largest and the smallest is 3
The method I like to use (for large and small straights as well as all other scoring) is to create a new int array from the int array that holds the dice values. Like this:
int[] numDice = new int[6];
for (int i: diceValues)
numDice[i-1] += 1;
This counts up all your dice and puts the number of each, in order, in a new array. For instance, if the 5 dice you rolled were 3, 4, 3, 1, and 6, your new array would be {1, 0, 2, 1, 0, 1}, and a yahtzee of all 4s would turn into {0, 0, 0, 5, 0, 0}. From this new array it's fairly trivial to determine all of the scores. For straights:
int straightCount = 0;
for (int i: numDice) {
if (i > 0)
straightCount++;
else
straightCount = 0;
if (straightCount > 3)
smallStraight = true;
if (straightCount > 4)
largeStraight = true;
}
If you wanted to you could use this array to easily determine all the valid scores in one short method, and store the booleans in a single array.