I'm having trouble with user input in java, hope anyone can help :)
The user declares how big the 2d array will be(number d is the side of the square array), then inputs a number "n", which tells the program how many inputs of numbers there will be, and then needs to input these numbers (eg. if n=4, the input must be sth like : 5 17 3 20.
I have already written the same thing for a single row array
for(i=0;i<=n;i++) {
arr[i]=sc.nextInt();
}
but am having trouble doing basically the same for the 2d array.
Any ideas?
Use two nested loops and index like arr[i][j]
int d=sc.nextInt(); //length of rows and columns
int n=sc.nextInt(); //user input how many numbers
int[][] array=new int[d][d]; //length and heigth of array
for (int i=0;i<d;i++) {
for(int j=0;j<d;j++) {
array[i][j]=sc.nextInt();
}
}
int distance=0;
int c=0;
for(int i=0;i<d;i++){
for(int j=0;j<d;j++){
array[i][j]=c;
c++;
}
}
that in the end is sth else, I just wanted for the whole thing to be seen, if maybe I missed something elsewhere.
Sorry I don't have the ability to comment yet so I am posting this as an answer. Essentially you need to use a nested for loop as stated above. I will provide you a basic template
for (int i = 0; i < length; i ++){
for (int j = 0; j < width; j ++){
if (counter < userInput){
counter++;
arr[i][j] = value;
} else {
break;
}
}
}
Related
I'm trying to make a program that will make square matrices based on user input. I know that arrays exist, but I wanted to make a matrix from scratch so that I could better understand the basic concept of it and further extend my understanding of loops. So far I have been able to make a square matrix that will accept one number as an input into that matrix, for example I input a square 2x2 matrix and while I want it to look like this 1 2 3 4 with 1 and 2 being above 3 and 4. I have only gotten it to accept one user input that it places in all four slots. For example, if my user input is 1 then the matrix looks like this 1 1
1 1
My code looks like this thus far:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int k = 0; k < number; k = k +1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
}
I believe that my problem lies in my first for loop where I have the user input the matrix number. Any helpful suggestions on how I can better write this so that the user can input a different number for each slot in the matrix?
It looks like you are trying to create a matrix and then populate it with values read from the user.
To create an N x N matrix of integers
int[][] matrix = new int[n][n]();
To assign a value to a matrix cell [i, j]:
matrix[i][j] = someValue;
Obviously, if you want to read a different value for each cell, you need to call nextInt() multiple times; i.e. once for each value you want to read.
(Note to other readers: I'm not coding this for the OP, because he will learn more by coding it himself.)
You can create a matrix using 2 dimensional arrays:
int[][] matrix = new int[row][column]; //row is the number of matrix rows
//column is the number of matrix columns
To access the elements of the matrix and define it after the declaration, you can use a nested for loop:
for (i = 0; i < row; i++ )
for (j = 0; j < column; j++)
{
scores[i][j] = value; // value is your chosen integer for that index
}
}
As you mention in your question, user has to input only onces and that it places in all four slots.
For example, if user input is 1 then the matrix looks like this 1 1 1 1.
Then no need for first for loop, just remove it.
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.print(matrix_number);
}
System.out.println();
}
You want the user to say the size of the square matrix, then you want the user to tell you every number in the matrix. You only need two loops here:
int number;
System.out.println("What are the dimensions of the matrix?");
number = in.nextInt();
for (int i = 0; i < number; i = i + 1)
{
for (int j = 0; j < number; j = j + 1)
{
System.out.println("What are the numbers in your matrix?");
int matrix_number = in.nextInt();
System.out.print(matrix_number);
}
System.out.println();
}
If you don't want your matrix polluted by "What are the numbers in your matrix?" questions, then you're going to need to learn how to store user input into some sort of data structure. As you said in your question, arrays are a great way to do this (as are 2d arrays).
If you were willing to learn file input or file output, then you could do what you seek without "storing" the numbers in an array. Either read the numbers in from a file and output them to the screen, or have the user type them as user input and output the matrix to a file.
Edit: You could try to erase the "What are the numbers in your matrix?" system out by printing backspace characters on linux systems. More here:
How to delete stuff printed to console by System.out.println()?
I created a Java program that takes the user's choice and creates an int array of that size. Then the array is sorted and displayed and a number is asked to search in the array. I'm trying to use the bubble sort technique, however, the result always turns out to be a descending array rather than an ascending one.
import java.util.*;
class mt {
int i,M=0;
public void main() {
Scanner sc=new Scanner(System.in);
System.out.println("enter the size of array");
int sizeOfArray=sc.nextInt();
int arr[]= new int [sizeOfArray];
int temp;
System.out.println("enter the numbers");
for (i=0; i<sizeOfArray; i++) {
arr[i]=sc.nextInt();
}
System.out.println("the sorted array is below :");
for ( i=0; i<sizeOfArray-1; i++){
for (int j=0; j<sizeOfArray-2; j++) {
if (arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (i=0; i<sizeOfArray; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("enter number to search");
int srch=sc.nextInt();
for (i=0; i<sizeOfArray; i++) {
if (arr[i]==srch)
{
System.out.println("found at "+i);
M++;
break;
}
else if (M==0&&i==sizeOfArray-1)
{
System.out.println("number not found");
}
}
}
}
Change your loops and condition as below
for ( i=0; i<arr.length - 1; i++){
for (int j=i+1; j<arr.length; j++) {
if (arr[i]>arr[j]) {
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
So you get resulting array in ascending order. In your case, you are missing elements as you are iterating over from 0 - array.length - 2.
Firstly the code mentioned above had lot of silly mistakes which need to be corrected:
1. "String args[]" need to be added in the main() method.
2. For all the for loops where "i" is the variable, it need to be defined as an "int".
3. the variable "M" need to be defined too.
Now when I did a dry run of this code, the result produced was also not proper.
Input given was as follows:
enter the size of array
5
enter the numbers
12
10
34
2
6
Output received was as below:
the sorted array is below :
2 10 12 34 6
enter number to search
Now the output was incorrect.
Although it was in ascending order... still the last element would get missed. The twin for loops that are used need to be used in a different way. Please find the code that should be present in that section:
for (int i=0; i<=sizeArr; i++){
for (int j=0; j<sizeArr-1; j++) {
if (arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
I hope that this works for you now.
How do I search a 2D array for a specific number (1)? I thought the following code did it, but apparently I was looking in a specific spot whenI declared it with [4][4].
boolean undirectedCircuit (int [][] graph)
{
//graph = graph1(graph1(null));
int edgeCounter = 0;
for (int edge = 0; edge < graph.length; edge++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if(graph[4][4] == '1')
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
if (edgeCounter % 2 == 0)
{
System.out.println("This is a circuit!");
//return true;
}
else System.out.println("This is not a circuit!!");
return false;
}
public void go ()
{
graph1 = new int[][] //This line is complained about.
{
{0,1,1,1,0},
{1,0,0,0,1},
{1,0,0,1,0},
{1,0,1,0,1},
{0,1,0,1,0}
};
undirectedCircuit(graph1); //This is complained about.
}
This is part of an assignment from my school, just pointers would be great. Thank you!
This line is wrong in two ways:
if(graph[4][4] == '1')
The quotes around '1' make it a char literal. Since your array contains ints, you'll want to drop the quotes and just write 1.
graph[4][4] will always check the same value in the array as you said. Specifically, it will always access the fifth value in the fifth array of your 2d array. Whenever you write numbers in your code, they are constants: the number 4 is never going to change during your program's execution, so you keep using 4 as the index over and over again, accessing the fifth element each time you do so.
In order to access every element in an array, you can loop over it like this:
for (int n = 0; n < array.length; n ++)
{
array[n]; //access the nth element of the array
}
n in this instance is the same as your edge variable.
However, since you are using a 2d array, these elements are themselves arrays! Therefore, you need another loop:
//array is a 2d array...
for (int n = 0; n < array.length; n ++)
{
//...so its elements are 1d arrays
for (int m = 0; m < array[n].length; m ++)
{
array[m][n]; //here we have a specific object in our 2d array.
}
}
We use variables for our indices so they can change in the loop and access different values in the array. Hope this helps!
You could try something like this where you will iterate through both dimensions of the array and check your current location rather than the 4,4
for (int x = 0; x < graph.length; x++)
{
for (int y = 0; y < graph[x].length; y++)
{
/* SET FOR WHEN 1s are found in array: edgeCounter++;*/
if (graph[x][y] == 1)
{
edgeCounter++;
System.out.println("edgeCounter found '1' " + edgeCounter + "times");
}
}
}
I'm trying to code a method which draws a cross in JAVA. (see the photo for an example).
Here is the example:
Few Questions:
how do I give an array the dimensions via parameter? It seems that Eclipse needs a number instead of variables for the array dimensions. I thought it is possible to give the method a parameter, how big the dimensions of the array should be.
Don't get the idea how to tell the loop which one of the array positions should be an X and which one not.
Here is my code idea so far...it does not really what it should do :) I took "1" instead of "X", so I can do it with an int array.
public void drawCross(int number){
int i,j;
int array[][]=new int[40][40];
for(j=1;j<=number;j++){
for(i=1;i<=number;i++){
if(array[i]==array[j]){
array[i][j]=1;
System.out.print(array[i][j]+" ");
}
}
System.out.print("\n");
}
}
Thank you in advance.
Pete
As this does not really seem homework, the solution
int[][] array = new int[number][number];
for (int i = 0; i < number; i++){
for (int j = 0; j < number; j++){
if (i == j || i == number - 1 - j) {
array[i][j] = 1;
}
System.out.print(array[i][j] + " ");
}
System.out.print("\n");
}
int[][] a is the conventional way. int a[][] is syntactic sugar for C programmers.
In math i normally is the row, and j the column, so switched the for-loops.
Arrays are indexed from 0.
The condition should say whether one is on one of both diagonals, so only concerns the indices i and j.
|| is OR, and && is AND (should you not already know).
As you see, the matrix array is not needed
So:
boolean isOnDiagonal = i == j || i == number - 1 - j;
System.out.print(isOnDiagonal ? "X " : ". "); // if-then-else operator.
I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.