I have to perform the following basic skills with arrays: Here is a list of everything I had to do:
a) Create an array x of doubles with an initializer list that contains the following values: 8, 4, 5, 21, 7, 9, 18, 2, and 100.
b) Print the number of items in the array.
c) Print the first array item.
d) Print the last array item. Be careful to choose the right index.
e) Use a standard for loop to print all the values in the array.
f) Use a standard for loop to print all the values in the array with labels to indicate the location of each element, such as [0] = xx
g) Use a standard for loop to print all the values in the array in reverse order.
h) Use an enhanced for loop to print all the values in the array.
I am having a lot of trouble with f), I saw that you could label using "JLabel" which I did not learn in my class but I wasn't sure if it could be applied here, here is my code so far. If "JLabel" can't be used, what else would I be able to do? Any help will be appreciated, Thanks!!!
public static void main(String[] args) {
double[] x = {8, 4, 5, 21, 7, 9, 18, 2, 100};
double temp;
System.out.println("The number of items in the array is " + x.length);
System.out.println("The first array item is " + x[0]);
System.out.println("The last array item is " + x[8]);
for(int i = 0; i < 9; i++)
{
System.out.println(x[i] + " ");
}
//F
//JLabel labels[] = new JLabel[8];
//for (int i = 0; i < 9; i++)
//{
//labels[i] = new JLabel("Label" + i);
//}
for(int i =x.length - 1; i >= 0; i--)
{
System.out.println(x[i] + " ");
}
for (double val : x)
{
System.out.println(val + " ");
}
}
}
JLabel is a Swing GUI component. It represents a text label in a GUI. It is not what you want to use here (although I can understand your attraction to the "Label" in its name -- but, you don't make ham with a hammer).
Your requirement is simply "print all the values in the array with labels to indicate the location of each element, such as [0] = xx". That is, "labels" in the dictionary sense, not "labels" as in some explicit special "label" class.
It's simpler than you think, you may be over-complicating this! For example:
for (int i = 0; i < x.length; i ++) {
// 'i' is the index
// 'x[i]' is the value
System.out.println( /* fill this in */ );
}
I'll leave the details as an exercise to you. Hint: If i==1 and x[i]==42 then the output should be [1] = 42.
Related
I need to write a code that will display the last three elements of an array using for loop. 1. The arrays size can be modified and the code should cope with that. 2. The elements should be displayed as they were entered (from left to right).
import java.util.Arrays;
public class Task4 {
public static void main(String[] args) {
int[] array = {7, -3, 9, -11, 18, 99, 2, 11};
System.out.println("Current array: " + Arrays.toString(array));
System.out.println("Last three elements of an array: ");
for (int i = array.length / 2 + 1; i < array.length; i++) {
System.out.print(array[i] + " ");
/*need to display last three elements of an array using for loop.
the elements should be displayed as they were entered(from left-to-right)*/
}
}
}
The code works only for this specific array. My question was is there any alternative solutions that will work for any array size?
you can try to start from the index that equals the length-3 by changing the loop into this :
for (int i = Math.max(0,array.length-3); i < array.length; i++) {
A java stream option here:
IntStream.of(array)
.skip(Math.max(array.length - 3, 0))
.forEach(System.out::println);
I have two arrays. Array1 holds 5 randomly generated numbers and array2 holds 5 guesses inputted by the user. I'm trying to count the matches but the only matches that are being read are the ones in the same position. How can I get my program to count the same number even if it's in a different position?
Here's what I've got so far:
int count = 0;
for (i=0;i<array1.length;i++){
if(array1[i] == array2[i]){
count = count +1;
}
}
System.out.println("matching numbers : "+count);
If the two arrays are both small, i.e. each array contains only five elements, then you need a nested loop. For each element in the random numbers array, iterate through the guesses array.
int count = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
count++;
}
}
}
System.out.println("matching numbers : "+count);
Note that the above is appropriate when both arrays are small. When both arrays are large the above is not appropriate.
You just need the intersection between the two arrays and then to count the size of the result array.
So you can avoid to manually loop over the two arrays just simply using the retainAll method on List class:
https://docs.oracle.com/javase/7/docs/api/java/util/List.html#retainAll
Here is a junit test that shows how to solve using this approach:
#Test
public void TestArraysIntersection() {
Integer[] randomlyGenerated = {1,2,3,4,5};
Integer[] userInput = {4,2,5,3,6};
System.out.println("Randomly generated numbers are: " + Arrays.toString(randomlyGenerated));
System.out.println("Number selected by the user are: " + Arrays.toString(userInput));
List<Integer> intersectionList = new ArrayList<>(Arrays.asList(randomlyGenerated));
intersectionList.retainAll(Arrays.asList(userInput));
System.out.println("Matching numbers are " + intersectionList.size() + " and the values are: "+ intersectionList);
}
Test result is the following:
Randomly generated numbers are: [1, 2, 3, 4, 5]
Number selected by the user are: [4, 2, 5, 3, 6]
Matching numbers are 4 and the values are: [2, 3, 4, 5]
You need to loop through both arrays. In your code you are comparing each element of one array with the element in the same position of the other array, but you have to compare each element of one array with every element of the other array, like this:
public class MyClass {
public static void main(String args[]) {
int[] numbers = {1, 3, 0, 6};
int[] guesses = {3, 8, 5, 1, 2};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < guesses.length; j++) {
if (numbers[i] == guesses[j]) {
System.out.println("A match on positions "+i+" and "+j+". "+numbers[i]+" = "+guesses[j]);
}
}
}
}
}
Output:
A match on positions 0 and 3. 1 = 1
A match on positions 1 and 0. 3 = 3
Of course, instead of outputting the values that match, you can instead increment a count like in your example, and show instead how many elements matched.
I have a Map structure that contains an Integer as a key and a set of Objects as the values. However, I have overriden the toString method to get the Integer values of the values. So, example, the Map would look like
Key: 1 Values: [1, 2, 4]
I am having a bit trouble constructing a 2D Matrix out out this Map Structure. When I am looping through, I am checking to see if my iterator value is a key in the Map but I am having trouble checking to see if the second iterator is equal to the set value. This is the part of the code in question
for (int i = 1; i < this.adjacencyMatrix[0].length; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 1; i < this.adjacencyMatrix.length; i++) {
System.out.print(i + " ");
for (int j = 1; j < this.adjacencyMatrix[i].length; j++) {
if (this.nodes.containsKey(i)) {
// Handle the set
this.adjacencyMatrix[i][j] = 1;
} else {
this.adjacencyMatrix[i][j] = 0;
}
System.out.print(this.adjacencyMatrix[i][j] + " ");
}
System.out.println();
}
My matrix right now will print 1's for the entire row of the map keys.
Example, if 4 is a key, the entire 10 rows will all be printing 1. However, say I have a mapping like 4-- [1, 2, 4] only 1, 2, 4 should have 1's in the given row, all the rest should be 0.
The if-condition (containsKey) is true (or false) for every step of the inner loop.
The inner loop should be replaced by two loops: First loop on the index j and initialize all values to 0. Then iterate on the elements in the nodes set, take each value and use it as index:
adjacencyMatrix[i][value] = 1
I have to locate and list all duplicate index values in array.
Example:
int[] array = { 0, 7, 9, 1, 5, 8, 7, 4, 7, 3};
7 is located in three different locations at index 1, 6, and 8. How would I go about modifying my existing code in order to have outputResults.setText() show the location of the duplicate values? outputResults.setText() is JTextField if that helps.
String tmp1 = getNumbers.getText();
try {
int search = Integer.parseInt(tmp1);
for (p = 0; p < array.length; p++) {
if(array[p]==search) {
b = true;
index = p;
}
}
if(b==true)
outputResults.setText(search + " was in the following fields of the array " + index);
else
throw new NumberNotFoundException("Your number was not found.");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(getContentPane(), "You can only search for integers.");
} catch (NumberNotFoundException ex) {
JOptionPane.showMessageDialog(getContentPane(), ex.getMessage());
}
At it's current state, it will only list the last time the duplicate number was located which would be index 8 based on my example. The list of numbers in the array is inputted by the user, and I'm not allowed to sort the values. My original guess was to create a nested loop and whenever it located an duplicated number, add p (current index it's searching) to a new array. I would then list the full array in outputResults.setText() but it gave several warnings and errors when I tried.
The full code can be found here if needed: http://pastebin.com/R7rfWAv0
And yes, the full program is a mess but it gets the job done and I was having such a headache with it. Also note, in the full program, the professor asked us to throw an exception if a duplicate value was detected as extra credit. I did it, but I commented it out to finish the original assignment so please disregard it.
I think you should use a List to record the indexs
List<Integer> indexs =new ArrayList<Integer>();
for (p = 0; p < array.length; p++) {
if(array[p]==search) {
indexs.add(p);
}
}
if(p.length()>0){
//print the result
}
No need for Hash tables, lists or whatever, you can do this very easily as so:
int [] array = { 0, 7, 9, 1, 5, 8, 7, 4, 7, 3};
int pointer=0;
int currNumber;
while(pointer<array.length)
{
currNumber=array[pointer];
for(int i=0;i<array.length;i++){
if(currNumber==array[i] && i>pointer){
System.out.println("Duplicate for "+currNumber +" in " +i);
break;
}
}
pointer++;
}
It will print all duplicates for all the numbers in the array.
Duplicate for 7 in 6
Duplicate for 7 in 8
Obviously, you'd probably have to concatenate a string and display it at the end of the loop by calling outputResults.setText()
Demo here.
How about just two for loops?
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j]) {
System.out.println("Duplicate - " + array[i] + " found at index " + i + " and " + j);
}
}
}
One option would be to create a HashMap that used the value as the key, and a collection of indexes for the value. As you scan the array, if the value isn't in the HashMap, add it w/ a new collection of the index. If the value is in the array, pull the collection, add the next index and finish the iteration.
Once that's complete, iterate the HashMap, any entry who has a value with size() > 1 has duplicates.
As you're iterating through the array, you are overwriting any previously found index with the line index = p;. This line only works if there is one occurrence of the value being searched. Let index be a string and concat to it each time you arrive at that line, so that index += " "+p;. Your line:
outputResults.setText(search + " was in the following fields of the array " + index);
will then print out all of the found indices for the value being searched.
So, there are several ways to complete your solution (some naive and some optimal) with that being said; you should think through what you're trying to achieve and figure out what each line is doing in your code (debug) when you have an issue.
I am using Java Arrays.sort in order to sort elements of a two dimensional array:
int[][] RAM = new int[4][10000];
I fill the RAM array with integers and then call:
for (i=0;i<4;i++){
Arrays.sort(RAM[i]);
System.out.println(i);
}
This results in all elements of RAM[][] being filled with zeros. What am I doing wrong?
Did you actually fill the Array with numbers first?
And if you did, you are only printing out the First part of your 2D array. You need to print out all 40,000 entries. 10,000 for each array in array. So [0][0...9999], [1][0...9999] etc.
public static void show (int [][] list)
{
System.out.println ("- show: -");
for (int [] ia : list) {
for (int i : ia)
System.out.print (i + ", ");
System.out.println ();
}
System.out.println ("---");
}
static Random random = new Random ();
public static void main (String [] args)
{
int[][] RAM = new int[4][2];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 2; ++j)
{
RAM[i][j] = random.nextInt (20);
System.out.print (i*2 +j);
}
}
show (RAM);
for (int i=0; i<4; i++) {
Arrays.sort (RAM[i]);
}
show (RAM);
System.out.println ();
}
Result:
- show: -
8, 13,
12, 10,
16, 3,
7, 1,
---
- show: -
8, 13,
10, 12,
3, 16,
1, 7,
---
I think the reason is that you didn't set a value for all elements of your array. For the item you didn't initialize, the default value is 0. Thus when you sort the all items in the array, the 0s are swapped to the first part of your array. If you output the first parts of the array, all you see are zeros. I guess so.