what is the best way to write these java arrays? - java

I am stuck on my class work:
Create an application containing an array that stores eight integers. The application should
display all the integers, (done)
display all the integers in reverse order,
display the sum of the eight integers, (done)
display all values less than 5,
display the lowest value, (done)
display the highest value, (done)
calculate and display the average, (Done)
display all values that are higher than the calculated average value.
I must use (or attempt to use) an array; also must use at least one loop to "traverse" (move through) the array. This also due # 23:59 mountain standard time tonight
What am I doing wrong?
package numberlistdemo;
import java.util.Arrays;
public class NumberListDemo
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int n[]= {1,2,3,4,5,6,7,8};
int lowest = 1000;
int highest = 0;
int sum = 0;
int five = 0;
int OverF = 0;
int rev = 0;
int OverAve= 0;
for (int i=0;i<n.length;i++)
{
int cur = n[i];
if (cur < lowest) lowest = cur;
if (cur > highest) highest = cur;
sum += cur;
}
double ave = sum / n.length;
for (int i=0;i<n.length;i++)
{
int cur = n[i];
if (cur > ave) OverAve = cur;
}
for (int i=0;i<n.length;i++)
{
int LowF = n[i];
if (LowF < 5) five = LowF;
if (LowF > 5) OverF = LowF;
}
//3
System.out.println("Total of the Array is " + sum );
//1
System.out.println("The number we are using are " + Arrays.toString(n));
//4
System.out.println("All values lower the 5 are " + five );
////2
for (int counter=n.length - 1; counter >= 0; counter--)
{
System.out.println("The reverse order of the numbers are " + (n[counter]));
}
//5
System.out.println("The lowest value is " + lowest);
//6
System.out.println("The highest value is "+ highest);
//7
System.out.println("The average is " + ave);
//8
System.out.println("All numbers higher than the average are: " + OverAve);
}
}
I get this
Total of the Array is 36
The number we are using are [1, 2, 3, 4, 5, 6, 7, 8]
All values lower the 5 are 4
The reverse order of the numbers are 8
The reverse order of the numbers are 7
The reverse order of the numbers are 6
The reverse order of the numbers are 5
The reverse order of the numbers are 4
The reverse order of the numbers are 3
The reverse order of the numbers are 2
The reverse order of the numbers are 1
The lowest value is 1
The highest value is 8
The average is 4.0
All numbers higher than the average are: 8

Sample loop to obtain sum, lowest, and highest integer from an array
int lowest = 1000;
int highest = 0;
int sum = 0;
for (int i = 0; i < array.length; ++i) {
int cur = array[i];
if (cur < lowest) lowest = cur;
if (cur > highest) highest = cur;
sum += cur;
}
Edit: the latest code updates made some progress, but likely do not quite meet the specified requirements. There are some difficulties in knowing the full requirement (e.g., output format).
Output Only
The current example is displaying the output (one entry per line). It is not clear if one only needs to display the output or actually reverse the array. If the only requirement is to output the reversal, the numbers larger than 5 and larger than 8, the the following three loops will work. One is mostly already in the suggested code.
System.out.println("The reversed array is: ");
for (int counter < n.length - 1; counter >= 0; counter--) {
System.out.print(n[counter] + " ");
}
System.out.println();
Note that these two should probably be in a method
final int lessThan = 5;
System.out.println("The numbers in the array less than " + lessThan + " are: ");
for (int i = 0; i < n.length; ++i) {
if (n[i] < lessThan) {
System.out.print(n[i] + " ");
}
}
System.out.println();
System.out.println("The numbers in the array greater than the mean " + ave + " are: ");
for (int i = 0; i < n.length; ++i) {
if (n[i] > ave) {
System.out.print(n[i] + " ");
}
}
System.out.println();
Create a new reversed array
It would make more sense for the assignment to require actually reversing the array. In that case, there are a couple of approaches. Probably the easiest is to create a new array and reverse the elements into it. Essentially it is the same loop as above, but placing the elements of n into the array rather than outputing them to the screen. (Note: #Debosmit proposed an example that does not require the additional index variable).
int[] reversed = new int[n.length];
int idx = 0;
for (i = n.length - 1; i >= 0; --i) {
reversed[idx++] = n[i]];
}
Later then one can use the same output approach as was used for displaying all of the original entries:
System.out.println("The reversed array is: " + Arrays.toString(reversed));

What is the error message?
since you are not using curly braces{ } your local variable int i will only exist within these lines:
for (int i=0;i<n.length;i++)
sum = sum + n[i];
and NOT these:
double rev = n.length - i - 1;
boolean l = (n[i] < 5);

Ah! Well... I'll contribute. Here is how to reverse...
// note this will change the original array
for(int i = 0 ; i < n.length ; i++) {
int t = n[i];
n[i] = n[n.length - 1 - i];
n[n.length - 1 - i] = t;
}
// this will not change the original array
int[] newArr = new int[n.length];
for(int i = 0 ; i < n.length ; i++) {
newArr[n.length - 1 - i] = n[i];
}
// you can now return `newArr` or something since it is `n` reversed
Now to look at all values that are higher than the calculated average value. I think you already have the sum of the numbers. Lets call it sum. avg = sum/n.length.
for(int i = 0 ; i < n.length ; i++) {
if(n[i] > avg)
System.out.println(n[i]);
}
All numbers less than 5.
for(int i = 0 ; i < n.length ; i++) {
if(n[i] < 5)
System.out.println(n[i]);
}
In the future, please don't come here with your homework before trying to do it yourself. Thanks! :)

Related

How can I find the lowest and highest number in 2d array?

package HighLow;
import javax.swing.JOptionPane;
public class HighLow {
public static void main (String[]args) {
int [][] arr= new int[3][4];
int smallest=arr[0][0];
int largest= arr[0][0];
int i = 0;
int j = 0;
{
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
{
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[0][0] > largest) {
largest = arr[i][j];
}
{
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
}
}
}}}
How can I find the lowest and highest number in 2d array?
I'm getting an error with my code? what seems to be wrong?
I just need to find the highest and lowest among the 12 numbers user will input. here is what I have so far.
How can I find the lowest and highest number in 2d array?
I'm getting an error with my code? what seems to be wrong?
I just need to find the highest and lowest among the 12 numbers user will input. here is what I have so far.
You do not have a loop to take in your array and therefore are receiving an error. To take in the input of the Array use this
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++)
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
Therefore you will have the box outputted 12 times for the user to input 12 Integers and then once you have the Array just run a simple sort to get the smallest and the largest.
int smallest = arr[0][0];
int largest = arr[0][0];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++) {
if (arr[i][j]<smallest)
smallest = arr[i][j];
else if(arr[i][j]>largest)
largest = arr[i][j];
}
}
Final Code being
public class Solution {
public static void main (String[]args) {
int [][] arr= new int[3][4];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++)
arr[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Please enter 12 numbers: "));
int smallest = arr[0][0];
int largest = arr[0][0];
for (int i = 0;i<3;i++)
for (int j = 0;j<4;j++) {
if (arr[i][j]<smallest)
smallest = arr[i][j];
else if(arr[i][j]>largest)
largest = arr[i][j];
}
}
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
}
}
The error is mainly in the initialization part where you have assumed the element in the first row and first column to be either the minimum or maximum element in the array.
You have to initialize the minimum value of the array with a value that is sure to be higher than all the values in the array, why? because only then will there be an update to the actual minimum value of the array, so for example if you set minimum to be 1000 then if the actual minimum of the array is 300, it would get updated. But if you set your minimum to be for example 30 then 300 which is the actual minimum wont get logged and there would be an error.
The absolute opposite applies to the initialization of the largest value of the array. While initializing, safe ball park estimates usually work so carry out the initializations accordingly.
Personally, I don't think you should use JOptionPane to get data from the user and to display data to the user in a Java console application such as yours. I prefer to use Scanner.
(Below code demonstrates. Notes after the code.)
Note that calling a method of JOptionPane will launch the Event Dispatch Thread (EDT) which means that your application will not terminate – unless you add System.exit(0);.
package HighLow;
public class HighLow {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.print("Please enter 12 numbers: ");
String line = stdin.nextLine();
String[] numbers = line.split(" ");
int k = 0;
int[][] arr = new int[3][4];
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(numbers[k++]);
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[i][j] > largest) {
largest = arr[i][j];
}
}
}
System.out.println("The smallest value in the Array is: " + smallest);
System.out.println("The largest value in the Array is: " + largest);
}
}
I assume that the user enters twelve numbers separated by a space in a single line.
Method split returns an array of size twelve where every element is one of the entered numbers.
I initialize smallest to the largest int which guarantees that the first int that I compare it to is guaranteed to be smaller.
Similarly for largest. I initialize it to the smallest possible int.
You need a loop in order to populate all the elements of arr.
Here is output from a sample run of the above code.
Please enter 12 numbers: 1 2 3 4 5 6 7 8 9 0 -1 -2
The smallest value in the Array is: -2
The largest value in the Array is: 9
EDIT
Since you claim that JOptionPane is required, below code uses JOptionPane.
String line = JOptionPane.showInputDialog("Please enter 12 numbers: ");
String[] numbers = line.split(" ");
int k = 0;
int[][] arr = new int[3][4];
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = Integer.parseInt(numbers[k++]);
if (arr[i][j] < smallest) {
smallest = arr[i][j];
}
if (arr[i][j] > largest) {
largest = arr[i][j];
}
}
}
JOptionPane.showMessageDialog(null, "The smallest value in the Array is:" + smallest);
JOptionPane.showMessageDialog(null, "The largest value in the Array is:" + largest);
System.exit(0);

I want to subtract the largest possible number from the Fibonacci sequence by decreasing it in

I want to get n from user and subtract the largest possible number from the Fibonacci sequence by decreasing it in sequence and continue this process until it reaches zero. Our Fibonacci sequence starts from 1. The number 88 can be The form 1 + 3 + 8 + 21 + 55 wrote that these numbers are the sentences 1, 3, 5, 7 and 9 of the Fibonacci sequence, respectively.
Input: 88
Output: 9 7 5 3 1
My code:
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] fibo = new int[1000];
int[] arr = new int [100];
int d = 0;
int b = 0;
fibo[1] = 1;
fibo[2] = 2;
for (int i = 3, j = 1; i <= 20; i++, j++)
fibo[i] = fibo[i - 1] + fibo[i - 2];
b = n;
for (int i = 1, j = 1; i <= 20 && b >= 0; i++, j++) {
if (b == fibo[i] || b + 1 == fibo[i] || b - 1 == fibo[i]) {
d = i;
b -= fibo[d - 1];
System.out.println("B= " + b);
arr[j] = d - 1;
System.out.println("arr= " + arr[j]);
}
}
}
}
The first problem is that, every time you subtract something from your number, the next number you will subtract will have to be smaller - because your number itself is smaller now - whereas in your code, the numbers just keep getting bigger.
For instance, after you try the 9th fibonacci number 55, you are trying 89, whereas you should be trying 34.
This can be solved by iterating backwards through the fibonacci numbers, as in starting from the biggest number at the end of the array, so that as the loop iterates, the numbers get smaller.
The second problem is your check in the if statement, which is only satisfied if there happens to be a fibonacci number very close to the number you are at.
Instead, if you want to select the largest fibonacci number that is smaller than your number, you can just check for the 'smaller than your number' part, since 'the largest fibonacci' part is already taken care of by how the for loop works.
Here is the working code. You will also notice a lot fewer variables. Also I hard-coded the input number for testing, you'll have to add the scanner stuff back in. Sorry.
public class Main {
public static int len = 20; // the program considers this many fibonacci numbers
public static void main(String args[])
{
int n = 88;
int[] fibo = new int[len];
for(int i=0; i<len; i++)
{
if (i < 2) fibo[i] = i+1; // for 1 and 2
else fibo[i] = fibo[i-1] + fibo[i-2]; // for 3 and 5 and ...
}
for(int i=len-1; i>=0; i--)
{
if (fibo[i] <= n)
{
System.out.format("%d: %d - %d = %d\n",
i+1, // to correct for 0-indexing
n, fibo[i], n-fibo[i]);
n -= fibo[i];
}
}
}
}

How to zigzag numbers in floyd's triangle pattern?

I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}

How to compare specific elements of an array in java

I'm trying to compare elements of an array of ints 8 elements long (array[]) add up the elements in sets of 2, then divide by 2 for the avg, eg array[0] + array[1] / 2 and assign the result to a new array 4 elements long.. Specifically, I want to compare them in sets of 2 to see if either / or both are less than 40, if either is less than 40, I add them both up and divide by 2 for the average, and assign the array with the minimum out of (40, array[i]).. however if they are both above 40 I still add both elements and divide by 2 but assign the array element[i] with the number I get, not bothering with a minimum calculation
Heres what I have so far
for (int i = 0; i < array.length ; i++)
{
if (array[i] < 40 )
{
array2[j] = Math.min(35, array2[j]);
}
}
The if statement is correct I think, but the boolean argument is far from it. Array[] = the original 8 element array... array2[] = the calculated and averaged array 4 elements long. Many thanks
Is this what you mean? Hopefully I understood the question.
for (int j = 0; j < array2.length; j++)
{
double avg = (array[2 * j] + array[2 * j + 1]) / 2;
if (array[2 * j] < 40 || array[2 * j + 1] < 40)
{
array2[j] = Math.min(avg, 40);
} else {
array2[j] = avg;
}
}
I think this captures the logic you described(?)
int[] test = {
22,44,
52,36,
35,41,
63,24
};
double[] newarr = new int[test.length/2];
for (int i = 0; i < newarr.length; i++){
newarr[i] = (test[i*2] + test[i*2+1]) / 2;
}
Gives:
[33.0, 44.0, 38.0, 43.5]
Correct?

Java: Array with loop

I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written.
But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
To populate the array:
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = i+1;
}
and then to sum it:
int ans = 0;
for (int i = 0; i < numbers.length; i++) {
ans += numbers[i];
}
or in short, if you want the sum from 1 to n:
( n ( n +1) ) / 2
If your array of numbers always is starting with 1 and ending with X then you could use the following formula:
sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.
int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}

Categories

Resources