Just before I begin to annoy you, I am a Java beginner and my main issue up to date is two- ord more-dimensional arrays.
Let me represent my problem:
The task in the study was: you have an sorted array, then you type the number of how many searching operations(let them named by N) the Programm should do.
Due to this you type N x 2 different values a and b, a should be smaller than b.
The Programm should search in the sorted array for intervalls containing your a and b and print these intervalls out.
For example:
The array to search for looks like this:
[1, 3, 5, 7, 9]
then the user types in the number of operations, for example 3. Following to this the a and b couples:
3 6
2 9
1 5
The output of the programm should be according to these a and b couples:
3 7
1 9
1 5
I tried to master this exercise but as mentioned above I have problems with multidimensional arrays. At the following you can see my code and I just want tipps or specific informations about arrays to understand how they're working.
And i improved it:
import java.util.*;
public class Blatt9{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
boolean check1 = false;
int N = s.nextInt();
int[] array = new int[N];
for(int i = 0; i < array.length; i++){
array[i] = s.nextInt();
}
for(int j = 0; j < array.length; j++){
for(int k = j+1; j < array.length -1; j++){
if(array[j] < array[k]){
check1 = true;
}
else{
check1 = false;
}
}
}
if(check1){
System.out.println("nicht aufsteigend sortiert");
}
else{
System.out.println("korrekt");
}
//Beginn der eigentlichen Aufgabe
int abfragen = s.nextInt(); // Anzahl der Abfragen
int[][] arr = new int[abfragen][2]; //um die abfragen zu speichern
int a = 0;
int b = 0;
for(int i = 0; i < abfragen; i++){
a = s.nextInt();
b = s.nextInt();
if(a>b){
System.out.println("Zahl 1 muss kleiner Zahl 2 sein");
break;
}
arr[i][0] = a;
arr[i][1] = b;
}
int intervall1 = 0;
int intervall2 = 0;
for(int i = 0; i < array.length; i++){
for(int j = 0; j < arr.length; j++){
if(array[i] <= a){
intervall1 = a;
}
if(array[i]>= b){
intervall2 = b;
}
}
System.out.print(intervall1 + " " + intervall2);
System.out.println();
}
}
}
The output now is:
input:
5
1 3 5 7 9
korrekt
3
3 6
2 9
1 5
begin of output:
1 0
1 0
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
1 5
Related
My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]
I am writing a program that should output an array, the elements of the array reversed, the sum of the array, the average of the array, min and max of array, and the array sorted (ascending by selection sort and descending by bubble sort). Everything seems to check out, BUT the module descendingOrderBBS()'s output is incorrect. This is my code so far:
import java.util.Scanner;
import java.lang.String;
public class Main
{
public static String input;
public static int n;
public static void main(String[] args)
{
int[] file1 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] file2 = new int[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int[] file3 = new int[]{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
inputData();
switch (input)
{
case "file1":
{
System.out.println("original array: ");
printArray(file1);
System.out.println(" ");
System.out.println("reversed array: ");
reverseArray(file1);
System.out.println(" ");
System.out.println("The sum of all elements: " + sum(file1));
System.out.printf("The average of all elements: %.1f%n", average(file1));
max(file1);
min(file1);
//System.out.printf("Array in ascending order (Selection Sort): %-10s", ascendingOrderSS(file1));
ascendingOrderSS(file1);
System.out.println(" ");
descendingOrderBBS(file1);
//System.out.printf("Array in ascending order (Bubble Sort): %-10s", ascendingOrder(file1));
break;
}
case "file2":
{
System.out.println(file2);
break;
}
case "file3":
{
System.out.println(file3);
break;
}
default :
{
Scanner keyboard = new Scanner(System.in);
System.out.println("File not found, try again: ");
inputData();
break;
}
}
}
private static String inputData()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please input file: ");
input = keyboard.nextLine();
return input;
}
private static void printArray(int f[])
{
for (int i = 0; i < f.length; i++)
{
System.out.printf("%-10s", f[i]);
}
}
private static void reverseArray(int f[])
{
int end = f.length - 1;
for (int start = 0; start < end; start++, end--)
{
int temp = f[start];
f[start] = f[end];
f[end] = temp;
}
for (int i = 0; i < f.length; i++)
{
System.out.printf("%-10s", f[i]);
}
}
private static int sum(int f[])
{
int sum = 0;
for (int i = 0; i < f.length; i++)
{
sum += f[i];
}
return sum;
}
private static float average(int f[])
{
float average = 0;
int sum = 0;
for (int i = 0; i < f.length; i++)
{
sum += f[i];
}
average = sum / f.length;
return average;
}
private static void max(int f[])
{
int largest = f[0];
for (int i = 0; i < f.length; i++)
{
if (f[i] > largest)
{
largest = f[i];
}
}
System.out.println("Max: " + largest);
}
private static void min(int f[])
{
int smallest = f[0];
for (int i = 0; i < f.length; i++)
{
if (f[i] < smallest)
{
smallest = f[i];
}
}
System.out.println("Min: " + smallest);
}
private static void descendingOrderBBS(int f [])
{
int i = 0;
int j = 0;
int temp = 0;
for (i = 0; i < f.length; i++)
{
for (j = i + 1; j < f.length; j++)
if (f[i] < f[j])
{
temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
System.out.println("Array in descending order (Bubble Sort): ");
for (int x = 0; x < f.length; x++)
{
System.out.printf("%-10s", f[x]);
}
}
private static void ascendingOrderSS( int f [])
{
int a = 0;
int b = 0;
int minIndex = 0;
for (a = 0; a < f.length - 1; a++)
{
minIndex = a;
for (b = a + 1; b < f.length; b++)
{
if (f[b] < f[minIndex])
{
minIndex = b;
}
}
int temp = f[minIndex];
f[minIndex] = f[a];
f[a] = temp;
}
System.out.println("Array in ascending order (Selection Sort): ");
for (int x = 0; x < f.length; x++)
{
System.out.printf("%-10s", f[x]);
}
}
}
Here is the whole program run together
Please input file: file1
original array:
1 2 3 4 5 6 7 8 9 10
reversed array:
10 9 8 7 6 5 4 3 2 1
The sum of all elements: 55
The average of all elements: 5.0
Max: 10
Min: 1
Array in ascending order (Selection Sort):
1 2 3 4 5 6 7 8 9 10
Array in descending order (Bubble Sort):
2 1 3 4 5 6 7 8 9 10
Process finished with exit code 0
I've tried changing the variables to a/b instead of i/j. I made all the modules private to see if that would make a difference, but nothing I've tried has done a thing. Oh and I've also tried using different IDEs.
This is the output with both sorting modules together:
ascendingOrderSS(file1);
System.out.println(" ");
descendingOrderBBS(file1);
Array in ascending order (Selection Sort):
1 2 3 4 5 6 7 8 9 10
Array in descending order (Bubble Sort):
2 1 3 4 5 6 7 8 9 10
Process finished with exit code 0
Output with ascending module ignored:
//ascendingOrderSS(file1);
System.out.println(" ");
descendingOrderBBS(file1);
Array in descending order (Bubble Sort):
10 9 8 7 6 5 4 3 2 1
Process finished with exit code 0
I'm not sure on why descendingOrderBBS() is changing. I've been up till 5:12am finishing this last project.
All fixed:
Array in ascending order (Selection Sort):
1 2 3 4 5 6 7 8 9 10
Array in descending order (Bubble Sort):
10 9 8 7 6 5 4 3 2 1
Process finished with exit code 0
For your first issue why it's printing 5.0 and not 5.5 is because sum / f.length is a division of integers and the value after the . will be dropped, however turning sum into float or casting sum to float will solve this issue.
Your current code (this prints 1.0):
float average = 3 / 2;
System.out.println(average);
The fix (this prints 1.5):
float sum = (float)3 / 2;
System.out.println(sum);
3 and 2 are the variables sum and f.length in your code.
I apologize for my english. So far I got this code that sort an array. The user input 10 numbers and after that, the program makes the sorting. But what I want is that every time the user inputs a number, the program immediately makes the sort. How can I do that?
For example, if I input 5 and then 3, immediately takes the 3 to the first position. And then if I put 2, immediately take it to the first position and sort the others (2,3,5). Then if I put 1, takes it to the first position, sorting the others(1,2,3,5) and so on.
import java.util.Scanner;
public class Nine{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for(int i = 0; i < 10; i++){
System.out.print("Número: ");
num[i] = input.nextInt();
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
System.out.println();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10 - i - 1; j++){
if(num[j+1] < num[j]){
temp = num[j+1];
num[j+1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
}
}
Now I have this code and it works. It does what I wanted to do. But to me it's a little bit complicated. I'm still a beginner. I understand what it does but is there a better way to do it. An easier way? Thanks
import java.util.Scanner;
public class practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int n = 0, l = 0, t = 0;
for(int i = 0; i < num.length; i++){
System.out.print("Número: ");
n = input.nextInt();
l = 0;
while(num[l] < n && l < i){
l = l + 1;
}
t = i;
while(t > l){
num[t] = num[t - 1];
t = t - 1;
}
num[l] = n;
for(int temp : num){
System.out.print(temp + " ");
}
System.out.println();
}
}
}
here you go
public class TestProgram {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for (int b = 0; b < 10; b++) {
System.out.println("Número: ");
num[b] = input.nextInt();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i - 1; j++) {
if (num[j + 1] < num[j]) {
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for (int k = 0; k < 10; k++) {
System.out.println(num[k] + " ");
}
}
}
}
To do this create a sort method which you can call to sort an array then return a new sorted array. Next every time a user inputs run a for loop which will create an array with the current amount entered. While entering just use i+1. Finally, with the new array call the sort method and the sorted array will be returned and you can do as you wish with the new array.
You make things more difficult for yourself using an array but assuming you want to start with an array of size 10 filled with 0s (so 0 is not a valid input) the basic algorithm is to go through the currently sorted array and if the current value is less than the indexed value move all the values in the sorted array to the right and insert the current value at the current index. As others have already mentioned for larger datasets this is very inefficient but for an array of size 10 it's not a big deal.
int current = input.nextInt();
for (int j = 0; j < sorted.length; j++) {
if (sorted[j] == 0) {
sorted[j] = current;
break;
}
if (current < sorted[j]) {
for (int k = sorted.length - 1; k > j; k--) {
sorted[k] = sorted[k - 1];
}
sorted[j] = current;
break;
}
}
Here's what the output at each iteration would look like for the input 5, 3, 2, 1, 4, 10, 20, 15, 13, 5:
5 0 0 0 0 0 0 0 0 0
3 5 0 0 0 0 0 0 0 0
2 3 5 0 0 0 0 0 0 0
1 2 3 5 0 0 0 0 0 0
1 2 3 4 5 0 0 0 0 0
1 2 3 4 5 10 0 0 0 0
1 2 3 4 5 10 20 0 0 0
1 2 3 4 5 10 15 20 0 0
1 2 3 4 5 10 13 15 20 0
1 2 3 4 5 5 10 13 15 20
I have to create a 2D jagged array with a random number of rows (5-10) with each row having a random length (5-10). I filled the jagged array with random numbers. It should look something like this:
2 4 1 5 3 8 6 3
2 5 8 9 7 4 3 5 6
6 7 9 3 5
2 6 7 8 4 5 3 6 7
1 4 2 2 1
This is my current createArray method
public static int [][] createArray(){
int row = (int)(Math.random()*5)+5;
int column = (int)(Math.random()*5)+5;
int[][]array = new int[row][];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
//Fill the matrix with random numbers
array[i][j] = (int)(Math.random()*10);
}}
return array;
}//End createArray method
However, this just randomizes the rows and columns and doesn't create a jagged array. Can anyone help lead me in the right direction? Thanks a lot!
As #DoubleDouble stated, your code throws a NullPointerException.
It looks like you want something like this:
public static int [][] createArray(){
int row = (int)(Math.random()*5)+5;
//int column = (int)(Math.random()*5)+5; //not needed
int[][] array = new int[row][];
for(int i = 0; i < array.length; i++){
int column = (int)(Math.random()*5)+5; //create your random column count on each iteration
array[i] = new int[column]; //Initialize with each random column count
for(int j = 0; j < array[i].length; j++){
//Fill the matrix with random numbers
array[i][j] = (int)(Math.random()*10);
}
}
return array;
}//End createArray method
Of course it will produce different results each time it runs, but here is a sample of what it will output:
1 2 5 4 3 9 2 7 9
4 1 4 2 2 6
9 5 7 8 7 8 4 2
8 3 8 7 9 4 0
0 2 1 4 9 3 7 8
4 0 3 8 3
1 3 8 9 9 8
package JavaPrograms;
import java.util.Random;
public class jaggedarr
{
public static void main(String[] args) {
int a[][] = new int[3][];
Random r = new Random();
a[0] = new int[4];
a[1] = new int[2];
a[2] = new int[3];
for (int[] a1 : a)
{
for (int j = 0; j < a1.length; j++)
{
a1[j] = r.nextInt(20);
}
}
for(int i[] : a)
{
for(int j : i)
{
System.out.print(j + " ");
}
System.out.println("");
}
}
}
I have a function that I need to calculate the sum of elements after the diagonal in the 2D array, but the problem is that the function return the sum of the elements in the diagonal.
What I need is that if I have a matrix like this:
1 2 3
4 5 6
7 8 9
The elements of the diagonal are = 1 5 9
What I need is to calculate the numbers that follow after these diagonal numbers, so it will be like this:
1 2 3
4 5 6
7 8 9
sum = 2+3+6 = 11
I would appreciate it if someone could help me to fix my problem.
this my code:
public int calculate(){
int sum = 0;
for(int row = 0; row <matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
if(row == col){
sum = sum + row+1 ;
}
}
}
System.out.println("the sum is: " + sum );
return sum;
}
public static void main(String[] args) {
int[][] ma = new int[2][2];
Question2 q2 = new Question2(2, 2, ma);
q2.fill();
q2.calculate();
}
the output is:
2 1
2 1
the sum is: 3
You want col to go through all elements, being always bigger than the diagonal.
Therefore try:
int sum = 0;
for(int i = 0 ; i < a.length ; ++i) {
for(int j = i + 1 ; j < a[i].length ; ++j) {
sum += a[i][j];
}
}