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
Related
The task is: write a program that swaps the maximum and minimum elements of a given array. Print the array before and after this operation.
I am still a huge noob at programming, most of the time I just can't really picture what the codes are doing.
public class problem6 {
public static void main(String[] args) {
int[] arr = new int[15];
for (int i = 0; i < arr.length; i++)
/*
I don't think I really understand incrementation in loops, what exactly do they do? As far as I understand
it is like having an industry line? I suppose 'i' would be the product and '++' would be the thing that
carries 'i' to the be checked one by one? I really need an ape analogy because I can't really visualize it.
*/
arr[i] = (int) (Math.random() * 15);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
int minIndex = 0, maxIndex = 0; //why do we assign min and max to 0 and not any other number?
for (int i = 1; i < arr.length; i++) {
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
/*
I see a lot of codes like:
if (arr[minIndex] > arr[i])
minIndex = i;
if (arr[maxIndex] < arr[i])
maxIndex = i;
what purpose does it serve? For the lack of knowledge and from a really noob programmer's perspective
it seems like we are "reassigning" minIndex and maxIndex to 'i', which is probably not what we're actually doing
but I don't know how to describe it other way.
*/
}
System.out.println(minIndex + " " + arr[minIndex]);
System.out.println(maxIndex + " " + arr[maxIndex]);
{
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
/*
Here again, for the lack of understanding and better way of describing, it seems to me that we are reassigning,
which makes it appear illogical to me, but I'd assume it's not actually "reassigning".
int tmp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = tmp;
*/
}
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + ", ");
System.out.println();
}
}
What is i, what does it do and what does i++ mean:
i is used in this loop to indicate how many times you've looped through said loop.
The ++ is there to do i + 1 after each time you've looped trough the for loop.
For better understanding on how you use i in your example, imagine the array arr being a big book and what you write in the [] is which page you want to open. In the loop you basically flip through the book to each pagenumber in those brackets.
Why does minIndex and maxIndex get set to 0 instead of any other number?
They get set to 0 because we can assume that that is the lowest possible Index in your array. So when the Index gets compared to any other possible number that could be the lowest or highest Index, it always gets set to said lowest or highest Index instead of always having the same value you set because no other value in your array is higher or lower than that.
Why do we make arr[minIndex] assert the same value as arr[maxIndex]?
In your question's title you said that you wanted to swap the highest number in your array with the lowest number. So now that we have found the highest and lowest number in your array these steps switch the two.
If you have any other questions or if any of my descriptions are unclear, just comment under the answer and I'll do my best to help you out. Also, don't look down on yourself so much. Everyone was a "noob" at some point :)
Here is quick fix for you.
Following is complete example of swaps the maximum and minimum elements of a given array.
Input :
Enter elements you want to input in array:
5
Enter all the elements:
10
15
16
1
9
Output :
Element After swaps :
10
15
1
16
9
public static void main(String arg[]) {
Scanner scan = null;
int number;
try {
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
number = scan.nextInt();
int array[] = new int[number];
System.out.println("Enter all the elements:");
for (int i = 0; i < number; i++) {
array[i] = scan.nextInt();
}
int[] resultArray = swap(array);
System.out.println("Element After swaps :");
for (int i : resultArray) {
System.out.println(i);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
scan.close();
}
}
public static int[] swap(int[] array) {
int minIndex = 0, maxIndex = 0;
for (int i = 1; i < array.length; ++i) {
if (array[i] < array[minIndex])
minIndex = i;
if (array[i] > array[maxIndex])
maxIndex = i;
}
int t;
if (maxIndex != minIndex) {
t = array[minIndex];
array[minIndex] = array[maxIndex];
array[maxIndex] = t;
}
return array;
}
Hope this solution works.
Please mark as answer if this solution is helpful.
I am working on a project in java and I was wondering how I can store a value to the second array container
I have
int[][] figure = new int[4][6];
I have the following for loop
public void ask(){
for(int i =0;i<Division;i++){
System.out.println("Enter sale for division " + i );
for(int j =0; j<4;j++){
System.out.println("For quarter " + j);
int input = keyboard.nextInt();
}
}
}
How can I set input equal to the second array container [][]<--
A 2D array is an array of arrays, therefore you can:
Add values to 2D arrays with double for-loops.
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++) {
array[i][j] = yourValue;
}
}
Or do array[index][index] = yourValue.
Example:
Say I want to add a value to the first index of the first array in a 2D array of type int.
I would do:
array[0][0] = 56.
Then, to access a value from the array, I would do:
int value = array[0][0]
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.
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.
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
}
}