I am trying to get a for loop inside a for loop so that the output is like this:
I wan the output to show a square
I'm not sure why it isn't doing it.
Below is my code:
import java.util.*;
public class test {
public static void main(String[] args) {
System.out.println("Give me a number : ");
Scanner kb = new Scanner(System.in);
int i = kb.nextInt();
for(int i2=i;i2<i+i;i2++) {
System.out.print("x");
for( i2=i;i2<i+i;i2++) {
System.out.println("x");
}
}
}
}
You need to have separate variables for each of the loops. Otherwise, you'll never run the second iteration of the outer loop. When you're done the inside, your i2 is at the max of the condition of your outer.
Also, you only need the System.out.print() on the inner loop.
for (int j = 0; j < i; j++) {
for (int k = 0; k < i; k++) {
System.out.print("x");
}
// When you're done printing the "x"s for the row, start a new row.
System.out.print("\n");
}
You are using the same loop counter for both loops, i2. So, when your inner loop executes, you are increasing the value of i2 by 1. This continues until i2 gets to your designated stop point. Then the inner loop ends. It then returns to the outer loop, and the outer loop checks if i2 is past the stop point. Since you increased the value of i2 in the inner loop, it is already past the cutoff point, and the outer loop stops.
To fix this, use separate variables for each loop. See below. I use i for the outer loop, j for the inner loop, and number as the cutoff point.
public static void main(String[] args) throws Exception {
int number = 4;
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
System.out.print("X");
}
System.out.println();
}
}
System.out.println("Give me a number : ");
Scanner kb = new Scanner(System.in);
int size = kb.nextInt();
int height = size;
int width = size;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print("X");
}
System.out.println();
}
Related
I'm having following problem with my program.
It's a "connect four" Java console application.
When starting my program, I reset 3 things.
A multi-dimensional char array
public final int rows = 8, columns = 8;
public char[][] board = new char[rows][columns];
I reset it with a for-loop, overwriting every array field with the character '.', which is my default board texture.
public char[][] resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
return board;
}
An integer-array
public int[] nums = new int[columns];
I reset it with a for-loop using the variable i, since I just need an array with the length of columns, which just counts up from 1. It is used so the user know which column he's choosing. Like in chess "A6" e.g., except without letters.
public int[] resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
return nums;
}
An integer
public int roundCounter = 0;
The integers keeps track of how many rounds there have been in the current game. I want it to be printed while playing.
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return roundCounter = 0;
}
I reset these looking like this:
gameMain main = new gameMain();
gameMode mode = new gameMode();
gameCheck check = new gameCheck();
main.board = main.resetBoard();
main.nums = main.resetNums();
check.roundCounter = check.resetRoundCounter();
My problem is when printing the game board, the nums-array and the round counter none seem to work.
The game board is just completely blank. The nums-array is only 0's and the round counter stays at 0.
When running the code in the main-method it worked better than running it through classes etc.
My print method:
public void printBoard() {
gameMain main = new gameMain();
gameCheck check = new gameCheck();
// Printing number array with space in between the elements
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
// Printing the round count next to the number array
System.out.println(" Round " + check.getRoundCounter());
for (int i = 0; i < main.rows; i++) {
for (int j = 0; j < main.columns; j++) {
System.out.print(main.board[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
System.out.println("\n");
}
I could really use some help, since I've been up all night. Originally due to how much fun I was having programming this, now it has become frustrating.
Thanks for reading and thanks in advance!
I think what is happening to you is related to the references of the objects you are using. You are mixing two different ways of working, I give you an example:
You can use the reference of 'roundCounter' and work on it:
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
or you can return it, like this:
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return 0;
}
In the first case, you will have to call the function like this:
resetRoundCounter(); //this function changes the value of your variable.
In the second case, you will have to call the function like this:
roundCounter = resetRoundCounter();
You can choose the way you like to work but I recomend you not working with global variables especially working with methods. I hope it helps you.
Do it as
public void resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
}
public void resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
}
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
Finally, call them as follows:
gameMain main = new gameMain();
gameCheck check = new gameCheck();
main.resetBoard();
main.resetNums();
check.resetRoundCounter();
I also recommend you follow Java Naming Convention e.g. gameMain should be GameMain and gameCheck should be GameCheck.
I'm working on a test prep program. Its not homework or for a grade, I just need help finishing and fixing it so I can study and better understand how it works. The directions are "Write a program named Matrix1.java that randonly fills in 0s and 1s into an n-by-n matrix, prints the matrix." I'm still pretty new to coding so any help would be greatly appreciated. This is the code I have so far:
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix=new Matrix1(5);
matrix.fill();
matrix.print();
}
public Matrix1(int n){
int[][] matrix = new int[n][n];
}
public void fill(int n){ // randomly fill in 0s and 1s
Random rand = new Random();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
Integer r = rand.nextInt;
matrix[i][j] = Math.abs(r);
}
}
}
public void print(int[][]matrix, int n){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.println(array[i][j]);
}
}
}
}
I ended up confusing myself and I'm not sure how to fix it or continue. I think I'm partially on the right track though.
Your code after fixes.
import java.util.Random;
public class Matrix1 {
private final int[][] matrix;
private final int n;
public Matrix1(int n) {
this.n = n;
this.matrix = new int[n][n];
}
/**
* randomly fill in 0s and 1s
*/
public void fill() {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = rand.nextInt(2);
}
}
}
/**
* print the matrix, each row is printed in a separate line
*/
public void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
}
So changes I've made:
I've changed "matrix" and "n" variables into class fields, so you don't have to pass them through class methods
filling array - it should be just 0/1 not any integer so you can use rand.nextInt(2) with bounds - it gives values less then 2
printing array - you have to print row in one line, then change line
It looks like the right direction, check your main method to set the necessary parameters (size, array and size).
Also set the Random object to only be 0 or 1 (Check the Java class libraries for the answer) I believe you can set a parameter inside the Random.nextInt method.
Also if its required to print it like a double array, change up your printing logic since you are always writing to a new line
Well, I see a few problems, which if fixed might help get you on the right track.
First of all, for the random integer, you'll probably want to use the method from this answer:
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);
I don't think you need to use Math.abs in this case, as long as you call ThreadLocalRandom.current().nextInt(0, 2).
Second, there are a couple of problems with your printing code. First of all, you should be using matrix[i][j] instead of array[i][j]. Second, you'll want to use System.out.print instead of System.out.println.
It should be something like this:
for(int i = 0; i< n; i++){
for(int j = 0; j<n; j++){
System.out.print(matrix[i][j]);
}
System.out.println();
}
public class Matrix1{
public static void main(String[] args){
Matrix1 matrix = new Matrix1(5);
matrix.fill();
matrix.print();
}
private int[][] m; //it is easier use a global variable
public Matrix1(int n){
m = new int[n][n];
}
public void fill(){ // randomly fill in 0s and 1s
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m.length; j++){
if (Math.random() > 0.5) {
m[i][j] = 1;
} else {
m[i][j] = 0;
}
}
}
}
public void print(){ //print the matrix, each row is printed in a separate line
for(int i = 0; i< m.length; i++){
for(int j = 0; j<m.length; j++){
System.out.print(m[i][j]); //only use print() for the same row
}
System.out.println("");
}
}
}
This is a very easy code sample of an exercise for school. I got it to work, but I don't understand why my first idea didn't work. My first idea was the while loop in the double for loop (see comments /* */). If I used those loops it gave me an array back that was filled with zeros (there is a file integer.txt with random numbers in the same direction, that's not the problem).
Has it something to do with sc.hasNextInt()? I really don't understand why it works in this way and not the other.
Thanks for explaining in advance.
public static void main(String[] args) throws IOException {
String filename = "integer.txt";
FileReader fr = new FileReader(filename);
Scanner sc = new Scanner(fr);
int[][] getallen = new int[2][5];
/*for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
while(sc.hasNextInt()){
getallen[i][j] = sc.nextInt();
}
}
}*/
while(sc.hasNextInt()){
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
getallen[i][j] = sc.nextInt();
}
}
}
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
System.out.print(getallen[i][j] + " ");
}
System.out.println();
}
System.out.println("Ok.");
sc.close();
}
Why
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
while(sc.hasNextInt()){
getallen[i][j] = sc.nextInt();
}
}
}
this code did not work?
Because as soon as it hits your while loop it will overwrite same index values again and again.
Inside your while loop i and j never move on, so within your while loop you were constantly over-writing the same positions inside getallen.
Just trace through what the code does and it should be obvious. i and j are 0. It then loops through pulling everything from the scanner and setting it into getallen[0][0]. It's then exhausted the scanner so it moves on with 0,0 containing the last scanner value. For every other step (unless something new comes into the scanner) hasNextInt() returns false so it never even executes and getallen[i][j] is not modified, which means it keeps its default value of 0.
How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}
I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}