So i have to write a DrawKwin.java which will print the letter K with little stars(*).
The user gives an integer parameter, if the parameter is less than 4 or more than 30 the program will terminate.
With the parameter, the program will create as many lines as the parameter trying to print the letter K.
For example if the user types the number 6 , the program will print 6 lines trying to create the letter K.The input will be from a input panel with and the letter K will be printed in an output panel with joptionpane.showmessagedialog().
Here is the code without the output panel code:
package Askisi_A1;
import javax.swing.JOptionPane;
class DrawKwin {
public static void main(String[] L) {
int line=Integer.parseInt(L[0]); // make L an integer.
if(line <= 4)
{
System.out.println("Program end, wrong argument!");
System.exit(0);
}
else if(line >= 30)
{
System.out.println("Program end, wrong argument!");
System.exit(0);
}
do
{
int mid=line/2; // find the middle.
int gap=0; // 'gap' is for the gap between the stars .
for(int i=0;i<line;i++) //loop for the creation of letter K.
{
if(i==0) gap=mid;
if(i<mid) // if it is before the middle of letter K, start printing stars and gaps but start with gap=middle and the decrease the number of gaps as you change lines.
{
System.out.print("*");
for(int j=gap;j>0;j--) // placement of gaps between the stars.
{
System.out.print(" ");
}
System.out.println("*");
gap--;
}
else if(i==mid && i!=0) // if it is in the middle of letter K, it will print only one star.
{
System.out.println("*");
gap=1;
}
else // if it is past the middle section of letter K, it will continue printing gaps but now the gaps start from 0 and keep increasing at each line.
{
System.out.print("*");
for(int j=0;j<gap;j++) // placement of gaps between the stars.
{
System.out.print(" ");
}
System.out.println("*");
gap++;
}
}
line = Integer.parseInt(JOptionPane.showInputDialog( "Give me a number ",4)); // input from input panel.
}while(line>=4 && line<=30);
}
}
So , if the user gives the number 5 as an input, the output should be like this:
* *
* *
*
* *
* *
but i need this to be printed in an output panel with the help of joptionpane.showmessagedialog().
Can anybody help me please?
Sorry if my English is bad.
My deadline is in Monday.
Try something like this:
do {
int mid = line / 2; // find the middle.
int gap = 0; // 'gap' is for the gap between the stars .
for (int i = 0; i < line; i++) // loop for the creation of letter K.
{
if (i == 0)
gap = mid;
if (i < mid) // if it is before the middle of letter K, start
// printing stars and gaps but start with
// gap=middle and the decrease the number of
// gaps as you change lines.
{
output += "*";
for (int j = gap; j > 0; j--) // placement of gaps between
// the stars.
{
output += " ";
}
output += "*\n";
gap--;
} else if (i == mid && i != 0) // if it is in the middle of
// letter K, it will print only
// one star.
{
output += "*\n";
gap = 1;
} else // if it is past the middle section of letter K, it will
// continue printing gaps but now the gaps start from 0
// and keep increasing at each line.
{
output += "*";
for (int j = 0; j < gap; j++) // placement of gaps between
// the stars.
{
output += " ";
}
output += "*\n";
gap++;
}
}
JOptionPane.showMessageDialog(null, output);
line = Integer.parseInt(JOptionPane.showInputDialog(
"Give me a number ", 4)); // input from input panel.
output = "";
} while (line >= 4 && line <= 30);
Build your output string then showMessageDialog with output string.
Create a String at the beginning, eg.
String kLetter = "";
After every:
System.out.print("*");
add
kLetter += "*";
System.out.print(" ");
add
kLetter += " ";
System.out.println("*");
add
kLetter += "*\n";
then use
JOptionPane.showInputDialog(result, null);
to show result in dialog and remember to set result to empty string after you show it in dialog.
result = "";
Related
So I just have no idea how could i print a staircase from right to left...
Right now the code works but it prints from left.. (this code is in a method)
Here is the code:
int row = 1;
while (row <= size) {
printStars(row);
row = row + 1;
also i was supposed to create a method that would print a number of spaces:
int space= 0;
while (space < amount) {
System.out.print(" ");
space = space + 1;
}
To print your stars in the opposite order, you can simply reverse the logic of your loop such that it begins at size and approaches zero:
int row = size;
while (row > 0) {
printStars(row);
row = row - 1;
}
import java.util.*;
public class GuessNumber{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int x = 0;
String num = "65854"; // This is the secret code
String s;
System.out.println("This program asks you to guess the code of 5 digits. ");
System.out.println("You have 5 attempts. ");
for(int i=0; i<5; i++){
do{
s = in.nextLine();
for(int c=0; c<s.length(); c++){
if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
}
System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds
}
while(!s.equals(num));
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0);
}
}
}
I tried to create a simple java program which should allow user to guess a prefixed code of five digits (with only five attempts). The do-while loop shows correct values only for the first two attempts, then it goes out of bounds (shows values>5, which are impossible for a code of only 5 digits). Can somebody explain why?
Remove your do-while loop. It will run till user guesses right code.
Insert following code to check length of string
if(s.length()!=5){
System.out.println("code should be of length 5");
continue;
}
You can add more restrictions for no characters in input string.
Also reset x at start of outer loop every time.
Also check if input string is correct in every outer loop
if(s.equals(num)){
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0);
}
this code is gonna run for EVER since you enter the true code , because you have do-while that its condition say !s.equals(num) , so you must remove the do-while at first , it is not neccessary , when your predicted code is equal to the num then the variable x must equal to 5 , so you terminate your program using a return statement after the printing success. be aware of the value of x , it must be equal to zero at each iteration , i mean x=0!
for(int i=0; i<5; i++){
s = in.nextLine();
if(s.length!=5){
System.out.println("code should be of length 5");
continue;
}
x = 0;
for(int c=0; c<5; c++){
if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
}
System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds
if(x==5){
System.out.println("Congrats! You guessed the secret code. ");
return;
}
}
System.out.println("Sryy !! :((");
Current Code -
for (int i = 0; i < 5; i++) {
do {
s = in.nextLine();
for (int c = 0; c < s.length(); c++) { // the length of s can exceed 5 as of **num = "65854"**
if (s.charAt(c) == num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
System.out.println("Number of correct digits in right position: " + x);
}
}
while (!s.equals(num)); // this ensures currently N number of attempts NOT JUST 5 as stated otherwise.
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0); // with this line the for loop would execute just once
}
Suggested Code -
String s;
int count = 0;
int x;
do {
x = 0;
if (count >= 5) { break; } // 5 attempts
s = in.nextLine();
String formattedNumber = String.format("%05d",
Integer.parseInt(s)); // make sure the input is of 5 digit integer (padding here with 0's)
for (int c = 0; c < formattedNumber.length(); c++) {
if (formattedNumber.charAt(c) == num.charAt(c)) {
x++;
}
if (x == 5) { // correct guess if all chars are equal
System.out.println("Congrats! You guessed the secret code.");
break; // break if guessed correct
} else {
System.out.println("Number of correct digits in right position: " + x);
}
}
count++; //next attempt
} while (!s.equals(num)); //input not equals the desired, next attempt
I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.
I need to create a triangle of at least 5 rows.
I know how to create the top and bottom but I can't figure out the middle part. I don't know how to find the algorithms to express the changes in spaces added to each subsequent row following the first. Can I get hints?
This problem is from my teacher.
You can think as this: suppose you want to paint a triangle of R rows. Then, for example, for R = 5, you would paint something like this:
*
**
***
****
*****
which is isosceles (and also right :)). So, the basic observation is that if the current row has i stars, the previous has i-1 and the next one i+1. So, you can initialize a variable with the current row, which also holds the number of stars to paint. Something like this:
int R = (...) // get this parameter from user or whatever
int r = 1; // current row, and number of stars to paint in the current line
while (r <= R) { // while you haven't painted more than R rows
int i = 1; // counter for painting r stars
while (i <= r) {
System.out.print('*');
++i; // next star
}
System.out.println(); // go to the next row (or line)
}
Hope it helped.
Edit: if your teacher is as skeptical as RealSkeptic down there in the comments, you can use the following observation. Suppose you want to paint a triangle like this:
*
**
***
**
*
That is, an isosceles triangle rotated, such that the len of the equal sides is R. For the example, R = 3. You can see that painting such triangle is like painting a rectangle with 2 different kinds of cells, like the following:
*00 (1 star, 2 zeroes)
**0 (2 stars, 1 zero)
*** (3 stars)
**0 (2 stars, 1 zero)
*00 (1 star, 2 zeroes)
You can note that the sequence grows and then decreases back. You can simulate such behavior with a counter that starts in negative values and runs until the same positive value. The code would be something like:
int R = (...) // get this parameter from user or whatever
int r = -R+1;
while (r <= R-1) {
int i = 1;
int rabs = r;
if (rabs < 0) rabs = -rabs; // take only the positive value
while (i <= R-rabs) {
System.out.print('*');
++i; // next star
}
System.out.println(); // go to the next row (or line)
++r;
}
EDIT2: watching the triangle you added to your question (which you should have added since the very beginning), you can follow the reasoning of the previous edit on the number of stars and spaces per row, and reach to a code like the following:
int R = (...) // get this parameter from user or whatever
int r = 1;
while (r < R) {
int i = 1;
while (i <= R-r) {
System.out.print(" ");
++i;
}
if (r>1) System.out.print("*"); // because there's only 1 star on first row always
i = 1;
while (i <= 2*r-3) { // the amount of spaces you need to paint
System.out.print(" ");
++i;
}
System.out.println("*");
++r;
}
// paint the last row separately
int last = R+R-1;
while (last > 0) {
System.out.print("*");
--last;
}
Good luck.
EDIT3: maybe this approach is more verbose, but easier to understand. The point is to save in variables how many spaces you need to print before the first star, and after the first star, in each row. The code would be like this:
int R = (...) // get this number from user or whatever
int spacesBeforeFirstStar = R-1;
int spacesAfterFirstStar = -1;
int r = 1;
while (r <= R) {
int i = 1;
while (i <= spacesBeforeFirstStar) { // paint the first spaces
System.out.print(" ");
++i;
}
if (r!=1) System.out.print("*"); // if not the first row, paint the first star
i = 1;
while (i <= spacesAfterFirstStar) { // paint the spaces inside the triangle
if (r==R) // if we are in the last row
System.out.print("*"); // we paint stars instead spaces
else
System.out.print(" "); // otherwise, we just paint spaces
++i;
}
System.out.println("*"); // print the second star
spacesBeforeFirstStar -= 1; // in the next row, we paint one space less
spacesAfterFirstStar += 2; // in the next row, we paint two spaces more
++r; // go to the next row
}
Here,
int n = 6;
int row = 0;
int col = 0;
int space = 0;
for(row = 1; row < n; row++) {
for(space = 0; space < n - row; space++) {
System.out.print(" ");
}
for(col = 1; col <= row; col++) {
if(row == (n-1)) {
System.out.print("* ");
} else {
if(col == 1 || col == row) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
It prints out the following:
As you can see it's an equilateral triangle. You can modify the code in the loop using conditional statements so that when it reaches at the time of creating the base for the triangle it will print this
I have left that one for you to ponder upon.
I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){