I am doing an exercise where I have to print 'x' (is an input) rows of numbers incrementing from 0 to 10.
If I input 3, the output should look like this
012
345
678
012
345
678
012
345
678
but instead, I get 3 rows of a 0 to 10 count.
I know it might be easy to code, but I am stuck in that!
I think I am not undestanding well the nested loops :(
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
}
}
}
You don't need two loops for this. All you need is to print a newline after every 3rd letter and an extra newline after every 3rd line. Your code can be like:
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
int lines = 0;
int letters = 0;
while (lines < q) {
System.out.print(i);
if (letters && letters % q == 0) {
System.out.println();
lines++;
}
if (lines && lines % q == 0) {
System.out.println();
letters = 0;
continue;
}
letters++;
}
}
PS: I haven't tried this code myself. But concept would be the same.
The answer above should solve your problem so I will try to explain what your code does.
Let's start with code inside first for loop:
for (int i = 0; i <= 10; i++) {
System.out.print(i);
}
System.out.println();
First we have a loop iterating through numbers from 0 to 10 and the output is:
012345678910
and a new line after that.
That means that output of your program will print above mentioned output q times.
012345678910
012345678910
012345678910
You can try with below code
public class quadrats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int j = 0; j < q; j++) {
for (int i = 0; i < 9; i++) {
if(i%3 == 0)
System.out.println();
System.out.print(i);
}
System.out.println();
}
}
}
Print X quandrants of X rows and X columns each
Scanner in = new Scanner(System.in);
int q = in.nextInt();
// q quadrants
for (int iQuadrat = 0; iQuadrat < q; iQuadrat++) {
// count will keep track of the last number you print
int count = 0;
// q rows
for (int iRow = 0; iRow < q; iRow++) {
// q cols
for (int iCol = 0; iCol < q; iCol++) {
System.out.print(count);
// increment the count and take its modulo 10 so it stays between 0 and 9
count = (count+1)%10;
}
// line return at the end of the row
System.out.println();
}
// line return between quadrants
System.out.println();
}
For an input of 12, it will print 12 times this quadrant
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
456789012345
678901234567
890123456789
012345678901
234567890123
Related
I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.
I have been running this algorithm in order to solve this CCC (Canadian Computing Contest) question. It runs fine and gives the correct output on IntelliJ but shows an NoSuchElementException in DMOJ and the CCC online grader.
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
solution(sc.nextInt());
}
public static void solution(int lines) {
Scanner sc = new Scanner(System.in);
int[][] sunflowers = new int[lines][lines];
int[][] temp = new int[lines][lines];
// Creating sunflowers array
for (int i = 0; i < lines; i++) {
for (int j = 0; j < lines; j++) {
sunflowers[i][j] = sc.nextInt();
}
}
boolean readyToSubmit = false;
int a = 0;
int b = 0;
while (readyToSubmit == false) {
b = 0;
a = 0;
readyToSubmit = true;
for (int g = 0; g < sunflowers.length - 1; g++) {
for (int h = 1; h < sunflowers[g].length; h++) {
if (sunflowers[g][h - 1] > sunflowers[g][h]) {
// Turn true if previous value smaller than current
readyToSubmit = false;
}
}
}
// If each column is in descending order
for (int d = 0; d < sunflowers.length; d++) {
for (int e = 1; e < sunflowers.length; e++) {
if (sunflowers[e - 1][d] > sunflowers[e][d]) {
readyToSubmit = false;
}
}
}
if (readyToSubmit == true) {
break;
}
// Rotating the Array w/ temp
for (int i = sunflowers.length - 1; i >= 0; i--) { // we want position to go right -> left
b = 0;
for (int j = 0; j < sunflowers[0].length; j++) { // We want columns to go up -> down
temp[a][b] = sunflowers[j][i];
b += 1;
}
a += 1;
}
for (int x = 0; x < lines; x++) {
for (int y = 0; y < lines; y++) {
sunflowers[x][y] = temp[x][y];
}
}
}
for (int s = 0; s < sunflowers.length; s++) {
for (int k = 0; k < sunflowers[s].length; k++) {
System.out.print(sunflowers[s][k] + " ");
}
System.out.println();
}
}
}
Input:
3
3 7 9
2 5 6
1 3 4
Output (in IntelliJ):
1 2 3
3 5 7
4 6 9
Output (on DMOJ):
IR (java.util.NoSuchElementException)
Output (on CCC Grader):
Exception in thread "main" java.util.NoSuchElementException
<251 more characters> // unfortunately, I am not able to see what the 251 characters are.
I am currently not sure on what causes this NoSuchElementException (since it doesn't tell me the line number on DMOJ nor the CCC grader). Any help would be greatly appreciated.
Note: This is found in the comment section, I just added it as answer to verify that this problem has been solved.
Remove this line Scanner sc = new Scanner(System.in); on the solution method. Then close sc after solution(sc.nextInt()); line on the main method. Refer to this [link]1
pass your scanner in the solution method. Change your solution method to accept a scanner, so the method signature will be public static void solution(int lines, Scanner sc) , then call it in your main method by solution(sc.nextInt(), sc);. Then after solution(sc.nextInt(), sc); close your scanner by using sc.close()
I start from the left-bottom and proceeding in clockwise direction till no chars are left. here is my code.
import java.io.*;
import java.util.*;
public class Solution {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] matrix = new char[n][m];
char[] temp = new char[n*m];
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
matrix[r][col] = sc.next().charAt(col);
}
}
int k=0, l = 0;
while(k < n && l < m){
if(l<m){
for(int i = n-1;i>=k;i--){
temp[count] = matrix[i][l];
count++;
}
l++;
}
for(int i = l;i<m;i++){
temp[count] = matrix[k][i];
count++;
}
k++;
for(int i = k;i<n;i++){
temp[count] = matrix[i][m-1];
count++;
}
m--;
if(k < n){
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
}
n--;
}
}
String code = String.valueOf(temp);
String[] dec = code.split("#");
//System.out.println(dec);
int count2 = dec.length;
System.out.println(count2);
}
}
So can anyone point out where I am going wrong? I start at left bottom, climb up, go right , then go down, go left and continue till no elements left.
There are two issues: incorrect input and missing counter increment.
Incorrect input:
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
// The following reads a new line each time a new character is needed
matrix[r][col] = sc.next().charAt(col);
}
}
This could be fixed either by lifting sc.next() from the inner loop:
for (int r = 0; r < n; r++) {
String line = sc.next();
for (int col = 0; col < m; col++) {
matrix[r][col] = line.charAt(col);
}
}
Or (preferable) removing inner loop completely:
for (int r = 0; r < n; r++) {
matrix[r] = sc.next().toCharArray();
}
Missing increment (lower part of the spiral):
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
// Counter increment is missing. Add
// counter++;
}
In general, is is better to use StringBuilder for gradual construction of the string. In you case it will look as following:
StringBuilder temp = new StringBuilder();
<...>
temp.append(matrix[n-1][i]);
<...>
String code = temp.toString();
In this code you don't have to estimate possible string size nor manually track current insert position.
starting left bottom in the matrix is
matrix[0][m];
going up the hill will be made by decreasing m to a point where you already had a char inserted.
i would use 4 for loops inside a while loop like is presented:
while (usedRow < (int)0.5*n && usedCol < (int)0.5*m)
{
//usedRow and usedCol start with the value of 0 and will be raised
// by the end of the loop
int i, j;
for (i = m - usedCol; i<=(m-usedCol); i++)
{
matrix[usedRow][m-i] = sc.next().charAt(0);
}
for (j = usedRow; j <= (n-usedRow); j++)
{
matrix[n + j][usedCol] = sc.next.charAt(0);
}
for (i = usedCol; i <= (m-usedCol); i++)
{
matrix [n - usedRow][m+i] = sc.next().chatAt(0);
}
for ( j = n - usedRow; j <= (n - usedRow); j++)
{
matrix[n - j][m - usedCol] = sc.next().charAt(0);
}
usedRow++;
usedCol++;
}
this way you go clockwise and keep the loop within the rows and cols that are not in use.
hope that it helped you in a way.
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");
}
}