I have a text file with first line will be the size of the board and the remaining values will be the values of p row by row. All values are separated by whitespace. For example:
5
2 5 10 3 5
4 6 9 12 3
11 5 9 7 7
7 2 4 8 19
2 6 8 10 1
How can I read the file and store them in a 2D Array?
Ok, I'm assuming that the first number defines the width and height, so that it will be square board.
Scanner in = new Scanner(new File("filename.in"));
int N = in.nextInt();
int[][] arr = new int[N][N];
for(int r=0; r<arr.length; r++) {
for(int c=0; c<arr[r].length; c++) {
arr[r][c]=in.nextInt();
}
}
Related
i want devide matrix into four sub-blocks equally by vertically and horizontallty in java (Here, we suppose that m and nare even numbers) .
for example we have matrix:
1 2 3 4 5 6
7 8 9 1 2 8
1 2 3 4 5 6
4 5 6 7 8 9
1 4 7 2 5 8
3 6 9 7 2 5
I want to display the last block that is:
7 8 9
2 5 8
7 2 5
how i can resolve this problem in java.
Iterate over the lower-right part of the matrix. Here is an example for a square matrix. I am sure you will be able to make it more generic for non-square quadrants or to get other quadrants than the lower-right one.
public int[][] getQuadrantOfSquareMatrix(int[][] matrix) {
int newDimension = matrix.length / 2;
int[][] toReturn = new int[newDimension][newDimension];
for (int i = 0; i < newDimension; i++) {
for (int j = 0; j < newDimension; j++) {
toReturn[i][j] = matrix[i + newDimension][j + newDimension];
}
}
return toReturn;
}
I am trying to make a method where a 2D array is created in the main, which can be any dimension. After that, we are supposed to make 2 methods, one which increments each next value in the array by a given number labeled step. One method is supposed to increment the rows, and the other increments it by columns.
This is what I have:
public static void main (String [] args){
int [][] fillRightArray = new int [5][8];
fillRight(fillRightArray, 2);
int [][] fillDownArray = new int[5][8];
fillDown(fillDownArray, -2);
For the fill right method, this is the what the output should be:
2 4 6 8 10 12 14 16
18 20 22 24... //all the way to 80, since the array has 40 elements (40*2=80)
This is my method:
public static void fillRight (int [][] fillRightArray, int step){
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
fillRightArray[i][j] += step*(j+1);
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
But for some reason, my output is:
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
2 4 6 8 10 12 14 16
Any idea as to why this is happening? Same thing happens when I go with the fillDown method, the output is supposed to be:
2 12 22....
4 14 24....
6 16 26....
8 18 28....
10 20 30.... all the way to 80
But instead I get:
2 2 2 2 2
4 4 4 4 4
6 6 6 6 6
8 8 8 8 8
10 10 10 10 10
Your code doesn't work because you aren't taking into account the previous cell.
Your logic for determining the value of a specific cell is fillRightArray[i][j] += step*(j+1); .
This line only considers the value of j to determine the value of a cell within your array, when it should also consider the value of i (explicitly or implicitly).
You should add a counter that keeps track of how many cells you have set, and set the next cells value based on the number of cells that have already been set.
Your fillRight method should instead look like this:
public static void fillRight (int [][] fillRightArray, int step){
int count = 0;
for (int i = 0; i< fillRightArray.length; i++){
for (int j = 0; j< fillRightArray[i].length; j++){
count++;
fillRightArray[i][j] += step*count;
System.out.print(fillRightArray[i][j] + " ");
}
System.out.print("\n");
}
}
You're constantly repeating the same work and going back to 0 each time.
In your fillRight, each row is doing 2,4,6,8,10 because you're doing step*(j+1), where j resets to 0 after each iteration of the loop. You need to find a way to include i as well as j when setting the value, or just have a counting variable that is incremented each step
Like this:
step += 2
fillRightArray[i][j] = step
That way you don't need to worry about position.
I am currently trying to create a nested for Loop statement using java, how do I Create new nested for Loop statement using java which gives the following output:
8
5 5 5 6 5 8 9 5 6 8
7 7 8 7 6 7 8 8 9 7
8 7 6 7 8 7 5 6 8 7
9 9 9 8 9 7 9 8 9 9
7 8 8 7 8 7 8 9 6 8
6 5 6 4 5 6 5 6 6 6
7 8 7 7 6 8 7 8 6 6
5 7 6 7 6 7 6 7 7 7
the above numbers are stored in a text file called data1.txt but need to be displayed properly as ints using a 2D array,
Below is my attempt at the code:
import java.util.*;
import java.io.*;
/**
* class <code>ReadMarks</code> simulates storing student data in a collection.
*
* #author
* #version 09 Feburary 2014
*/
public class ReadMarks
{
/**
* Constructor for objects of class ReadMarks
*/
public ReadMarks()
{
}
/**
* An example of a method - replace this comment with your own
*
*/
public void readMarksData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
while( scanner.hasNext() )
{
String info = scanner.nextLine();
System.out.println(info);
}
scanner.close();
}
for (int i= 0; i <8; i++)
for (int j=1; j<=i; j++)
System.out.print(i*j + "\t");
}
for (int row=1; row<=10; row++)
{
for (int col=1; col<=8; col++)
System.out.print(row*col + "\t");
System.out.println();
}
any answers or replies would be greatly appreciated
In you code, you do not read numbers from file, you just read whole lines and print it. If you want to read all these ints, you should write something like this:
List<Integer> ints = new LinkedList<>();
while (scanner.hasNextInt()) {
ints.add(scanner.nextInt());
}
Now, ints variable holds all ints sequentially read form your file. Then we need to print them. As correctly you've noticed, you will need two loops with nesting. You, however, assumed, that 10 rows and 8 columns. What if it doesn't? And what if we want to reformat our output? Let's rather set the number of columns and we will be printing as many rows, as needed:
int columnCount = 10;
for (int i = 0, l = ints.size(); i < l;) {
for (int c = 0; c < columnCount; c++, i++) {
System.out.printf("%3d", ints.get(i));
}
System.out.println();
}
Now you can just change value of columnCount to reformat output. If you need to print this matrix as a regular square (which not really can be possible, as int count doesn't have to sufficient to form regular square), you can calculate square root of the number of int in the ints list and compare its square to actual length — if those values match, it means you can set the value of columnCount to the square root of int count and be happy with nice square matrix.
How will do a program that displays a multiplication table based on the size that the user inputs? And will add each row and each column? Something like this:
Enter a number: 4
1 2 3 4 10
2 4 6 8 20
3 6 9 12 30
4 8 12 16 40
10 20 30 40
I tried this:
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = s.nextInt();
for(int i = 1; i <= x; i++)
{
for (int j = 1; j <=x; j++)
{
System.out.print((i*j) + "\t");
}
System.out.println();
}
Sample Output:
Enter a number: 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
How I will do to add each row and each column?
Since this seems like homework, I wouldn't feel comfortable writing your code for you. However, keep the following things in mind.
Your matrix will always be a square, as the user only enters a single number, of n x n numbers.
Since these numbers increment by one along the row and column, the sum of each row and column pair will be the same. In other words, the total of row[n] will equal the total of column[n].
Using that, you can create a single array of size n to store the sum of each row. For example:
Enter a number: 3
1 2 3 x
2 4 6 y
3 6 9 z
x y z
When you're looping through each row, you can store the row total in the array.
Row 0: Add 1 + 2 + 3 and store in array[0]
Row 1: Add 2 + 4 + 6 and store in array[1]
Row 2: Add 3 + 6 + 9 and store in array[2]
At the end of each row you can simply display the total in array[row]. When you finish drawing all rows, you'd simply loop through array and display each total value.
Hope this points you in the right direction!
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter size of table: ");
int x = s.nextInt();
int r = 0;
int l = 0;
int f = 0;
for(int i=1;i<=x;i++){
for (int j=1; j <=x; j++)
{
r = r + j;
System.out.print(i*j+"\t");
}
System.out.print(r);
System.out.println();
System.out.println();
l=l+i;
}
for(int k = 1; k<=x;k++)
{
f=f+l;
System.out.print(f + "\t");
}
As I said, I would like to "scroll" through a Multi Dimensional array via the secondary diagonal, my desired input to be: (Case a) [It can be in either C++ or Java, it doesn't matter]
NOTE+EDIT: The order is not random. It starts from the 1 at the bottom and goes its way up.
Is this possible?
If not then at least half of the code? (Case b)
// Case a:
16 15 13 10
14 12 9 6
11 8 5 3
7 4 2 1
// Case b:
0 0 0 1
0 0 9 6
0 8 5 3
7 4 2 1
You can do this with a simple loop (this is Java):
int size = 4;
int[][] matrix = new int[size][size];
// . . .
for (int i = 0; i < size; ++i) {
doSomethingWith(matrix[i][size - i - 1]);
}
int[][] a={{7,6,4,1},{5,3,9,6},{2,8,5,3},{7,4,2,1}};
for(int i=0; i<a.length; i++)
{
for(int j=a[i].length-1; j>=a[i].length-(i+1); j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}