I am trying to sort numbers into two categories. Number (actual number) and count (how many occurrences of this number), all of the numbers are stored in a array of 50 integers. I sort this array in descending order using a bubble sort method.
My print method needs work. The code compiles just fine but when I run the code nothing is output.
Why is my code not printing anything?
Here is my code
public class HW5{
public static void main(String[] args) {
int[] array = new int[50];
bubbleSort(array, 'D');
printArray(array);
}
public static void bubbleSort(int[] array, char d){
int r = (d=='D') ? -1 : 1 ;
for (int f = 0; f < array.length - 1; f ++){
for (int index = 0; index < array.length - 1; index++){
if (array[index] > array[index + 1]){
}
}
}
}
public static void printArray(int[] array){
int count = 0;
int i = 0;
for(i = 0; i < array.length - 1; i++){
if (array[i]== array[i + 1]){
count = count + 1;
}else{
System.out.printf(count + "/t" + array[i]);
count = 0;
}
}
}
}
Why is my code not printing anything?
object array is holding 50 elements all of them with the value set to zero and the printArray method will print if and only IF this condition is false
array[i] != array[i + 1]
but since all elements in the array are 0... you just dont print anything...
Your code is printing anything because you aren't setting your array values to anything. Because you aren't setting your array to anything, java defaults all the values to 0. Your code doesn't output if array[i] == array[i+1] I'd change your print method to this:
public static void printArray(int[] array){
int count = 0;
int i = 0;
for(i = 0; i < array.length - 1; i++){
if (array[i]== array[i + 1]){
count = count + 1;
}else{
System.out.print(count);
count = 0;
}
System.out.print(array[i]); //Moved this line out of the if/else statement so it will always print the array at i
}
}
I only changed the line I commented on. However, if you did change the values of your array, your original code would work. For random values, first you need to import java.util.Math then do the following:
for(int i = 0; i < array.length; i++)
array[i] = (int)Math.random() * 100; //Sets the array at i to a random number between 0 and 100 (non-inclusive)
This will help your code above to work as you wanted. Hope this helps!
EDIT: Fixed a grammar error.
Related
I am practicing creating a randomly generating integers in an array, then randomizing the elements in the array. All is well when I print the numbers, but there seems to be one element that does not print when I am displaying the randomized elements. Is there a step I am leaving out?
public class shufflingArrays {
public static void main(String[] args) {
int[] myList = new int[10];
System.out.println("Numbers:");
for(int i = 0; i < myList.length; i++) {
myList[i] = (int)(Math.random() * 100);
System.out.print(myList[i] + " ");
}
System.out.println("\nRandomized:");
for (int i = myList.length - 1; i > 0; i--){
//Generate index j randomly with 0 <= j <= i
int j = (int)(Math.random() * (i + 1));
//Swap myList[i]; with myList[j]
int temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
System.out.print(myList[i] + " ");
}
}
Your for loop has condition i > 0, which means when i == 0 it will terminate and not print out the first array element.
However, if you're doing the Fisher-Yates shuffle, as it appears, you do indeed need to go from myList.length-1 to 1, so your initial code was correct. You then can't print out all the elements in the array from the same loop, so either use another loop after to print out the elements, or add System.out.print(myList[0]); after.
Ex: for (int i = 4; i > 0; i--)
will run the for loop when i = 4, 3, 2, 1 only and not when i = 0, because the condition there is i > 0. Change the i > 0 condition in for (int i = myList.length - 1; i > 0; i--) to i >= 0 and you will get what you want.
So I have to write a program that accepts 10 numbers (ints) from the keyboard. Each number is to be stored in a different element of an array.
Then my program must then display the contents of the array in reverse order.
int [] array = new int [10];
for(int i = array.length - 1;i >= 0; i--)
{
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
array[i] = number;
}
JOptionPane.showMessageDialog(null, array[i]);
}
I tried to put the JOPtionPane.showMessageDialog outside of the loop but then the program can't find the integer "i". I don't know what to do here :/ Please help :P
You need to enter your data first, then display it thereafter in the order you desire...
int [] array = new int[10];
for (int i = 0; i < array.length - 1; i++) {
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i + 1)));
array[i] = number;
}
for (int i = array.length - 1; i >= 0; i--) {
JOptionPane.showMessageDialog(null, array[i]);
}
I'd also be tempted to simply construct a StringBuilder for your final results and then just show the message dialog once only, rather than for every element of the array, but that's up to yourself :)
i belongs to the loop scope, that's why you can't use it outside of the loop.
To print the reversed array use another loop
// insert the data to the array
int [] array = new int [10];
for(int i = array.length - 1 ; i >= 0 ; i--) {
int number = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number " + (i+1)));
array[i] = number;
}
// print the array
for (int i = 0 ; i < array.length ; ++i) {
JOptionPane.showMessageDialog(null, array[i]);
}
That's because you've declared in in for loop, so it has loop scope. Declare it before loop to reuse it after loop finishes
int i;
for(i = array.length - 1;i >= 0; i--)
After that, you can make another loop:
for(i = 0; i < array.length; i++)
to print it in reverse order.
You need two for loops. The first iterates from 0 to 9 and asks for the number and puts it in the array. The second iterates from 9 to 0 and prints the numbers in the array
I'm quite new to Java and recently I wanted to practice more. So I stumbled in this. I wanted to print out all the values in the array using Array.sort, but all I get is:1,2,3,4,5,6 instead of;22,51,67,12,98,34.
Here is the code:
public static void main(String[] args) {
int[] array;
array =new int[6];
array[0]=22;
array[1]=51;
array[2]=67;
array[3]=12;
array[4]=98;
array[5]=34;
Arrays.sort(array);
int i;
for (i=0; i < array.length; i++){
array[i]= i+1;
System.out.println("num is"+array[i]);
}
You're refilling the elements in array[i] inside the for loop. Just print the contents of the array:
for (i=0; i < array.length; i++){
//remove this line since it's setting the value of (i+1) to array[i]
//array[i]= i+1;
//leave this line only
System.out.println("num is"+array[i]);
}
Or, use Arrays.toString to display the content of your array:
//no for loop needed
System.out.println("Array data: " + Arrays.toString(array));
You could always use your own code, EG:
private void butgoActionPerformed(java.awt.event.ActionEvent evt) {
int nums[] = {13,6, 1, 25,18,12};
//Array is called "nums", holds random numbers and such
int place = 0;
int check = 0;
while (place < nums.length - 1) {
while (check < nums.length) {
// "Check" loops inside place and checks to see where larger
if (nums[place] > nums[check]) {
//Change To < For Descending
int temp = nums[place];
nums[place] = nums[check];
//"Check" swaps the values around
nums[check] = temp;
}
check++;
}
//"Place" tells loop when to stop and holds a value to be compared
place++;
check = place + 1;
}
place = 0;
//"Place" acts as a counter
while (place < nums.length) {
//Output Loop
txtout.append("\n" + nums[place] + "");
//"txtoutput" is the textarea (.append means to add to the text already there
place++;
//"\n" means new line
}
}
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}
I am working on a java assignment where I need to delete an integer element in an array and shift the below elements up on space to keep them in order. The array is currently random integers in descending order. I am not allowed to use array.copy because I will need to collect array usage information as part of the assignment. I have tried a ton of different ways of doing this but cannot seem to get it working.
public static void deletionArray(int anArray[], int positionToDelete) {
for (int j = anArray[positionToDelete] - 1; j < anArray.length; j++) {
System.out.println("j is " + j);
anArray[j] = anArray[j + 1];
}
displayArray(anArray);
}
You're iterating until anArray.length (exclusive), but inside the loop, you're accessing anArray[j + 1], which will thus be equal to anArray[anArray.length] at the last iteration, which will cause an ArrayIndexOutOfBoundsException.
Iterate until anArray.length - 1 (exclusive), and decide what should be stored in the last element of the array instead of its previous value.
You're also starting at anArray[positionToDelete] - 1, instead of starting at positionToDelete.
You have two bugs there.
Since this is an assignment, I won't give a complete answer - just a hint. Your loop definition is wrong. Think about this: what happens on the first and on the last iteration of the loop? Imagine a 5-element array (numbered 0 to 4, as per Java rules), and work out the values of variables over iterations of the loop when you're erasing element number, say, 2.
Use System.arraycopy faster than a loop:
public static void deletionArray( int anArray[], int positionToDelete) {
System.arraycopy(anArray, positionToDelete + 1, anArray,
positionToDelete, anArray.length - positionToDelete - 1);
//anArray[length-1]=0; //you may clear the last element
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
if (anArray.length == 0) {
throw new IlligalArgumentException("Error");
}
int[] ret = new int[anArray.length - 1];
int j = 0;
for (int i = 0; i < anArray.length; ++i) {
if (i != positionToDelete) {
ret[j] = anArray[i];
++j;
}
}
return ret;
}
Why do we reserve a new array?
Because if don't, we would use C\C++-style array: an array and a "used length" of it.
public static int deletionArray(int anArray[], int positionToDelete, int n) {
if (n == 0) {
throw new IlligalArgumentException("Error");
}
for (int i = positionToDelete; i < n - 1; ++i) {
anArray[i] = anArray[i + 1];
}
return n - 1; // the new length
}
How's this ? Please note the comment, I don't think you can delete an element in an array, just replace it with something else, this may be useful : Removing an element from an Array (Java)
Updated with 'JB Nizet' comment :
public class Driver {
public static void main (String args []){
int intArray[] = { 1,3,5,6,7,8};
int updatedArray[] = deletionArray(intArray , 3);
for (int j = 0; j < updatedArray.length; j++) {
System.out.println(updatedArray[j]);
}
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
boolean isTrue = false;
for (int j = positionToDelete; j < anArray.length - 1; j++) {
if(j == positionToDelete || isTrue){
isTrue = true;
anArray[j] = anArray[j + 1];
}
}
anArray[anArray.length-1] = 0; //decide what value this should be or create a new array with just the array elements of length -> anArray.length-2
return anArray;
}
}