The purpose of this program is for the user to decide the length (rows) of a triangle, and also decide if it should be facing up or down. And the triangle is made of letters, so it is supposed to look like this:
How many rows would you like? (finish with -1): 4
Do you want the triangle to face up (1) or down (2)? 1
A
A B
A B C
A B C D
How many rows would you like? (finish with -1): 6
Do you want the triangle to face up (1) or down (2)? 2
A B C D E F
A B C D E
A B C D
A B C
A B
A
I have two problems when I try to get the triangle to print facing down, first the letters look like this (it should begin with an A)
F E D C B A
F E D C B
F E D C
F E D
F E
F
And the letters are followed by loads of different characters that I don't want. I've tried so many things and nothing seems to be working. I could really use some advice.
This is my code so far:
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int a = 0;
int b = 0;
while (a != -1) {
System.out.println("How many rows would you like? (finish with -1):");
a = scan.nextInt();
if (a != -1) {
b = a - 1;
int j = 'A';
char alphabet = (char) (j + 'A');
System.out.println("Do you want the triangle to face up (1) or down (2)?");
int c = scan.nextInt();
if (c == 1) {
for (int i = 1; i <= b + 'A'; i++) {
for (j = 'A'; j <= i; j++)
System.out.print((char) j + " ");
System.out.println(alphabet);
}
} else {
for (int i = 1; i <= b + 'A'; i++) {
for (j = b + 'A'; j >= i; j--)
System.out.print((char) j + " ");
System.out.println(alphabet);
}
}
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 0;
int b = 0;
while (a != -1) {
System.out.println("How many rows would you like? (finish with -1):");
a = scan.nextInt();
if (a != -1) {
System.out.println("Do you want the triangle to face up (1) or down (2)?");
int c = scan.nextInt();
if (c == 1) {
for (int i = 0; i < a; i++) {
for (int j = 0; j <= i; j++) {
System.out.print((char) (j + 'A'));
}
System.out.println();
}
} else {
for (int i = 0; i < a; i++) {
for (int j = a; j > i; j--) {
System.out.print((char) (a - j + 'A'));
}
System.out.println();
}
}
}
}
}
Adopt a more modular solution given below.
It prints both triangles composed of 4 rows, one facing up and the other facing down.
public static void main(String args[]) {
int a = 4; // # of rows
// Triangle facing up
for (int i = 1; i <= a; i++) // i - How many letters in this row (also row No)
printRow(i);
System.out.println("--------"); // Separator
// Triangle facing down - Start from the longest row, then decrease its length
for (int i = a; i > 0; i--)
printRow(i);
}
static void printRow(int length) {
for (int j = 0; j < length; j++) // j - char code shift
System.out.printf("%c ", j + 'A');
System.out.println();
}
This solution is more elegant, as the code to print a row is not repeated.
Note also a more natural way to express the length of consecutive rows: For the triangle facing down the loop decreases the row length.
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--) {
Input: {a, b, c, d} (Character Array)
I want to generate below sequence using above character array as Input
Output:
a bcd
ab cd
abc d
abcd
a b c d
ab c d
a bc d
a b cd
You can try,
char[] a = { 'a', 'b', 'c', 'd' };
for (int i = 0; i < (a.length*2); i++) {
if (i < a.length) {
for (int j = 0; j < a.length; j++) {
System.out.print(a[j]);
if (j == i)
System.out.print(" ");
}
System.out.println("");
} else {
for (int k = 0; k < a.length; k++) {
System.out.print(a[k]);
if (k != (i - (a.length + 1)))
System.out.print(" ");
}
System.out.println("");
}
}
import org.apache.commons.lang3.StringUtils;
public class Demo2 {
public static void main(String...args){
char [] a = {'a','b','c','d'};
String str = String.valueOf(a);//convert to
String[] input = str.split("");//string array
String str1 = StringUtils.join(input,""); // join to "abcd" for the first half of output
String str2 = StringUtils.join(input," "); // join to "a b c d" for the second half of output
for(int i = 1; i<str1.length()+1; i++){
System.out.println(str1.substring(0, i)+" "+str1.substring(i, str1.length())); //insert " "at index i
}
System.out.println(str2);
for(int i = 1; i<str2.length()-1; i=i+2){
System.out.println(str2.substring(0, i)+""+str2.substring(i+1, str2.length())); //remove " " at index i
}
}
}
for (int i = (1 << (a.length - 1)) - 1; i >= 0; --i) {
System.out.print(a[0]);
for (int j = 0; j < a.length - 1; ++j) {
if ((i & (1 << j)) == 0)
System.out.print(" ");
System.out.print(a[j + 1]);
}
System.out.println();
}
this code works for the above given output,
for(i=0;i<(2*a.length);i++){
if(i<a.length){
for(j=0;j<a.length;j++){
System.out.print(a[j]);
if(j==i)
System.out.print(" ");//for white spaces
}
System.out.println(""); //new line
}
else{
for(k=0;k<a.length;k++){
System.out.print(a[k]);
if(k!=(i-(a.length+1)))
System.out.print(" ");
}
System.out.println("");
}
}
But, i think your code doesn't give the expected output, not even the first few lines as you said.
So, for my programming class, our teacher tasked us with making a tree out of *'s and other random characters. There has to be a star at the top of the tree that increases in size every so often, depending how large the user wants the tree. For some reason, if the number the user enters is greater than 15, the bottom half is too far to the right. I tried changing my code, but then everything less than 15 is too far the right. How can I get that to work?
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int a = scan.nextInt();
int b = 0;
int c = 0;
int d = 0;
if ( a >= 12){
d = 1;
} else {
d = 0;
}
//Top Half of Star
for (int i = 0; i < a / 4; i++) {
for (int j = i; j < a; j++){
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++){
System.out.print("*");
b = b + 1;
}
System.out.println("");
}
//Bottom Half of Star
for (int i = 1; i < a/4; i++){
for (int j = d; j < a; j++){
System.out.print(" ");
}
for (int j = c; j < b/3; j++){
System.out.print("*");
}
c = c + 2;
d = d - 1;
System.out.println("");
I think this is what you're looking for, if you're defining the size as the number of rows.
import java.util.Scanner;
public class NestedTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int size = scan.nextInt(); // Get the size of the tree
for (int i = 0; i < size; i++) {
int spaces = size - i;
for (int s = 0; s < spaces; s++) { // Print spaces
System.out.print(" ");
}
for (int r = 0; r <= i; r++) { // Print stars
System.out.print("* ");
}
System.out.print("\n"); // new line
}
}
}
I'm creating a program that can sort objects (vector) with the Bubble sort method. I found a code on the internet which helped me alot to create it (Bubble sort in Arrays):
http://www.programmingsimplified.com/java/source-code/java-program-to-bubble-sort
When i compile the program i don't get any syntax error, but the results are not correct. I think i made an error in the IF-Statement, but i'm not sure if that's the only error. Here is the result i get when i run it:
Input number of integers to sort
5
Enter 5 integers
2
0
1
6
4
Sorted list of numbers
1
2
3
3
3
And here's my code:
import java.util.Scanner;
import java.util.*;
import java.io.*;
class BubbleSortVector {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort");
n = in.nextInt();
Vector v ;
v = new Vector();
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
//v.addElement(c);
v.insertElementAt(in.nextInt(),c);
for (c = 0; c < ( n - 1 ); c++) {
for (d = 0; d < n - c - 1; d++) {
if ((Integer)v.elementAt(d) > (Integer)v.elementAt(d+1)) /* For descending order use < */
{
swap = (Integer)v.elementAt(d);
v.insertElementAt(d+1,d);
v.insertElementAt(swap,d+1);
}
}
}
System.out.println("Sorted list of numbers");
for (c = 0; c < n; c++)
System.out.println(v.elementAt(c));
}
}
// ...
Vector<Integer> v = new Vector<>();
// ...
for (c = 0; c < (n - 1); c++) {
for (d = 0; d < n - c - 1; d++) {
if (v.get(d) > v.get(d + 1)) {
swap = v.get(d);
v.set(d, v.get(d + 1));
v.set(d + 1, swap);
}
}
}
// ...
Your following code is wrong, inserting d+1 at index d means you're using the value of the loop index/counter into the vector, not the actual value that is at d+1
swap = (Integer)v.elementAt(d);
v.insertElementAt(d+1,d); // this is incorrect, d is the index/loop counter
v.insertElementAt(swap,d+1);
Chage that middle line to:
v.insertElement((Integer)v.elementAt(d+1), d);
you can solve it by simple swapping method. after loop you print the array.
int[] Array = new int[5]{2 , 0 , 6 , 1 , 4};
int temp = 0;
for (int i = 0; i < Array.Length; i++)
{
for (int j = 0; j < Array.Length - 1; j++)
{
if (Array[j] > Array[j + 1])
{
temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = temp;
}
}
}
I am trying to extend the following code to sort the array if I added a third value 'C'. Would this be possible to do while retaining only one loop. The following code will sort an array with two possible values 'A' and 'B'.
public class TestSort
{
public static void main(String args[])
{
char f[] = {'A','B','B','A','B','B','A','B','A','A','B'};
int k = 0, t = f.length-1;
while(k < t)
{
if(f[k] == 'A')
k = k + 1;
else if(f[k] == 'B')
{
char m = f[t];
f[t] = f[k];
f[k] = m;
t = t - 1;
}
}
System.out.print("\nSorted List\n");
for(char i : f)
System.out.print(i + ", ");
System.out.println();
}
}
Here is an attempt. I don't know if I'm on the right track.
public class TestSort
{
static char f[] = {'C','A','B','A','C','B','A','B','C','C','B','A','B'};
//static char f[] = {'A','A','A','A','A','C','A','C','A','A','C','A','C'};
//static char f[] = {'C','B','B','B','C','B','B','B','C','C','B','C','B'};
//static char f[] = {'A','B','B','B','A','B','C','B','A','A','B','A','B'};
public static void main(String args[])
{
int j = 0, k = 0, t = f.length-1, l = f.length-1;
while(t >= 0)
{
if(f[k] == 'A')
k = k + 1;
else if(f[k] == 'B')
{
char m = f[j];
f[j] = f[k];
f[k] = m;
j = j + 1;
}
else if(f[k] == 'C')
{
char m = f[l];
f[l] = f[k];
f[k] = m;
l = l - 1;
}
for(char i : f)
System.out.print(i + ", ");
System.out.println();
}
}
}
Maybe something like:
public sort(char[] array) {
int[] frequencies = new int[3];
for(char c : array) {
if (c == 'A')
frequencies[0]++;
if (c == 'B')
frequencies[1]++;
if (c == 'C')
frequencies[2]++;
}
int index = 0;
for (int i = 0; i < frequencies[0]; i++) {
array[index++] = 'A';
}
for (int i = 0; i < frequencies[1]; i++) {
array[index++] = 'B';
}
for (int i = 0; i < frequencies[2]; i++) {
array[index++] = 'C';
}
}
Is the requirement "keep it O(n)", or "keep one loop" ?
Adding a second (non-nested) loop wouldn't change the O(n) quality. then you could do it in two steps: first push all the 'A's to the start and a second one to push all the 'C's to the end.