how to print particular value in array with other values change to '*'? - java

For example, in the following layout:
. 8 * * *
. * * * *
. * 8 * *
. * * * *
All of the cards that are face down are indicated by a *. The pairs of 8 which are face up are at coordinates (1,1) and (2,3).
I have done my 2D array and now i'm stuck in printing the *. The one i've done is only printing * * * *. i have no idea how to print the 8 inside the array.
Any help?
public static void Shuffles(){
int[][]a = new int[4][4];
for (int i =0; i<4;i++){
for (int j=0;j<4;j++){
System.out.print("*");
System.out.print(" ");
}
System.out.println("");
System.out.println("");
}
}
public static void main(String[] args) {
List<Integer> randoms = new ArrayList<Integer>();
Random randomizer = new Random();
int [][] memory = new int[4][4];
for(int i = 0; i < 8; ) {
int r = randomizer.nextInt(8)+1;
if(!randoms.contains(r)) {
randoms.add(r);
++i;
}
}
List<Integer> clonedList = new ArrayList<Integer>();
clonedList.addAll(randoms);
Collections.shuffle(clonedList);
randoms.addAll(clonedList);
for(int i=0; i < 4; i++){
memory[0][i] = randoms.get(i);
memory[1][i] = randoms.get(i+4);
memory[2][i] = randoms.get(i+8);
memory[3][i] = randoms.get(i+12);
}
for (int i =0; i<4;i++){
for (int j=0;j<4;j++){
System.out.print(memory[i][j]);
System.out.print(" ");
}
System.out.println("");
System.out.println("");
}
int x1,y1,x2,y2;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the coordinate [x1] : ");
x1 = input.nextInt();
while((x1<1) || (x1>4)){
System.out.print("Invalid coordinate!! Re-enter [x1] : ");
x1 = input.nextInt();
}
System.out.print("Please enter the coordinate [y1] : ");
y1 = input.nextInt();
while((y1<1) || (y1>4)){
System.out.print("Invalid coordinate!! Re-enter [y1] : ");
y1 = input.nextInt();
}
System.out.print("Please enter the coordinate [x2] : ");
x2 = input.nextInt();
while((x2<1) || (x2>4)){
System.out.print("Invalid coordinate!! Re-enter [x2] : ");
x2 = input.nextInt();
}
System.out.print("Please enter the coordinate [y2] : ");
y2 = input.nextInt();
while((y2<1) || (y2>4)){
System.out.print("Invalid coordinate!! Re-enter [y2] : ");
y2 = input.nextInt();
}
x1=x1-1;
y1=y1-1;
x2=x2-1;
y2=y2-1;
if(memory[x1][y1] != memory[x2][y2]){
Shuffles();
}
}
}
this is wad i've done so far...

Are you looking for this?
// k is the number to display
//a[][] is the array
public static void Shuffles(int k, int[][]a)
{
for (int i =0; i<4;i++)
{
for (int j=0;j<4;j++)
{
if(a[i][j] == k)
{
System.out.print(a[i][j]);
}
else
{
System.out.print("*");
}
System.out.print(" ");
}
System.out.println("");
System.out.println("");
}
}

Print the positions one at a time. For each one, check if the card is face up, if so then print the value, else print the star. System.out.print() will allow you to print without a new line.

Are you looking for a nested loop?
for (int y = 0; y < 8; y++)
{
for (int x = 0; x < 8; x++)
{
// Use 'x' and 'y' here to index your 2-D 8x8 array
system.out.println( ... );
}
}

Related

What is the best way to read user inputs via scanner?

I use some approaches similar to the following one in Java:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] a= new int[3];
//assign inputs
for (int i=0;i<3;i++)
a[i] = scan.nextInt();
scan.close();
//print inputs
for(int j=0;j<3;j++)
System.out.println(a[j]);
}
However, generally the first input parameter is length and for this reason I use an extra counter (c) in order to distinguish the first element. When using this approach, the scanner does not read inputs one by one and checking the first and other elements in two blocks seems to be redundant.
// input format: size of 3 and these elements (4, 5, 6)
// 3
// 4 5 6
public static void getInput() {
int n = 0; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array = null;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//block I: check the first element (size of array) and assign it
if (scan.nextInt() <= 0)
System.out.println("n value must be greater than 0");
else {
n = scan.nextInt();
array = new int[n];
}
System.out.println("Enter array elements:");
//block II: check the other elements adn assign them
while(scan.hasNextInt() && c<n) {
if (scan.nextInt() >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c] = scan.nextInt();
c++;
}
}
scan.close();
int sum = 0;
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
My question is "how can I modify this approach with a single block (while and for loop inside while)? I tried 5-6 different variations but none of them works properly?"
Hope this helps,
public static void getInput() {
int n; //size
int c = 0; //counter for distinguish the first index
int sum = 0; //
int[] array;
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
//check the first element (size of array) and assign it
n = scan.nextInt();
while(n <= 0)
{
System.out.println("n value must be greater than 0");
System.out.println("Enter size:");
n = scan.nextInt();
}
array = new int[n];
System.out.println("Enter array elements:");
// check the other elements and assign them
while(c<n) {
int num = scan.nextInt();
if (num >= 100) {
System.out.println("Array elements must be lower than 100");
} else {
array[c++] = num;
}
}
scan.close();
for (int j = 0; j < n; j++) {
sum += array[j];
}
System.out.println("Sum = " + sum);
}
Output:
Enter size:
-1
n value must be greater than 0
Enter size:
4
Enter array elements:
1
2
3
4
Sum = 10
I've optimized your code and fixed some bug.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size:");
int n = scan.nextInt();
if (n <= 0) {
System.out.println("n value must be greater than 0");
return; // need to break from here
}
int c = 0;
int sum = 0; // no need for array
System.out.println("Enter array elements:");
// check the other elements and assign them
while (c++ < n) {
int next = scan.nextInt();
if (next >= 100) {
System.out.println("Array elements must be lower than 100");
c--; // ensure can reenter the number
} else {
sum += next;
}
}
scan.close();
System.out.println("Sum = " + sum);
}

How to accept values within a certain range 2d array

I was wondering how to i set a range between certain number when entering numbers in?
Thanks
I tried using a do loop but it just kept looping even when i entered numbers within the range
public static void main(String args[])
{
int row, col, i, j;
int a[][]=new int[10][10];
do{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the order of a square matrix :");
row=sc.nextInt();
col=sc.nextInt();
/* checking order of matrix and then if true then enter the values
* into the matrix a[][]
*/
if(row == col)
{
System.out.println("Enter elements in the matrix:"+row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
a[i][j]=sc.nextInt();
}
}
} while(row != col);
// Display the entered value
System.out.println ("You have entered the following matrix");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
System.out.print (a[i][j] + " ");
System.out.println ();
}
First of all you should learn to extract tasks in methods and add Javadoc to make your code easier to read.
Hope this helps you:
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int dimension;
System.out.println("Enter the dimension of a squared matrix :");
dimension = sc.nextInt();
final int col = dimension;
final int row = dimension;
int[][] matrix = fillMatrix(row, col);
displayMatrix(matrix);
}
/**
* Prints the given matrix to console
*
* #param matrix to be printed
*/
private static void displayMatrix(int[][] matrix) {
System.out.println("You have entered the following matrix");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
/**
* Uses users input to fill create a matrix with the given dimensions
*
* #param row matrix row dimension
* #param col matrix column dimension
*
* #return a filled matrix
*/
private static int[][] fillMatrix(final int row, final int col) {
System.out.println("Enter elements in the matrix:" + row * col);
int[][] matrix = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int tmpNumber = 0;
while(tmpNumber<15 || tmpNumber >60){
System.out.println(String.format("Enter value for row %s, column %s between 15 and 60", i, j));
tmpNumber = sc.nextInt();
}
matrix[i][j] = tmpNumber;
}
}
return matrix;
}
Output:
Enter the dimension of a squared matrix :
2
Enter elements in the matrix:4
Enter value for row 0, column 0 between 15 and 60
2
Enter value for row 0, column 0 between 15 and 60
17
Enter value for row 0, column 1 between 15 and 60
18
Enter value for row 1, column 0 between 15 and 60
19
Enter value for row 1, column 1 between 15 and 60
20
You have entered the following matrix
17 18
19 20
First add the bounds as constant
final int LOWER_BOUND = 0;
final int UPPER_BOUND = 100;
Then check in the loop each entered value against the bounds before adding the value to the array
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
The problem remaining is that you can't use you for loops as they are now since the user might need several iterations to enter the right value. One simple solution is to surround the above code in a infinite while loop that is not exited until a correct value is given.
while (true) {
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
break;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
}
A better solution might be to replace the innermostfor loop with a while loop where you increase j manually when a correct value has been entered
This is simple example for your cause.
public static void main(String[] args) {
int number;
String getInputLine;
Scanner sc = new Scanner(System.in);
int a[][] = new int[10][10];
// for number of rows in your array
for (int i = 0; i < a.length; i++) {
// for number of columns in your array
for (int j = 0; j < a[0].length; j++) {
// print this message on screen
System.out.print("Enter your number: ");
// get input from next line
getInputLine = sc.nextLine();
//if you haven't match one or more integers
while (!getInputLine.matches("\\d{1,}")) {
System.out.print("Error! You inputted an invalid passcode, try again: ");
getInputLine = sc.nextLine(); // Prints error, gets user to input again
}
number = Integer.parseInt(getInputLine); // parse input into an integer
a[i][j] = number; // store it to array at position i j
System.out.println("You've set number " + number + " for array[" + i + " " + j + "]"); // Prints the passcode
}
}
//print your array
System.out.println(Arrays.deepToString(a));
}
}

Inputting integers in to an array Error?

The purpose of my code is to display the student number and their respective grade as follows:
Student Grade
1 53
2 45
So on...
I used a 5x2 array, in which the user can input the values for the grade...
However I run in to a problem, when inputting the grades, for some reason I have to input 3 values, out of all the 3 inputted values only the 3rd is considered.
My problems:
(1) Why is it that I am even able to enter 3 values per student (Should only be able to input 1 value per student).
(2) Why is it the 3rd value that is being considered?
Here is my code:
import java.util.*;
public class practice {
public static void main(String[] args) {
int[][] studentGrade = new int[5][2];
for(int i = 0; i<5; i++) {
studentGrade[i][0] = i+1;
}
for(int j = 0; j<5; j++) {
System.out.printf("Student %s: ", j+1);
Scanner input = new Scanner(System.in);
if(input.nextInt()>=0 && input.nextInt()<=100) {
studentGrade[j][1] = input.nextInt();
}
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j);
}
}
System.out.print("\nStudent \t Grade");
for(int s=0; s<5; s++) {
System.out.print("\n" + studentGrade[s][0] +"\t" + "\t " + studentGrade[s][1]);
}
}
}
input.nextInt() consumes the next integer in the stream.
You need to do this:
Scanner input = new Scanner (System.in);
for (int j = 0; j < 5; j++) {
System.out.printf("Student %s: ", j+1);
int num = input.nextInt();
if (num >= 0 && num <= 100)
studentGrade[j][1] = num;
else {
studentGrade[j][1] = 0;
System.out.printf("Student %s's mark has been defaulted", j+1);
}
}
This will make it so that you read the number being input only once, and then you use that number when checking boundaries and then setting the grade.

How do I create a loop that takes keyboard input to print out row and column?

My program will output a graphical representation of some rows and columns. It asks the users to input the number of rows and columns they want to see the figure for. For example if the user chooses 4 rows and 3 columns, it should print a figure (let's say it's made up of character X) which has 4 rows and 3 columns.
The final output will look like this:
X X X
X X X
X X X
X X X
Now the problem is I can't set the logic in my for loop so that it makes the desired shape. I tried, but couldn't figure it out.
This what I have done so far:
package banktransport;
import java.util.*;
public class BankTransport {
static int NumOfRow;
static int numOfColum;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
showRowCol(NumOfRow, numOfColum);
}
public static void showRowCol(int NumOfRow, int numOfColum) {
System.out.println("Enter row: ");
NumOfRow = input.nextInt();
System.out.println("Enter Col: ");
numOfColum = input.nextInt();
System.out.println("");
System.out.println("Visual Representation: ");
//print column and row
for (int i = 0; i < numOfColum; i++) {
System.out.print(" X ");
//System.out.println("");
//for(int j=1; j<(NumOfRow-1);j++){
// System.out.print(" Y ");
//}
}
System.out.println("");
}
}
Try a loop like this:
for ( int i = 0; i < numOfRow; i++ )
{
for ( int j = 0; j < numOfColum; j++ )
{
System.out.print(" X ");
}
System.out.println();
}
Try:
for (int i = 0; i < numOfRow; i++) {
StringBuilder line = new StringBuilder();
for (int j = 0; j < numOfColumn; j++) {
line.append("X ");
}
System.out.println(line.toString());
}
You can also use Apache Commons Lang StringUtils.repeat method (which would prevent you from having a trailing space at the end of the line):
for (int i = 0; i < numOfRow; i++) {
System.out.println(StringUtils.repeat("X", " ", numOfColumn));
}

Printing *s as triangles in Java?

My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input how many rows is wanted. The triangles have to look like this
*
**
***
****
*
**
***
****
*
***
*****
So far I was able to do the left aligned triangle but I can't seem to get the other two. I tried googling but nothing turned up. Can anyone help? I have this so far.
import java.util.*;
public class Prog673A
{
public static void leftTriangle()
{
Scanner input = new Scanner (System.in);
System.out.print("How many rows: ");
int rows = input.nextInt();
for (int x = 1; x <= rows; x++)
{
for (int i = 1; i <= x; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
public static void rightTriangle()
{
Scanner input = new Scanner (System.in);
System.out.print("How many rows: ");
int rows = input.nextInt();
for (int x = 1; x <= rows; x++)
{
for (int i = 1; i >= x; i--)
{
System.out.print(" ");
}
System.out.println("*");
}
}
public static void centerTriangle()
{
}
public static void main (String args [])
{
Scanner input = new Scanner (System.in);
System.out.println("Types of Triangles");
System.out.println("\t1. Left");
System.out.println("\t2. Right");
System.out.println("\t3. Center");
System.out.print("Enter a number: ");
int menu = input.nextInt();
if (menu == 1)
leftTriangle();
if (menu == 2)
rightTriangle();
if (menu == 3)
centerTriangle();
}
}
Sample Output:
Types of Triangles
1. Left
2. Right
3. Center
Enter a number (1-3): 3
How many rows?: 6
*
***
*****
*******
*********
***********
Hint: For each row, you need to first print some spaces and then print some stars.
The number of spaces should decrease by one per row, while the number of stars should increase.
For the centered output, increase the number of stars by two for each row.
Ilmari Karonen has good advice, and I'd just like to generalize it a bit. In general, before you ask "how can I get a computer to do this?" ask "how would I do this?"
So, if someone gave you an empty Word document and asked you to create the triangles, how would you go about doing it? Whatever solution you come up with, it's usually not hard to translate it to Java (or any other programming language). It might not be the best solution, but (hopefully!) it'll work, and it may point you to a better solution.
So for instance, maybe you would say that you'd type out the base, then go up a line, then type the next highest line, etc. That suggests that you can do the same in Java -- create a list of Strings, base-to-top, and then reverse them. That might suggest that you can just create them in reverse order, and then not have to reverse them. And then that might suggest that you don't need the list anymore, since you'll just be creating and printing them out in the same order -- at which point you've come up with essentially Ilmari Karonen's advice.
Or, maybe you'd come up with another way of doing it -- maybe you'd come up with Ilmari Karonen's idea more directly. Regardless, it should help you solve this and many other problems.
Left alinged triangle-
*
**
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)each row contains star and no of stars i each row is incremented by 1.
So for Left alinged triangle we need to use 2 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing stars in each rows.
Code for Left alinged triangle-
public static void leftTriangle()
{
/// here no of rows is 4
for (int a=1;a<=4;a++)// for loop for row
{
for (int b=1;b<=a;b++)for loop for column
{
System.out.print("*");
}
System.out.println();}
}
Right alinged triangle-
*
**
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)In each row we need to print spaces followed by a star & no of spaces in each row is decremented by 1.
So for Right alinged triangle we need to use 3 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing spaces.
3rd "for loop" for printing stars.
Code for Right alinged triangle -
public void rightTriangle()
{
// here 1st print space and then print star
for (int a=1;a<=4;a++)// for loop for row
{
for (int c =3;c>=a;c--)// for loop fr space
{
System.out.print(" ");
}
for (int d=1;d<=a;d++)// for loop for column
{
System.out.print("*");
}
System.out.println();
}
}
Center Triangle-
*
* *
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)Intially in each row we need to print spaces followed by a star & then again a space . NO of spaces in each row at start is decremented by 1.
So for Right alinged triangle we need to use 3 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing spaces.
3rd "for loop" for printing stars.
Code for center Triangle-
public void centerTriangle()
{
for (int a=1;a<=4;a++)// for lop for row
{
for (int c =4;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
CODE FOR PRINTING ALL 3 PATTERNS -
public class space4
{
public static void leftTriangle()
{
/// here no of rows is 4
for (int a=1;a<=4;a++)// for loop for row
{
for (int b=1;b<=a;b++)for loop for column
{
System.out.print("*");
}
System.out.println();}
}
public static void rightTriangle()
{
// here 1st print space and then print star
for (int a=1;a<=4;a++)// for loop for row
{
for (int c =3;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int d=1;d<=a;d++)// for loop for column
{
System.out.print("*");
}
System.out.println();
}
}
public static void centerTriangle()
{
for (int a=1;a<=4;a++)// for lop for row
{
for (int c =4;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
public static void main (String args [])
{
space4 s=new space4();
s.leftTriangle();
s.rightTriangle();
s.centerTriangle();
}
}
package apple;
public class Triangle {
private static final int row = 3;
public static void main(String... strings) {
printLeftTriangle();
System.out.println();
printRightTriangle();
System.out.println();
printTriangle();
}
// Pattern will be
// *
// **
// ***
public static void printLeftTriangle() {
for (int y = 1; y <= row; y++) {
for (int x = 1; x <= y; x++)
System.out.print("*");
System.out.println();
}
}
// Pattern will be
// *
// **
// ***
public static void printRightTriangle() {
for (int y = 1; y <= row; y++) {
for (int space = row; space > y; space--)
System.out.print(" ");
for (int x = 1; x <= y; x++)
System.out.print("*");
System.out.println();
}
}
// Pattern will be
// *
// ***
// *****
public static void printTriangle() {
for (int y = 1, star = 1; y <= row; y++, star += 2) {
for (int space = row; space > y; space--)
System.out.print(" ");
for (int x = 1; x <= star; x++)
System.out.print("*");
System.out.println();
}
}
}
This is for normal triangle:
for (int i = 0; i < 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
Output:
*
* *
* * *
* * * *
* * * * *
This is for left triangle, just removed space before printing *:
for (int i = 0; i < 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
Output:
*
**
***
****
*****
1) Normal triangle
package test1;
class Test1 {
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=n-i;j++)
{
System.out.print(" ");
}
for(int k=0;k<=2*i;k++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
2) right angle triangle
package test1;
class Test1 {
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=n-i;j++)
{
System.out.print(" ");
}
for(int k=0;k<=i;k++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
}
}
3) Left angle triangle
package test1;
class Test1 {
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
}
I know this is pretty late but I want to share my solution.
public static void main(String[] args) {
String whatToPrint = "aword";
int strLen = whatToPrint.length(); //var used for auto adjusting the padding
int floors = 8;
for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
for (int k = 1; k < h; k++) {
System.out.print(" ");//padding
}
for (int g = 0; g < f; g++) {
System.out.print(whatToPrint);
}
System.out.println();
}
}
The spaces on the left of the triangle will automatically adjust itself depending on what character or what word you want to print.
if whatToPrint = "x" and floors = 3 it will print
x
xxx
xxxxx
If there's no automatic adjustment of the spaces, it will look like this (whatToPrint = "xxx" same floor count)
xxx
xxxxxxxxx
xxxxxxxxxxxxxxx
So I made add a simple code so that it will not happen.
For left half triangle, just change strLen * floors to strLen * (floors * 2) and the f +=2 to f++.
For right half triangle, just remove this loop for (int k = 1; k < h; k++) or change h to 0, if you choose to remove it, don't delete the System.out.print(" ");.
For the right triangle, for each row :
First: You need to print spaces from 0 to rowNumber - 1 - i.
Second: You need to print \* from rowNumber - 1 - i to rowNumber.
Note: i is the row index from 0 to rowNumber and rowNumber is number of rows.
For the centre triangle: it looks like "right triangle" plus adding \* according to the row index (for ex : in first row you will add nothing because the index is 0 , in the second row you will add one ' * ', and so on).
well for the triangle , you need to have three loops in place of two ,
one outer loop to iterate the no of line
two parallel loops inside the main loop
first loop prints decreasing no of loops
second loop prints increasing no of ''
well i could give the exact logic as well , but its better if you try first
just concentrate how many spaces and how many '' u need in every line
relate the no of symbols with loop iterating no of lines
and you're done
..... if it bothers more , let me know , i'll explain with logic and code as well
This will print stars in triangle:
`
public class printstar{
public static void main (String args[]){
int m = 0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4-i;j++){
System.out.print("");}
for (int n=0;n<=i+m;n++){
if (n%2==0){
System.out.print("*");}
else {System.out.print(" ");}
}
m = m+1;
System.out.println("");
}
}
}'
Reading and understanding this should help you with designing the logic next time..
import java.util.Scanner;
public class A {
public void triagle_center(int max){//max means maximum star having
int n=max/2;
for(int m=0;m<((2*n)-1);m++){//for upper star
System.out.print(" ");
}
System.out.println("*");
for(int j=1;j<=n;j++){
for(int i=1;i<=n-j; i++){
System.out.print(" ");
}
for(int k=1;k<=2*j;k++){
System.out.print("* ");
}
System.out.println();
}
}
public void triagle_right(int max){
for(int j=1;j<=max;j++){
for(int i=1;i<=j; i++){
System.out.print("* ");
}
System.out.println();
}
}
public void triagle_left(int max){
for(int j=1;j<=max;j++){
for(int i=1;i<=max-j; i++){
System.out.print(" ");
}
for(int k=1;k<=j; k++){
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String args[]){
A a=new A();
Scanner input = new Scanner (System.in);
System.out.println("Types of Triangles");
System.out.println("\t1. Left");
System.out.println("\t2. Right");
System.out.println("\t3. Center");
System.out.print("Enter a number: ");
int menu = input.nextInt();
Scanner input1 = new Scanner (System.in);
System.out.print("maximum Stars in last row: ");
int row = input1.nextInt();
if (menu == 1)
a.triagle_left(row);
if (menu == 2)
a.triagle_right(row);
if (menu == 3)
a.triagle_center(row);
}
}
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner userInput = new Scanner(System.in);
int myNum = userInput.nextInt();
userInput.close();
System.out.println("Centered Triange");
for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
System.out.print(" ");
}
for (int j = 0; j < i; j++) { //Prints a " " followed by '*'.
System.out.print(" *");
}
System.out.println(""); //Next Line
}
System.out.println("Left Triange");
for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
for (int j = 0; j < i; j++) { //Prints the '*' first in each line then spaces.
System.out.print("* ");
}
System.out.println(""); //Next Line
}
System.out.println("Right Triange");
for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
System.out.print(" ");
}
for (int j = 0; j < i; j+=1) { //Prints the " " first in each line then a "*".
System.out.print(" *");
}
System.out.println(""); //Next Line
}
}
This is the least complex program, which takes only 1 for loop to print the triangle. This works only for the center triangle, but small tweaking would make it work for other's as well -
import java.io.DataInputStream;
public class Triangle {
public static void main(String a[]) throws Exception{
DataInputStream in = new DataInputStream(System.in);
int n = Integer.parseInt(in.readLine());
String b = new String(new char[n]).replaceAll("\0", " ");
String s = "*";
for(int i=1; i<=n; i++){
System.out.print(b);
System.out.println(s);
s += "**";
b = b.substring(0, n-i);
System.out.println();
}
}
}
For left aligned right angle triangle you could try out this simple code in java:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
for(int i=0;i<size;i++){
for(int k=1;k<size-i;k++){
System.out.print(" ");
}
for(int j=size;j>=size-i;j--){
System.out.print("#");
}
System.out.println();
}
}
}
Find the following , it will help you to print the complete triangle.
package com.raju.arrays;
public class CompleteTriange {
public static void main(String[] args) {
int nuberOfRows = 10;
for(int row = 0; row<nuberOfRows;row++){
for(int leftspace =0;leftspace<(nuberOfRows-row);leftspace++){
System.out.print(" ");
}
for(int star = 0;star<2*row+1;star++){
System.out.print("*");
}
for(int rightSpace =0;rightSpace<(nuberOfRows-row);rightSpace++){
System.out.print(" ");
}
System.out.println("");
}
}
}
*
***
*****
*******
*********
***********
*************
For center triangle
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int b=(n-1)*2;
for(int i=1;i<=n;i++){
int t= i;
for(int k=1;k<=b;k++){
System.out.print(" ");
}
if(i!=1){
t=i*2-1;
}
for(int j=1;j<=t;j++){
System.out.print("*");
if(j!=t){
System.out.print(" ");
}
}
System.out.println();
b=b-2;
}
output:
*
* * *
for(int i=1;i<=5;i++)
{
for(int j=5;j>=i;j--)
{
System.out.print(" ");
}
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
for(int j=1;j<=i-1;j++)
{
System.out.print("*");
}
System.out.println("");
}
*
***
public class Triangle {
public static void main ( String arg[] ) {
System.out.print("Enter Triangle Size : ");
int num = 0;
try {
num = Integer.parseInt( read.readLine() );
} catch(Exception Number) {
System.out.println("Invalid Number!");
}
for(int i=1; i<=num; i++) {
for(int j=1; j<num-(i-1); j++) {
System.out.print(" ");
}
for(int k=1; k<=i; k++) {
System.out.print("*");
for(int k1=1; k1<k; k1+=k) {
System.out.print("*");
}
}
System.out.println();
}
}
}
Target output:
*
***
*****
Implementation:
for (int i = 5; i >= 3; i--)
for (int a = 1; a <= i; a++)
{
System.out.print(" ");
}
for (int j = 10; j/2>=i; j--)
{
System.out.print("*");
}
System.out.println("");
}
(a) (b) (c) (d)
* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********
int line;
int star;
System.out.println("Triangle a");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= line; star++ )
{
System.out.print( "*" );
}
System.out.println();
}
System.out.println("Triangle b");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= 10; star++ )
{
if(line<star)
System.out.print( "*" );
else
System.out.print(" ");
}
System.out.println();
}
System.out.println("Triangle c");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= 10; star++ )
{
if(line<=star)
System.out.print( "*" );
//else
// System.out.print(" ");
}
System.out.println();
}
System.out.println("Triangle d");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= 10; star++ )
{
if(line>10-star)
System.out.print( "*" );
else
System.out.print(" ");
}
System.out.println();
}
You might be interested in this too
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int b=0;
for(int i=n;i>=1;i--){
if(i!=n){
for(int k=1;k<=b;k++){
System.out.print(" ");
}
}
for(int j=i;j>=1;j--){
System.out.print("*");
if(i!=1){
System.out.print(" ");
}
}
System.out.println();
b=b+2;
}
Output:: 5
* * * * *
* * * *
* * *
* *
*

Categories