For a homework assignment, I am trying to construct a program that prints an hourglass shape to the screen using asterisks and spaces. I have written the program below, but its output doesn't look anything like an hourglass. Can anyone help me understand why my program isn't producing the expected output?
public class hourglass {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int k = 2 * x - 1;
int c = k;
for (int j = x; j > 0; j--) {
for (int f = j; f <= k; f++) {
System.out.print("*");
}
for (int o = 1; o <= c; o++) {
if (k % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT: I redid the program now it just prints into infinity and beyond, I understand the logic that I need to take in a x number and then run a for loop, each and every time I go through it I -1 from the x.
Can anyone help me with this please? I'm simply trying to deepen my understanding in Java.
public class hourglass
{
public static void main(String[] args)
{
int valueIn = Integer.parseInt(args[0]);
int maxVALUE = 2*valueIn ;
for( int i = 0 ; (valueIn - 1) > i; i--)
{for( int j =1 ; j < maxVALUE; i++)
{
System.out.print("*");}
for (int o = 1; o < maxVALUE; o++) {
if (maxVALUE % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT 2*
If anyone sees this well, here I go.
I've constructed a code on my own for the past 8 hours and now I'm stuck, I don't know how I can "reverse" my for loop to make it print into the other direction here's my code, I don't know what to do and if anyone can give me any insight on how to do this I would be very pleased, I tried doing an if case if(i == 0) but that never happens and I even tried making that if case ==1; but then the loop ran forever.
Any pointers on how to finish my program?
public class mathrandom
{
public static void main ( String [] args)
{
int valueIn = Integer.parseInt(args[0]);
for ( int i = valueIn; 1 <= i; i--){
for ( int k = i ; k < 2*valueIn -1; k++)
{System.out.print(" ");}
{for ( int j = 1; j <= (i*2)-1; j++)
{
System.out. print("*");
}
System.out.println();
}
}
}}
If you don't think in code (and what novice does?), you can try starting by writing a prose(-ish) description of how your program will go about its task, and then writing code that matches up to the prose. For example, you might start with:
Given an input x representing the width of an hourglass shape, print the hourglass to the screen as a series of lines containing asterisks and spaces. The number of asterisks on each line will start at x, count down by two per line until a line containing fewer than two asterisks, then count back up by two per line until it reaches x again. An appropriate number of leading spaces will be printed on each line to center that line's run of asterisks relative to the other lines' (assuming spaces are displayed with the same width as asterisks).
You can even put that into your source code as a comment. In fact, it can help to break it up into several smaller comments, so that you can follow each logical thought with code that corresponds specifically to that thought. If you do that, then not only does it help you organize your code, but you end up with a nicely-documented program without any extra effort.
If you compare my prose to your program, you should see both similarities and differences. Your program performs some kind of count-down, at each step printing zero or more space characters, some asterisks, and then a newline to end the line. Those are basically the right things for it to do, but the details are wrong. Enough wrong and oddly enough wrong, in fact, that I'm inclined to suspect that the program is more cribbed from external sources than thoughtfully constructed de novo. I suggest from here out you devote your attention to writing the program yourself. In fact, consider starting by tossing out everything in main() except int x = Integer.parseInt(args[0]);.
Related
Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}
To this question:
The superqueen is a chess piece that can move like a queen, but also like a knight. What is the maximal number of superqueens on an 8X8 chessboard such that no one can capture an other?
I want to write a brute force algorithm to find the maximum. Here's what I wrote:
public class Main {
public static boolean chess[][];
public static void main(String[] args) throws java.lang.Exception {
chess = new boolean[8][8];
chess[0][0] = true;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
/*Loop to check various possibilities*/
if (!checkrow(i) && !checkcolumn(j) && !checkdiagonals(i, j) && !checkknight(i, j)) {
if (i != 0 || j != 0) {
chess[i][j] = true;
}
}
}
}/*printing the array*/
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(((chess[i][j]) ? "T" : "x") + "|");
}
System.out.println();
}
}
/*All working fine here*/
public static boolean checkrow(int a) {
for (int i = 0; i < 8; i++) {
if (chess[a][i]) {
return true;
}
}
return false;
}
/*All working fine here*/
public static boolean checkcolumn(int a) {
for (int i = 0; i < 8; i++) {
if (chess[i][a]) {
return true;
}
}
return false;
}
/*All working fine here*/
public static boolean checkdiagonals(int pi, int pj) {
int i = pi - Math.min(pi, pj);
int j = pj - Math.min(pi, pj);
for (int k = i, l = j; k < 8 && l < 8; k++, l++) {
if (chess[k][l]) {
return true;
}
}
int i_2 = pi - Math.min(pi, pj);
int j_2 = pj + Math.min(pi, pj);
for (int k = i_2, l = j_2; k < 8 && l > 1; k++, l--) {
if (chess[k][l]) {
return true;
}
}
return false;
}
/*Not All working fine here try commenting out this method above so that that it doesn't run during the check*/
public static boolean checkknight(int pi, int pj) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (0 <= pi + 2 * i && pi + 2 * i <= 8 && 0 <= pj + j && pj + j <= 8) {
if (chess[pi + 2 * i][pj + j]) {
return true;
}
}
if (0 <= pi + i && pi + i <= 8 && 0 <= pj + 2 * j && pj + 2 * j <= 8) {
if (chess[pi + i][pj + 2 * i]) {
return true;
}
}
}
}
return false;
}
}
I have two questions:
My algorithm for checkknight looks for all knight positions, is it wrong? or there is some coding error.Everything is working fine when I comment out it and I get a nice solution.
Secondly it'll result only in one solution.For other solutions I have to offset(or change position) of other pieces bit by bit after each mega-loop of this, I am confused about implementing it. My instincts guide me that I need to change whole of the code. Is there a modification or a way to do it?
Additional Thoughts: I think we would add to a counter each time we place a piece and add to a long array and output the maximum and array after storing the relevant data.
Code Location: You may view/edit/fork/download it at http://ideone.com/gChD8a
This a rough brute-force method starting from the opposite direction, i.e. from the solved eight-queens puzzle. This will allow us to find a bunch of viable solutions.
The brute-force technique for going from a single superqueen to potentially 8 seems to be especially complex due to the knight's traversal. Based on the runs, about 60% of the viable paths for normal queens are invalid with superqueens. So if we were to instead brute force normal queens, and then work backwards, that is potential time saved for finding a solution, and we can better determine the run-time. Because we know normal queens is easier.
We start off with the 12 fundamental solutions, we would then use these as inputs. Solving normal queens is outside this, but the wiki page has a fantastic article describing everything.
In my case, I stored them as Strings representing the coordinate of the queen (the rows are indices).
So: "17468253" = A1, B7, C4, D6, E8, F2, G5, H3
By brute-forcing the opposite direction from solved queens, we only have to test at most 12 x 8! possible solutions. Because order doesn't matter, additional optimization could occur by eliminating duplicate boards and solutions for processing.
First up, checkKnight, which appears to be your source of confusion. Using absolute values, you can reasonably determine whether or not a piece is within knight's range by checking whether the X offset is 2 and Y offset is 1, or vice versa. You've made a complex checkKnight function to check each individual location and whether or not a piece is on the border. Working the other way by hitscanning each queen to each other queen is logically simpler and less of a nightmare to debug.
Queen class
public class Queen {
int i, j;
public Queen(int i, int j) {
this.i = i;
this.j = j;
}
public boolean checkKnight(Queen queen) { // if any queen meets another
// queen at 2 and 1 offset, we
// eliminate it.
return (Math.abs(i - queen.i) == 2 && Math.abs(j - queen.j) == 1)
|| (Math.abs(i - queen.i) == 1 && Math.abs(j - queen.j) == 2);
}
}
This board has been modified since I originally posted. It takes a String input and converts it to a full chessboard. It has some minor work towards the potential any-size board, but right now it handles child board creation. When a child board is created, the queens are passed by reference rather than making a whole new set of queens. A total of 96 queens are stored in memory, 1 for each one on the original 12-board solution. Not perfectly optimized, but better than 96 -> 672 -> 4032 -> ...
Board class
public class Board {
static int boardSize = 8;
ArrayList<Queen> queens = new ArrayList<Queen>();
public Board(String s) {
for (int i = 0; i < s.length(); i++) {
queens.add(new Queen(i, s.charAt(i) - 49)); // you could implement
// base 16 here, for
// example, for a 15x15
// board
}
}
public Board(Board b) { // duplicates the board, but keeps references to
// queens to conserve memory, only 96 total queens
// in existence through search!
for (Queen q : b.queens) {
queens.add(q);
}
}
public boolean checkForImpact() {
for (int i = 0; i < queens.size(); i++) {
for (int j = i + 1; j < queens.size(); j++) {
if (queens.get(i).checkKnight(queens.get(j))) { // just check
// for any
// queens
// intersecting,
// one hit is
// enough
return true;
}
}
}
return false;
}
public ArrayList<Board> getChildBoards() { // create child boards with a
// single queen removed
ArrayList<Board> boards = new ArrayList<Board>();
for (int i = 0; i < queens.size(); i++) {
boards.add(new Board(this));
}
int i = 0;
for (Board b : boards) {
b.queens.remove(i);
i++;
}
return boards;
}
public String drawBoard() {
String s = "";
char[][] printableBoard = new char[boardSize][boardSize];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
printableBoard[i][j] = '_';
}
}
for (Queen q : queens) {
printableBoard[q.i][q.j] = 'Q';
}
s += " A B C D E F G H\n";
for (int i = 0; i < 8; i++) {
s += (8 - i) + "|";
for (int j = 0; j < boardSize; j++) {
s += printableBoard[i][j];
s += "|";
}
s += "\n";
}
return s;
}
}
Test class
import java.util.ArrayList;
public class Test {
static String[] boards = { "24683175", "17468253", "17582463", "41582736",
"51842736", "31758246", "51468273", "71386425", "51863724",
"57142863", "63184275", "53172864" }; // all 12 solutions for the 8
// queens problem
static ArrayList<Board> boardObjects = new ArrayList<Board>();
public static void main(String[] args) {
for (String queens : boards) { // create starter boards
boardObjects.add(new Board(queens));
}
int i;
ArrayList<Board> foundBoards = null;
for (i = 8; i > 0; i--) {
ArrayList<Board> newBoards = new ArrayList<Board>();
foundBoards = new ArrayList<Board>();
for (Board b : boardObjects) {
if (b.checkForImpact()) { // if any queen intercepts we get
// children
ArrayList<Board> boardsToBeAdded = b.getChildBoards(); // pass
// all
// permutations
// of
// queens
// once
// removed
for (Board bo : boardsToBeAdded) {
newBoards.add(bo); // add it in to the next list
}
} else {
foundBoards.add(b); // if we have no impact, we have a
// solution
}
}
if (!foundBoards.isEmpty())
break;
boardObjects.clear();
boardObjects = newBoards;
}
System.out.println("The maximum number of super-queens is: " + i);
ArrayList<String> winningCombinations = new ArrayList<String>();
for (Board board : foundBoards) {
String createdBoard = board.drawBoard();
boolean found = false;
for (String storedBoard : winningCombinations) {
if (storedBoard.equals(createdBoard))
found = true;
}
if (!found)
winningCombinations.add(createdBoard);
}
for (String board : winningCombinations) {
System.out.println(board);
}
}
}
The end output is:
The maximum number of super-queens is: 6
A B C D E F G H
8|Q|_|_|_|_|_|_|_|
7|_|_|_|_|_|_|Q|_|
6|_|_|_|Q|_|_|_|_|
5|_|_|_|_|_|_|_|_|
4|_|_|_|_|_|_|_|Q|
3|_|Q|_|_|_|_|_|_|
2|_|_|_|_|Q|_|_|_|
1|_|_|_|_|_|_|_|_|
A B C D E F G H
8|Q|_|_|_|_|_|_|_|
7|_|_|_|_|_|_|_|_|
6|_|_|_|_|Q|_|_|_|
5|_|_|_|_|_|_|_|Q|
4|_|Q|_|_|_|_|_|_|
3|_|_|_|_|_|_|_|_|
2|_|_|_|_|_|Q|_|_|
1|_|_|Q|_|_|_|_|_|
A B C D E F G H
8|_|_|_|_|Q|_|_|_|
7|Q|_|_|_|_|_|_|_|
6|_|_|_|_|_|_|_|Q|
5|_|_|_|Q|_|_|_|_|
4|_|_|_|_|_|_|_|_|
3|_|_|_|_|_|_|_|_|
2|_|_|Q|_|_|_|_|_|
1|_|_|_|_|_|Q|_|_|
A B C D E F G H
8|_|_|_|_|Q|_|_|_|
7|Q|_|_|_|_|_|_|_|
6|_|_|_|_|_|_|_|Q|
5|_|_|_|Q|_|_|_|_|
4|_|_|_|_|_|_|_|_|
3|_|_|_|_|_|_|Q|_|
2|_|_|Q|_|_|_|_|_|
1|_|_|_|_|_|_|_|_|
A B C D E F G H
8|_|_|_|_|Q|_|_|_|
7|Q|_|_|_|_|_|_|_|
6|_|_|_|_|_|_|_|Q|
5|_|_|_|_|_|_|_|_|
4|_|_|Q|_|_|_|_|_|
3|_|_|_|_|_|_|Q|_|
2|_|_|_|_|_|_|_|_|
1|_|_|_|Q|_|_|_|_|
I've removed the duplicates and made a nice board printing method. don't remember the exact math, but this highlights 40 possible locations. There are others, just by looking, but we've found a fair chunk of them already! From here, we can gently shift individual queens around. From a cursory look, each board has a single piece that can be moved to 3 additional spaces, so now we know there are probably about 160 solutions.
Conclusions
With this application, the run-time on my machine was less than a second, meaning that if we attached this to a standard queens application, the additional knight's brute-forcing would have no impact on that process and have almost the same run-time. In addition, because only 6-piece puzzles are possible, we know that your eventual application run will finish its finding at the 6th piece being placed, as no more solutions are possible, since there are no viable 7-piece and 8-piece solutions.
In other words, finding the maximum super-queen layout is likely actually shorter than the maximum queen layout due to the additional restrictions!
Trying to brute-force such a question is a good way to get a feel for it. So I won't suggest looking up pre-cooked solutions at first.
One little remark though: I don't see the reason for the condition if (i != 0 || j != 0) { that you have there. You are working on Java arrays. Instead of 1 through 8, they go 0 through 7, but the 0 is the first column, you should not eliminate it, otherwise it's only a 7x7 board.
First, let me address your technical question: how to calculate the knight positions.
Take a sheet of quad paper, put a queen somewhere not less than two squares away from the edge. Then mark the end positions of a knight-move from it.
You'll end up with just 8 squares that need to be considered. There is no point in doing a 3x3 loop to find them. A better idea would be to prepare a static array with the relative coordinates of the knight moves - an array of 8 pairs of numbers - and loop on that. So you have only an 8-step loop. In each step of the loop, check for bounds (0 ≤ X + Xoffset < 8, 0 ≤ Y + Yoffset < 8 ), and you have the knight coordinates.
Second, there is no point checking the part of the board that's ahead of you. Since you have not covered the next row and those below it, there is no point in looking for queens there. The implications of this:
You'll never put another queen in the same row where you have just marked a queen position (because you threaten it horizontally). This means that if you mark a queen, you should use continue to break out of the inner loop to the next row.
You don't need checkrow(). When you start a row, there is no queen ahead of you. And if you followed the above bullet point, there is no queen on your back, either.
When you use checkcolumn, you start at row 0, but you can finish at the row before the one you are on (i-1). There are still no queens in the rows below you! The same is true for the diagonal checks.
Earlier I said that you need to prepare and check 8 knight positions. But now you know there is no queen at the knight positions ahead of you. So you only need to prepare an array with four knight positions - the ones above your position.
But most importantly... once you have finished and you have your queens in positions and print the board: you have a single solved board. You have proved that this number of queens is possible. But is it the highest number possible? You have not checked what happens if you don't put a queen on the first square of the first row, but on the second. Perhaps this will allow you to put in an extra queen later. And what about the queen in the second row? Maybe if you moved that, you would be able to put a queen somewhere below where you couldn't before?
So, now you have to actually do the same thing over again, changing one decision every time and working from there. In effect, you have many potential boards. Why? Because there may be more than one valid position on each row where you put that row's queen. So you have decided to put it in the first valid position. But what if you decide to put it in the second valid position? Or leave that row empty? Each such decision is followed by another set of decisions on the next row.
The different boards created by different decisions form a decision tree. The problem for you to consider, therefore, is how to work such a tree out. How to write your decision trail and then backtrack, change, fill another board and count the queens at each level. People here suggested recursion, because it lends itself nicely to such problems. Or you can keep a stack of decisions if you want. You can eliminate some of the potential boards based on symmetries.
I suggest you first make sure you understand your single board well, and then consider how to represent your decision tree and how to traverse it.
There are several questions here.
The first is: how many knight-queens can be placed on an nxn chessboard? Since a k-piece solution can trivially be reduced to a k-1 piece solution, it makes sense to start from the upper bound. That is, look for an n-piece solution, if that fails look for an n-1 piece solution, and so forth.
The second question is: how should I look for a k-piece solution? There are two classic strategies: depth-first and breadth-first. In the former, you consider one vertex of the search tree at a time and use backtracking on failure. In the latter, you consider one complete level of the search tree at a time.
Something that can make a great deal of difference to your search is to account for symmetry (in this case, rotations and reflections).
The third (implicit) question is: what is a good representation here? If your chess-boards are less than 8x8 in size then a 64-bit bit-pattern will do very nicely!
In practical terms, try to separate the three levels of your problem as far as you can. If you don't, you'll find that a choice in one level will severely limit your options at another level.
I have to create a cross shape using methods, and the parameter is the 'size' of the cross. A number is input and the cross is drawn if the number is odd, so if I were to input a 5, the output would look like the screenshot I added to the bottom
The centre line is what's really throwing me off as I've only started methods last week, but so far I have:
import java.util.Scanner;
public class Cross {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type a number: ");
int num = keyboard.nextInt();
drawCross(num);
}
public static void drawCross(int num){
for (int = 1; i <= num; i++) {
if ((num % 2) != 0) {
System.out.println(i + "*");
}
}
}
}
I know this is probably way off, but I'm a total newbie to methods.
Analyze the problem before you start programming. Break the task into steps:
Check whether num is valid for this problem.
num must be positive.
num must be odd.
Notice that you're checking whether num is valid more than once. Check it at the beginning, and quit with an error message if num is invalid. Or, throw an exception, and have main catch it and report to the user.
After you know how to use exceptions, that is.
By the way, num is a bad name for the variable. It's too generic. Except for loop indices, try to have your name be descriptive.
Compute how many spaces must precede the * on all but the center output line.
Compute which line is the center output line.
Do a loop for the top half of the output.
Don't use System.out.println() for individual characters.
That method should be called only once per line.
Print the central line.
Do a loop for the bottom half of the output.
Now, you should try to stop doing everything in main and other static methods. Cross is a class, and you should create an instance of the class and have it do the work.
public class Cross {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type a number: ");
int num = keyboard.nextInt();
Cross cross = new Cross();
cross.drawCross(num);
}
private void drawCross(int size) {
// Your turn.
}
}
Why? So you can test it. One of the most invaluable tools in Java programming is the JUnit library. You will want to offload your logic into tiny methods like:
public boolean validSize(int size) {
// You fill this in.
}
In a test class, CrossTest, you'll write code like:
#Test
public void negativeSizesAreIllegal() {
Cross cross = new Cross();
// Test whether cross.validSize(-13) returns false.
// Look at the JUnit web site or any book describing the tool.
}
Figure out what your requirements on the method are, and write tests to check each one. You'll have similar tests too for 0, odd integers, and even integers. But if you do all your code in static methods, that's a lot harder. This way, as you change your program, you'll know whether your changes have broken your tests. It's like computing an indefinite integral, and differentiating it to check whether you made a mistake.
Finally, simplify your work. The way I outlined your problem, there will be a lot of code duplication. See if you can write a method to replace the duplicate code in steps 4 and 6, and call it twice. Keep going with it; you'll see lots of chances to shorten your program. Having tests is invaluable for that. You'll also be able to use standard methods in the java.lang.String class to simplify things further.
Did you see that
System.out.println(i + "*");
did not do what you thought it did?
Not a best solution. but this one I came up with in 2 mins time :
public static void drawCross(int num){
if (num % 2 != 0) {
for(int i = 0; i < num; i++) {
for(int j = 0; j < num; j++) {
if((i == num / 2) || (j == num / 2))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
Here is some code that should work:
public static void drawCross(int num)
{
if(num % 2 != 0) //if "num" is odd
{
for(int y = 0; y < num; y++) //loop through the following code "num" times
{
for(int x = 0; x < num; x++) //loop through the following code "num" times
{
if(x == (int)(num / 2) || y == (int)(num / 2)) //if "x" or "y" is in the middle
/*(note that at this point "num" will always be odd, so "num / 2" will always
be #.5. That's why the "(int)" is there: to change it from "#.5" to "#"*/
{
System.out.print("*"); //print "*"
}
else //if "x" or "y" is NOT in the middle
{
System.out.print(" "); //print a space
}
}
System.out.println(); //create a new line
}
}
}
public static void drawCross(int num){
if(num % 2 != 0){
for(int line = 0;line < num;line++){
for(int col = 0;col < num;col++){
if(line == num / 2 || col == num / 2) System.out.print("*");
else System.out.print(" ");
}
System.out.println("");
}
}
}
I am new to Java and now I want to learn better for loop. I made some examples , but I don't know how to do a triangle that look like this:
for n=6:
111111
22222
3333
444
55
6
My code until now:
class Pyramid
{
public static void main (String[] args)
{
int i,n=9,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++) {
System.out.print(i); }
System.out.print("\n");
}}}
But what I managed to do it looks like this:
1
22
333
4444
55555
666666
How to make it in reverse order ?
We can use is a function int numberForRow(int row) that will perform a suitable transformation. Then the function can be used like r = numberForRow(i); print(r). It needs to map this:
row (i) -> display number (r)
6 1
5 2
4 3
3 4
2 5
1 6
I think you can write it :)
Look at the relationship between the input (i) and output (r) - it might be useful to note that they always add up to the same value so a little bit of math should do the trick.
(While a function isn't strictly required I find that such functions can help break down a problem and, especially in this case, illustrate a transformation well - it also works in case of a "more advanced" transformation, such as was in the original question ;-)
Your issue is that your outer for loop was going from 6 to 1, so you need to reverse that.
Change
for(i=n;i>=1;i--) {
To
for(i = 1; i <= n; i++) {
Further explanation, so you understand what is happening inside a for loop:
A for loop operates on three clauses: where you start, the condition that the loop runs, and what to do after it runs.
------v
for(i = 1; i <= n; i++) {
This is the assignment. You set a variable to a number, which is where the loop starts. In this case, we start with i = 1, since we want to print only one 1 on the first line. In the third clause, we will increment it (read: add one to it), and run the loop again.
--------------v
for(i = 1; i <= n; i++) {
This is the condition. The loop will run whenever this condition evaluates to true. In other words, if n = 6, this loop will run when i <= 6.
--------------------v
for(i = 1; i <= n; i++) {
This is what will happen each time the loop is executed. After it runs through once when i = 1, we will increment i, so now i = 2. This will happen until the condition (i <= n) evaluates to false, i.e. when i = 7. If the condition is false, the loop will terminate.
public class Pyramid {
public static void main (String[] args)
{
int i,n=9,j;
for(i=1;i<=n;i++)
{
//for(j=1;j<=i;j++) {
for(j=n;j>=i;j--) {
System.out.print(i);
}
System.out.print("\n");
}
}
}
This should help.
Can be done using below method:
public class Main {
public static void main(String[] args) {
int n = 6;
int m =n;
for (int i = 1; i <= n; i++,m--) {
for (int j = 1; j <= m; j++) {
System.out.print(i);
}
System.out.println();
}
}
}
If you want to print the triangular numbers then use the following code
`public class Triangular{
public static void main(String[] args) {
int i = 0;
int j =0;
int count =0;
for (i=1;i<=10;i++){
count = 0; // This is a program to print triangular numbers in JAVA
for(j=1;j<=i;j++){
count = count + j;
}
System.out.println(count);
}
}
}`
Doing some homework in my CSC 2310 class and I can't figure out this one problem... it reads:
Write a program that will draw a right triangle of 100 lines in the
following shape: The first line, print 100 '', the second line, 99
'’... the last line, only one '*'. Name the program as
PrintTriangle.java.
My code is pretty much blank because I need to figure out how to make the code see that when i = 100 to print out one hundred asterisks, when i = 99 print ninety-nine, etc. etc. But this is all i have so far:
public class PrintTriangle {
public static void main(String[] args) {
// Print a right triangle made up of *
// starting at 100 and ending with 1
int i = 100;
while (i > 0) {
// code here that reads i's value and prints out an equal value of *
i--;
}
}
}
The rest of the assignment was way more difficult than this one which confuses me that I can't figure this out. Any help would be greatly appreciated.
You clearly need 100 lines as you know. So you need an outer loop that undertakes 100 iterations (as you have). In the body of this loop, you must print i * characters on a single line, so you just need:
for (int j = 0 ; j < i ; j++) System.out.print("*");
System.out.println(); // newline at the end
Hence you will have:
int i = 100;
while (i > 0) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
i--;
}
Or equivalently,
for (int i = 100 ; i > 0 ; i--) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
EDIT Using only while loops:
int i = 100; // this is our outer loop control variable
while (i > 0) {
int j = 0; // this is our inner loop control variable
while (j < i) {
System.out.print("*");
j++;
}
System.out.println();
i--;
}
So to break it down:
We have an outer loop that loops from i = 100 downwards to i = 1.
Inside this outer while loop, we have another loop that loops from
0 to i - 1. So, on the first iteration, this would be from 0-99
(100 total iterations), then from 0-98 (99 total iterations), then
from 0-97 (98 total iterations) etc.
Inside this inner loop, we print a * character. But we do this i
times (because it's a loop), so the first time we have 100 *s, then 99, then 98 etc. (as
you can see from the point above).
Hence, the triangle pattern emerges.
You need two loops, one to determine how many characters to print on each line, and an inner nested loop to determine how many times to print a single character.
The hint is that the inner loop doesn't always count to a fixed number, rather it counts from 1 to (100 - something).
Try this:
public class PrintTriangle {
public static void main(String[] args) {
for(int i = 100; i >= 1; i--){
System.out.print("\n");
for(int j = 0; j < i; j++){
System.out.print("*");
}
}
}
}
Explanation: The nested for loop has a variable named j. j is the amount of times * has been printed. After printing it checks if it is equal to i. i is a variable in the big for loop. i keeps track of how many times a line has been printed. \n means newline.
You could come at it side ways...
StringBuilder sb = new StringBuilder(100);
int index = 0;
while (index < 100) {
sb.append("*");
index++;
}
index = 0;
while (index < 100) {
System.out.println(sb);
sb.deleteCharAt(0);
index++;
}
But I think I prefer the loop with loop approach personally ;)
You could improve the effiency of the first loop by increasing the number of stars you add per loop and reducing the number loops accordingly...
ie, add 2 starts, need 50 loops, add 4, need 25, add 5 need 20, add 10, need 10...
For example
while (index < 10) {
sb.append("**********");
index++;
}