I want to print number pattern like this..
but, I failed to get this triangle shape,and I am confused how to put spaces to get this shape -->
1
212
32123
4321234
Here's the code i tried so far
public class Ch {
public static void main(String[] args) {
int r =Integer.parseInt(args[0]);
for(int u=1;u<=r;u++)
{
for(int i=u;i>=1;i--)
{
System.out.print(i);
}
for(int i=2;i<=u;i++)
{
System.out.print(i);
}
System.out.println();
}
}
}
output of this code looks-like this
1
212
32123
4321234
Thanks
Just add one more step in you main loop before the other two:
for (int i = u; i < r; i++)
{
System.out.print(" ");
}
This will print spaces to make up for the "missing" numbers.
In regard to Mateusz' comment, look at this answer on how to pad your numbers with spaces to make them equally wide in case you go beyond 9:
static int padding;
public static void main(String[] args)
{
int r = Integer.parseInt(args[0]);
padding = Math.max(1, (int) Math.ceil(Math.log10(r)));
for (int u = 1; u <= r; u++)
{
for (int i = u; i < r; i++)
{
print(" ");
}
for (int i = u; i >= 1; i--)
{
print(i);
}
for (int i = 2; i <= u; i++)
{
print(i);
}
System.out.println();
}
}
private static void print(Object text)
{
System.out.print(String.format("%1$" + padding + "s", text));
}
using 2 for loops
package com.stackoverflow;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the pyramid limit value: ");
int limit = in.nextInt();
in.close();
for (int i = 0; i < limit; i++) {
for (int j = 0; j < limit + i; j++) {
if (j < limit -i-1)
System.out.print(" ");
else{
int temp = (limit-j > 0) ? limit-j : j-limit+2;
System.out.print(temp);
}
}
System.out.println();
}
}
}
using 4 for loops
package com.stackoverflow;
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the pyramid limit value: ");
int limit = in.nextInt();
in.close();
for (int i = 0; i < limit; i++) {
for(int j=0; j<limit-i; j++){
System.out.print(" ");
}
for(int j=0; j<=i; j++){
System.out.print(i-j+1);
}
for(int j=i; j>0; j--){
System.out.print(i-j+2);
}
System.out.println();
}
}
}
Related
Can anyone help me why the calculateCoin function doesn't show up? Basically what it does is, it calculates the coin, that was generated randomly in the drawMap function within 20% chance.
What I did and not sure doing right is, I called the calculateCoin function IN the drawMap function, and then I call the drawMap in the main.
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.drawMap());
}
public int[][] drawMap(){
int[][] map = new int[5][5];
char coin = 'o';
for(int i =0; i<map.length; i++){
for(int j =0; j<map[i].length; j++){
map[i][j] = (int)(Math.random()*10);
if(map[i][j]<2){
System.out.print(coin+ " ");
}
else
System.out.print("*"+ " ");
}
System.out.println("");
}
calculateCoin(map, coin);
System.out.println("");
return map;
}
public int calculateCoin(int[][] map, char coin){
int result = 0;
for(int i = 0; i<map.length; i++){
for(int j = 0; j<map[i].length; j++){
if(map[i][j] == coin){
result++;
}
}
}
return result;
}
The function is actually being called but the value that you return from it is not stored in any variable. If you want something to happen after printing the map, store the result of the call in a variable and then print it.
int calculatedCoin = calculateCoin(map, coin);
System.out.println("Calculated coin: " + calculatedCoin)
try this , but basically you declare a type of a class not a method.
public class dave {
public static void main(String[] args) {
dave main = new dave();
System.out.println(dave.drawMap());
}
public static int[][] drawMap() {
int[][] map = new int[5][5];
char coin = 'o';
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = (int) (Math.random() * 10);
if (map[i][j] < 2) {
System.out.print(coin + " ");
} else
System.out.print("*" + " ");
}
System.out.println("");
}
calculateCoin(map, coin);
System.out.println("");
return map;
}
public static int calculateCoin(int[][] map, char coin) {
int result = 0;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == coin) {
result++;
}
}
}
return result;
}
}
I am writing the code to print a matrix on taking user input in the form of n value:
Suppose if,
n= 3
output:
3 3 3
3 0 3
3 1 3
3 2 3
3 3 3
I am getting ArrayIndexOutOfBoundException in the line: a[i][j]=n;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done. TheArrayIndexOutOfBoundsException is aRuntime Exception thrown only at runtime.
Look at this line:
for(int j=0;i<n;j++)
you increment while "i < n" but you increment "j++".
When your j reaches value 3, the inner loop continues, but exceeds the array-length (of 3, because the hightest array-index is actually 2).
(Also on a minor sidenote, it is usually preferrable to write ++i or ++j within for-loop increments. This is not a rule, just easier to read for most oldscool c-Devs). Also consider leaving spaces to inprove readability:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][] = new int[n][n];
int b = 0;
int mid = n / 2 + 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + j == mid) {
a[i][j] = n - b;
b++;
} else {
a[i][j] = n;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
minor correction in a loop
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++) //minor correction here
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}
1**
2**
3***
4****
Till then I have got this snippet of code
public class triangles {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
You can print your index before the loop :
for (int i = 1; i <= 4; i++) {
System.out.print(i);//<<----------Print the index i
for (int j = 0; j < i; j++) {
System.out.print(i == 1 ? "**" : "*");//check if i == 1 then print 2 stars else 1
}
System.out.println("");
}
In case you mean 1* you can replace System.out.print(i == 1 ? "**" : "*"); with System.out.print("*");
you just need to add i index to print
here you go
public class triangles {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
system.out.println(i);
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
Java 8 simplifies it:
public class triangles {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
System.out.print(i);
System.out.println(String.join("", Collections.nCopies(i, "*")));
}
}
}
Here is my main method in Java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//n is the number of height
int n = in.nextInt();
int j = 0;
int k = 0;
for (int i = 0; i < n; i++)
{
//print out spaces
while(j < n - i)
{
System.out.print(" ");
j++;
}
while(k < (n - j + 1))
{
System.out.print("#");
k++;
}
System.out.println();
j = 0;
k = 0;
}
}
You are printing space for the last line also.
You can replace space with some other visible character and check output.
Here is accepted solution.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(j>=n-i+1)
System.out.print("#");
else System.out.print(" ");
}
System.out.println();
}
}
}
You can try with this code. It's gathering the whole string and printing it at the end.
static void Main(string[] args)
{
int _n;
_n = Convert.ToInt32(Console.ReadLine());
StairCase(_n);
}
static void StairCase(int n)
{
string s = "";
if (n > 0 && n < 101)
{
for (int i = 0; i < n; i++)
{
s = StairCase(s, i + 1);
if (i + 1 < n)
{
s += string.Format("\n");
}
}
}
Console.WriteLine(s);
Console.ReadLine();
}
private static string StairCase(string s, int n)
{
int c = n;
while (c > 0)
{
s += string.Format("#");
c = c - 1;
}
return s;
}