I'm trying to write a program that outputs a diamond pattern like this:
*
***
*****
***
*
I've started by trying to first get it to print the top half of the diamond.
I can input the 'totalLines' into the console, but I can't type anything when it prompts for 'character'. Why would this be happening?
We've been using JOptionPane for most of our assignments, so it makes sense that I'd be having trouble with this, but from what I can tell from reading the book, this is correct.
(And if you have time to talk to me about the for-loops, I'm pretty sure they need work. I'd be very grateful.)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int totalLines, lines, currLine = 1, spaces, maxSpaces, minSpaces, numCharacters, maxCharacters, minCharacters;
String character;
System.out.print("Enter the total number of lines: ");
totalLines = input.nextInt();
System.out.print("Enter the character to be used: ");
character = input.nextLine();
lines = ((totalLines + 1)/2);
// spaces = (Math.abs((totalLines + 1)/2)) - currLine;
maxSpaces = (totalLines + 1)/2 - 1;
minSpaces = 0;
// numCharacters = (totalLines - Math.abs((totalLines +1) - (2*currLine)));
maxCharacters = totalLines;
minCharacters = 1;
spaces = maxSpaces;
for (currLine = 1; currLine<=lines; currLine++) {
for (spaces = maxSpaces; spaces<=minSpaces; spaces--){
System.out.print(" ");
}
for (numCharacters = minCharacters; numCharacters>= maxCharacters; numCharacters++){
System.out.print(character);
System.out.print("\n");
}
}
}
Try using next() instead of nextLine().
I'm creating a separate answer in regards to your for loops. This should be pretty close to what you need.
StringBuilder might be new to you. Because StringBuilder is mutable and String is not, if you're doing multiple concatenations onto an existing string it's usually preferable to use StringBuilder instead of String. You don't have to use StringBuilder for this exercise but it's a good habit to start.
//Get user input here
int lines = totalLines;
if(totalLines % 2 != 0)
lines += 1;
int i, j, k;
for (i = lines; i > 0; i--)
{
StringBuilder spaces = new StringBuilder();
for (j = 1; j < i; j++)
{
spaces.append(" ");
}
if (lines >= j * 2)
{
System.out.print(spaces);
}
for(k = lines; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}
for (i = 2; i <= lines; i++)
{
StringBuilder spaces = new StringBuilder();
System.out.print(" ");
for (j = 2; j < i; j++)
{
spaces.append(" ");
}
if(lines >= j * 2)
{
System.out.print(spaces);
}
for (k = lines ; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}
Related
My code is supposed to make a pryamid. The example below, however, is supposed to have another A character at the end, like the second example.
ABCDDCBA
ABCCBA
ABBA
AA
ABCDDCBA
ABCCBA
ABBA
AA
A
This is my code. It starts with ABCDDCBA, and removes the characters in the middle each time. So ABCDDCBA would be ABCCBA as the Ds get removed. However, when there are two characters (always the same) the code is supposed to remove one, but it doesn't.
public static void pyramid(int n)
{
int i, j, num, gap;
// outer loop to handle number
// of rows n in this case
for (i = n; i >= 0; i--) {
// inner loop to create right triangle
// gaps on left side of pyramid
for (gap = n - 1; gap >= i; gap--) {
System.out.print(" ");
System.out.print(" ");
}
// initializing value corresponding to ASCII value of 'A'
num = 'A';
// loop to print characters on
// left side of pyramid
for (j = 1; j <= i; j++) {
System.out.print((char)num++ + " ");
}
// loop to print characters on
// right side of pyramid
for (j = i - 0; j >= 1; j--) {
System.out.print((char)--num + " ");
}
System.out.println("");
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
pyramid(n);
}
Please help me. :(
You have a typo in your code:
for (j = i - 0; j >= 1; j--) {
should be
for (j = i - 1; j >= 1; j--) {
I'm trying to create a 2d gamefield with line numbering, but I can't get my head around how to code the numbering correctly in java.
What I have so far is only working up to an imput of rows and columns to 9.
For any two digit number or higher it's not displaying the map correctly as I don't have enough space. I could add to block let's say two blank spaces so the line numbering can go up to hundreds, but I'm trying to get a map that isn't restricted.
Any help is much appreciated.
Here is what I have now:
public String toString() {
String output;
output = "gamemap:\n ";
for (int j = 0; j < this.y; j++) { // loop over columns
output += j;
}
output += "\n *";
for (int j = 0; j < this.y; j++) { // loop over columns
output += "*";
}
output += "*\n";
for (int i = 0; i < this.x; i++) { // loop over rows
output += i + "*";
for (int j = 0; j < this.y; j++) { // loop over columns
output += this.map[i][j];
}
output += "*\n";
}
output += " *";
for (int j = 0; j < this.y; j++) { // loop over columns
output += "*";
}
output += "*\n";
output += "The player has "+ this.player.lives + " lives left.";
return output;
}
private String getPaddedNumber(int number, int maxNumber) {
if(maxNumber <= number) return Integer.toString(number);
int buffer = number;
while((buffer /= 10) != 0 & (maxNumber /= 10) != 0) {
//nothing
}
StringBuilder sb = new StringBuilder();
while(maxNumber != 0) {
sb.append('0'); //alternatively sb.append(' ');
maxNumber /= 10;
}
return sb.append(number).toString();
}
number is the line number you want to display, maxNumber would be the number of lines you have (or more precicely, the highest line index you have)
Good day guys! So I'm self learning java right now. And one of the exercises I'm answering now is creating a program Pyramid.java that takes an input N and prints a
pyramid whose each side is of length N, like the one below: My problem is that everytime I put an input on the command line, the 3 asterisk in the middle don't appear.
*
* *
* * *
* * * *
* * * * *
Here's my code
public class D2Q6 {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int k = 1;
for(int i = 1; i <= N; i++) {
for(int j = 0; j < N-i; j++)
System.out.print(" ");
System.out.print("*");
if(i > 1) {
if(i == N) {
for(int j = 0; j < i-1; j++)
System.out.print(" *");
}
else {
for(int j = 0; j < k; j++)
System.out.print(" ");
k = k+2;
System.out.print("*");
}
}
System.out.println();
}
}
I presume you are trying to execute your program through eclipse or some editor with its own console. The issue might not be with the program, but with the font (type and size) used in console.
Try running the program in DOS prompt, and you might be able to see your desired outcome.
public class PrintPyramidStar
{
public static void main(String args[])
{
int c = 1;
for (int i = 1; i <= 8; i++)
{
for (int j = i; j < 8; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= c; k++)
{
if (k % 2 == 0)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
Above is a random star program I picked using search. Running the same via eclipse console gave me skewed triangle, wherein running the same via windows command prompt gave me a perfect triangle.
I stepped through your program in Eclipse and thought the problem might be here. Currently this is printing a blank space.
else {
for(int j = 0; j < k; j++)
System.out.print(" ");
k = k+2;
System.out.print("*");
}
If you change it to the below, it prints solid asterisk then an extra one at the end;
else {
for(int j = 0; j < k; j++)
System.out.print("*");
k = k+2;
System.out.print("*");
}
However I assume that you are going for a '* * *' kind of thing, but hopefully that narrows it for you.
I would start by creating two methods, one to get the spaces and one to get the asterisks. Something like,
private static String getNSpaces(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(' ');
}
return sb.toString();
}
private static String getNAsterisks(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append('*');
}
return sb.toString();
}
Then your main method can be as simple as -
for (int i = 1; i <= N; i++) {
System.out.print(getNSpaces(N - i));
System.out.println(getNAsterisks(i));
}
When I run the above with N equal to 5 I get
*
* *
* * *
* * * *
* * * * *
I thought I would post an alternative, brief approach to this common programming exercise.
public static void main(String args[]) {
System.out.println(pyramid(Integer.parseInt(args[0])));
}
public static String pyramid(int size) {
return line(size, size);
}
public static String line(int max, int size) {
return size < 1 ? "" : line(max, size - 1) + copies(" ", max - size) + copies("* ", size) + '\n';
}
public static String copies(String s, int size) {
return size < 1 ? "" : String.formatîui("%0" + size + "d", 0).replace("0", s);
}
See live demo
This uses recursion and breaks the code up into meaningful methods that each have their own task that is accomplished in one line.
This is not a high performance solution, but would be fast enough for moderate sizes. It is written for readability and method cohesion.
I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.
I am having difficulties with completing this program. I am trying to make a program that creates asteriks, but then makes it into a triangle.
This is what I have already.
public class 12345 {
public static void main(String[] args) {
int n = 0;
int spaces = n;
int ast;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for (int i = 0; i < n; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces)
System.out.print(' ');
else
System.out.print('*');
}
System.out.println();
spaces--;
}
}
}
It is creating the asteriks, but how would I be able to continue them where they make a triangle... so they get bigger as they go, and then back smaller...
Thank you in advance!
Try moving
int spaces = n;
to AFTER the value of n is read from stdin.
This solves half your problem and hopefully gets you on the right track.
I added a few things to your code and got it to print the full triangle, where the number input in the scanner will be the number of asterisks printed in the bottom row. I.e. if the input is 3, the triangle will be two rows of 1->3; if the input is 5 then the triangle will be 3 rows of 1->3->5, and so on.
public static void main(String[] args) {
int ast;
int reverse = 1;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
int spaces = keyboard.nextInt();
for (int i = 0; i < spaces; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces) {
System.out.print(' ');
} else {
System.out.print('*');}
if (j > spaces + ast) {
for (int k = 0; k < spaces-(reverse-1); k++) {
System.out.print(' ');
}
}
int k = 0;
reverse++;
}
System.out.println();
spaces--;
}
}
}
I added another if statement after your if-else that triggers when the variable j exceeds the first loop condition. This triggers another loop that makes the output lines symmetrical by essentially repeating your first if statement.
I hope this helps =)