Coding this pyramid pattern with user input and spaces in Java? - java

I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.

I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));

It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}

it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)

Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}

Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.

I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######

Related

The code that I have tried is not displaying the expected output. How can I rectify my code which is related to patterns?

I need to print a square pattern where the number increases as per the row, for example consider variable 'i' which represents row value, if you initialize i=1 and increase the value till 'n' which is user input using while loop, the first row will print 1, second row will print 2 and so on till it reaches the value 'n'. Additionally I created variable for column and named it 'j' whose value also increases till it reaches n.
The output that I'm getting though is:
enter image description here
The code that I have written is: (java)
enter image description here
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int i =1;
while(i<=n){
int j = 1;
while(j<=n){
System.out.println(i);
j=j+1;
}
System.out.println();
i=i+1;
}
Why is the output for the above code:
enter image description here instead of
1111
2222
3333
4444
Please help me out.
Problem
The doc states the following and you know it
Prints an integer and then terminates the line
Fix
Use print instead
while (i <= n) {
int j = 1;
while (j <= n) {
System.out.print(i);
++j;
}
System.out.println();
++i;
}
Improvements
Could be a little bit nicer with for loops
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
System.out.print(i);
}
System.out.println();
}
Using String.repeat
for (int i = 1; i <= n; ++i) {
System.out.println(Integer.toString(i).repeat(n));
}

Can you use charAt();'s to compare values in a string?

I'm writing a java code currently for class and I'm trying to figure out how to implement a run length encoding on a user input. The main problem I'm having it with comparing the first letter with the next and that letter with the next and so on to see if they're the same letter. Currently I have:
System.out.print("Enter a string: ");
String s1 = reader.nextLine();
int sum = 0;
char ast = '*';
//System.out.println("Run length encoded version of string: ");
for (int counter = 0; s1.charAt(counter) <= s1.length()-1; counter++) {
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
if (sum >= 4) {
System.out.print(ast + s1.charAt(counter) + sum);
}
else {
System.out.print(s1.charAt(counter));
}
}
I know where the big problem comes from in this and why it doesn't work but, namely from the
for (int j = 0; s1.charAt(counter) == s1.charAt(j)+1; j++) {
sum++;
counter++;
}
segment as it just goes infinitely. Is there a proper way to do this? The professor mentioned it can be done without loops and while I can see it being possible I can't see it being short. Any help would be appreciated, thanks!
String str="ayyusaab";
char[] ch=str.toCharArray();
for(int i=0;i<ch.length-1;i++){
for(int j=i+1;j<ch.length-1;j++){
if(ch[i]==ch[j]) {
System.out.println(ch[i]+" at Index "+i +"with j at "+j);
}
}
}

Java Nested Loop Triangle [Basic]

So the task is to make the system output a triangle with spaces that increment in between x's like this(dashes added in place of space for readability):
xx
x-x
x--x
x---x
x----x
x-----x
x------x
x-------x
So, I've done this before and it seems easy enough, but the issue I'm having is getting the initial amount of spaces correct. I would like an example of how to do this and why it works as plainly stated as possible, thank you. Here's the code I have so far, along with the output:
Scanner in = new Scanner(System.in);
System.out.println("How many columns");
col = in.nextInt();
for (int i = 0; i < col; i++)
{
System.out.print("#");
for(int j = 0; j < (i+ 1); j++)
{
System.out.print(" ");
}
System.out.print("#");
System.out.println();
}
Output(when cols = 4):
x-x
x--x
x---x
x----x
All help is truly appreciated :)
public static void main(String[]args){
System.out.println("How many columns?");
int columns = new Scanner(System.in).nextInt();
for(int i=0; i<=columns; i++){
String toPrint = "x";
for(int cols=0; cols<i; cols++){
toPrint+=" ";
}
System.out.println(toPrint+"x");
}
}
change condition for j like below. also you have declared variable as col and used it like cols. so make corrections first.
Scanner in = new Scanner;
System.out.println("How many columns");
col = in.nextInt();
for (int i = 0; i < col; i++)
{
System.out.print("#");
for(int j = 0; j < i; j++)
{
System.out.print(" ");
}
System.out.print("#");
System.out.println();
}
I think The problem is with the r value set initially. There is no need of new variable r to be set.
If i is less than j, the loop doesn't get executed first time, and the loop executes 1 step more than each previous iteration of outer for loop

Java Homework - Printing a triangle pattern?

I'm struggling with an assignment. I understand that it is entirely my fault, but I've fallen behind in my classes and am struggling with this assignment.
My goal is to print the following pattern:
*
**
***
****
*****
******
*******
********
*********
**********
Using (nested) for loops.
Would anyone be able to give me hints on how I might go about this? I've managed to print a square of asterisks, but I'm having trouble figuring out how to make a triangle.
Thanks in advance for the help.
First figure out how many lines you need to print out. That's your first for loop. Then on each line, how many asterisks do you need to print out (suppose you are on line i, how many asterisks are on line i)? Answer those questions first and the program should come easily.
Review the following. It doesn't do exactly what you need to do but it will help get you started.
for (int x = 1; x <= 7; x++) {
for (int y = x; y <= 7; y++) {
System.out.print("(" + x + ", " + y + ")");
if (y == 7) {
System.out.print("\n");
}
}
}
Okay, so you basically have to print out as many asterisks as the line number, right?
I'm not allowed to give you code, as this is a homework assignment, but I can give you pseudocode.
start with variable i at 1, loop while i is less than or equal to 10, increment i
// The line of code that you just wrote will execute once per line.
// Now you can print out your asterisks.
// Make another loop and execute it once per asterisk. That's i times, right?
start with variable j at 1, loop while j is less than or equal to i, increment j
print out an asterisk
end loop
end loop
You need 2 loops for these type of problems . 1st loop is used for iteration and the second one for printing the stars. Here 1st u need to get the input from the user and store it in a variable suppose 'n' and the 1st loop should iterate till n .
for(i=1;i<=n;i++)
{for(j=1;j<=i;j++)
{ System.out.print("*");
}
System.out.println("");
}
java8 solution:
IntStream.rangeClosed(0, MAX)
.forEach(i -> IntStream.rangeClosed(0, i)
.mapToObj(j -> j == i ? "*\n" : "*")
.forEach(System.out::print)
);
here is an outline.
for (i = 1; i < 11; i++) {
String toPrint = "";
for (j = 1; j <= i; j++ {
// create string of asterisks here
}
// print a line here
}
since this is homework, you should do the rest yourself
Solution 1:
for(int i=1; i< 10; ++i) {
for (int j = 0; j<i; ++j) {
System.out.print("*");
}
System.out.println("");
}
Soulution 2:
String s = "*";
for (int i = 1; i< 10; i++) {
System.out.println(s);
s = s + "*";
}
Your choice.
class Program
{
static void Main(string[] args)
{
String var = "";
String exp_Str = "";
for (int i = 1; i < 8; i++)
{
for (int j = 1; j < i; j++)
{
if (i > j)
{
var = var + j;
//Console.WriteLine(j+"");
}
}
Console.WriteLine(var);
var = "";
}
Console.ReadLine();
}
}
use a for loop
for(i=0;i<10;i++){
for(int j=0;j<i;j++)
System.out.print("*");
System.out.println();
}
hope that helps!

pyramid sequence in Java

I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}

Categories

Resources