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.
Related
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();
}
}
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.
Here is one solution to the Josephus problem (where people are arranged in a circle and every other person is killed until only one remains):
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
ArrayList<Integer> chairArr = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
chairArr.add(i);
}
int result = 0;
for (int i = 1; i < chairArr.size() - 1; i = i + 2) {
chairArr.add(chairArr.get(i));
result = i;
}
System.out.print("Result: " + chairArr.get(result));
}
}
But what if, instead of skipping every other person, we increased the number skipped as we went through? That is, if 10 people were arranged in the circle, persons 1, 3, 6, 10, etc. were killed in that order. I think the modification would come in the i = i + 2 in the for loop, but I'm not sure.
I worked it out on paper, and this is the order of elimination, where asterisks denote the number to be removed:
0 *1* 2 3 4 5 6 7 8 9 10
1 2 *3* 4 5 6 7 8 9 10
2 2 4 5 *6* 7 8 9 10
3 2 4 5 7 8 9 *10*
4 2 4 5 7 *8* 9
5 2 4 5 7 *9*
6 2 4 *5* 7
7 *2* 4 7
8 *4* 7
9 7 <-- Result
Thoughts?
Edit: Tried this modification of the for loop:
for (int j = 2; j < chairArr.size() - 1; j++) {
for (int i = 1; i < chairArr.size() - 1; i = i + j) {
chairArr.add(chairArr.get(i));
result = i;
}
}
This won't work because after the initial pass where j = 2, the inner loop will already have narrowed the list down to one candidate so the outer loop never completes.
Write a program that prints the following on the Screen:
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10
3 4 5 6 7 8 9 10
4 5 6 7 8 9 10
5 6 7 8 9 10
6 7 8 9 10
7 8 9 10
8 9 10
I'm having a little trouble correcting the nested loops - I have it to look like that, the numbers won't stop at 10 though. The code prints this:
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
7 8 9 10 11 12 13 14 15 16
8 9 10 11 12 13 14 15 16 17
I'm a beginner programmer and need help with this - do you need a third loop inside of the nested loop already? Any help is appreciated! Here is my code so far:
import java.util.Scanner;
public class LoopProgram
{
public static void main(String args [])
{
for (int e=0; e<8; e++)
{
for (int f=1; f<=10; f++)
{
System.out.print(f + e + " ");
}
System.out.println();
}
}
}
Two loops are enough.
The outer loop runs eight times, you've got that working already.
Your inner loop, however, always runs ten times, which is not what you want. You want the inner loop to run 10 times first, then only 9 times, then only 8 times etc. The trick here is to change the start or end value of that inner loop, like this:
for (int e=0;e<8;e++) {
for (int f=e+1; f<=10; f++) {
...
}
}
I think this is what you are looking for.
for(int e=1;e<9;e++) {
for(int f=e;f<=10;f++) {
System.out.print(f+" ");
}
System.out.println();
}
This ouputs exactly what you asked.
Try this for the second loop:
for(int f=e;f<=10;f++)
and for output
System.out.print(f+" ");
Here's how I would do it
for (int i = 1; i <= 8; i++) {
for (int j = i; j <= 10; j++)
System.out.print(j + " ");
System.out.println();
}
Three loops is severe overkill. This can be done with a single loop and two counters.
public class LoopProgram {
static final int LIMIT_1 = 8;
static final int LIMIT_2 = 10;
public static void main(String[] args) {
int a = 1, b = 2;
while(b <= (LIMIT_1 + 1)) {
System.out.print(a);
if(a < LIMIT_2) {
System.out.print(" ");
a++;
} else {
System.out.println();
a = b;
b++;
}
}
}
}
You only need two loops:
The outer one will run eight times and the inner one will begin at the value of the outer counter (thats what makes each line count up to ten but always start at the first value of last line + 1) and run while it's counter is less than 10.
Something like that:
for (int i = 0; i < 8; i++) {
for (int e = i; e < 10; e++) {
//print e + 1
}
}
You have to print e + 1 so that your lines do not begin at 0, but at one, going up to 10.
This is more of an explanation of how to work this sort of thing out for yourself. In the commonest cases of a for-loop, you should ask yourself three questions about the index variable:
What is the first value I want it to have?
Under what conditions do I want to do another iteration?
How should it change from iteration to iteration?
For your inner loop, the answers are:
e
f <= 10
f++
From that, it is easy to construct the loop, and you already have several examples of it written for you.