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()?
Related
I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.
[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]
I have created a program previously using the BubbleSort method that works to sort numbers in a list that already exists, however, I am having difficulty with trying to manipulate this program in order to allow a user to input the list of numbers to be sorted instead. So far I have:
import java.util.Scanner;
public class MedianValue {
public static void main(String[] args) {
//use scanner to input list of numbers to sort
Scanner scan = new Scanner(System.in);
int[] numbers = new int[] {scan.nextInt()};
//nested for loop
//outer loop just iterating
//inner loop going through and flipping
//checking if out of order (if statement)
int counter = 0;
//outer loop: keep doing this until it's sorted
for(int i = 0; i < numbers.length - 1; i = i + 1)
//put in a inner loop number.length times minus one because we don't want to swap the last element
for(counter = 0; counter < numbers.length - 1; counter = counter + 1)
{
if (numbers [counter] > numbers [counter + 1])
{
int temporary = numbers [counter];
numbers [counter] = numbers [counter + 1];
numbers [counter + 1] = temporary;
}
}
for(int i =0; i < numbers.length; i = i + 1)
{
System.out.print(numbers[i] + " ");
}
}
}
But, in this program, instead of sorting the inputted numbers, the program simply prints the first number that is inputted by the user. I am not sure if I need to move where my scanner function is placed, or add on to it within the loop for it to sort all of the numbers as I want it to do. I am lost on where to change the program if that is the case.
That's because int[] numbers = new int[] {scan.nextInt()}; is a single assigment. scan read a single input and assign to number[0].
You actually need to modify your code for scan to read n numbers and store in n-sized numbers.
something like.
int[] numbers = new int[scan.nextInt()];
for( int i = 0; i < numbers.length; i++)
numbers[i] = scan.nextInt();
The code int[] numbers = new int[] {scan.nextInt()}; will always create an array (not a List) of size 1.
Usually in these kinds of assignments you get n + 1 numbers, for example 5 3 6 2 4 1 would mean "I'm going to give you five numbers. Oh here they are: 3 6 2 4 and 1!"
You probably want something like int[] numbers = new int[scan.nextInt()]; - then loop from 0 to numbers.length to fill the array.
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;
}
}
}
I have been beating my head against the wall with my code. I finally got my code to allow me to input whatever numbers the user desires depending on how many rows and columns they want, but for some reason whenever I try to type in a larger column number than row number, I get an error. I've read over my loop tens of times, inserting -1 where I think the program is over counting, but it still won't work. I'm assuming this is the appropriate way to write a multidimensional array when it is completely dependent on the user, but if not, please tell me how to make my code more efficient. Thanks!
public class MultiPractice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompts user to insert desired rows and columns
System.out.print("Enter how many rows you want in your array: ");
int rowSize = input.nextInt();
System.out.print("Enter hwo many columns you want in your array: ");
int colSize = input.nextInt();
// Asks users to insert desired numbers for the multi-array
System.out.print("Enter " + (rowSize*colSize) + " integers: ");
// Creates the multidimensional array
int[][] multi = new int[rowSize][colSize];
// Runs the for loop to put numbers where they belong in array
for (int i = 0; i < multi.length; i++) {
for (int j = 0; j < multi[colSize].length; j++) {
multi[i][j] = input.nextInt();
System.out.print(multi[i][j] + " ");
}
System.out.println();
}
}
}
multi[colSize].length should be multi[0].length or multi[i].length (since you have a rectangular array, these have the same value).
multi[colSize].length is the length of row colSize. Therefore, if you have less than colSize+1 rows (since they start from 0), this is out-of-bounds.
It's .length that's screwing you up here. Multi[colSize].length is not the same as colSize; in fact, it's colSize + 1 (since length starts counting at 1).
My Solution: Instead of using multi.length, you can use i < rowSize. You can also swap out the multi[colSize] with < colSize.