Java Nested Loop Triangle [Basic] - java

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

Related

Coding this pyramid pattern with user input and spaces in 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:
#
##
###
####
#####
######

nextInt() Java input in same line

I'm doing a matrix solving console software on java.
What I am trying to do is that each "enter" key do a space instead of break in other to create a row and so on.
When the user types an INT then press "ENTER" it does a break so it breaks the matrix design.
This is my code so far:
Scanner scanner = new Scanner(System.in);//.useDelimiter("\\s+");
for(int i = 0; i < matrix.length; i++) {
System.out.print("| ");
for(int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = scanner.nextInt();
}
System.out.print("|");
System.out.println("");
}
scanner.close();
System.out.println("Done");
Any ideas?
Thanks!
I don't think this possible, so i will suggest another way:
Instead to use Enter and return to the line why you don't write all your values and separate them with a space or a specific delimiter, so when you finish press enter to return to the next line to scan the next row like this:
1 2 3 4 5
5 6 7 8 9
Then you can get your values like this:
String line = scan.nextLine();
String[] row = line.split(" ");
Then use the String[] to get your int values?
This can help you.
In console mode, enter is enter : that is a breakline.
To solve your problem, you could do things differently :
You take a user input without consideration about formatting.
After each input you re-display the actual result of the matrix object.
In this way, you format it as you want, you can even display a special character the position of the next number to fill by the user.
With your actual code it could look like :
Scanner scanner = new Scanner(System.in);//.useDelimiter("\\s+");
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = scanner.nextInt();
displayActualMatrix(matrix)
}
}
scanner.close();
System.out.println("Done");
...
private void displayActualMatrix(int[][] matrix){
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
// rendering the matrix
}
}
...
}

Java - Incrementing Numbers using for loop

I have attempted to complete the following exercise however the output isn't as expected.
You should print a number of pluses equal to the number entered by the user, followed by a list of numbers, so that in total exactly 20 characters are printed. The numbers printed should be the last digit of the current position in the list. Example: +++++678901234567890 if the number entered by the user was 5.
Here's my code:
package interact;
import java.util.Scanner;
public class Interact {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
{int value,k
for (int i=0; i<num1; i++) {
System.out.print("+");}
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
}
The output if 6 is entered is ++++++77777777777777. The numbers aren't incrementing - why not?
You aren't incrementing k or num1, so k becomes whatever number the user enters + 1, and keeps printing that out. You need to update k. First set k=num1. Then change your loop to:
if (k>9) {k=0;}
else k++;
System.out.print(k);
Since, your num1 remains same throughout the below loop.
for (int j=0; j<20-num1; j++) {
if (num1>9) {k=num1-10;}
else k=num1+1;
System.out.print(k);
}
But if you do like this it'll work
k=num1+1;
for (int j=0; j<20-num1; j++) {
if (k>9) {k=0;}
System.out.print(k);
k++;
}
This should fix it for you :)
i can answer any questions you got on the modification :)
good luck :)
int value, k;
for (int i = 0; i < num1; i++) {
System.out.print("+");
}
k=num1;
for (int j = 0; j < 20 - num1; j++) {
if (k >= 9) {
k = 0;
}
else
k++;
System.out.print(k);
}

Reading text files, for in while vs while in for (java)

This is a very easy code sample of an exercise for school. I got it to work, but I don't understand why my first idea didn't work. My first idea was the while loop in the double for loop (see comments /* */). If I used those loops it gave me an array back that was filled with zeros (there is a file integer.txt with random numbers in the same direction, that's not the problem).
Has it something to do with sc.hasNextInt()? I really don't understand why it works in this way and not the other.
Thanks for explaining in advance.
public static void main(String[] args) throws IOException {
String filename = "integer.txt";
FileReader fr = new FileReader(filename);
Scanner sc = new Scanner(fr);
int[][] getallen = new int[2][5];
/*for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
while(sc.hasNextInt()){
getallen[i][j] = sc.nextInt();
}
}
}*/
while(sc.hasNextInt()){
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
getallen[i][j] = sc.nextInt();
}
}
}
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
System.out.print(getallen[i][j] + " ");
}
System.out.println();
}
System.out.println("Ok.");
sc.close();
}
Why
for(int i = 0; i < 2; i++){
for(int j = 0; j < 5; j++){
while(sc.hasNextInt()){
getallen[i][j] = sc.nextInt();
}
}
}
this code did not work?
Because as soon as it hits your while loop it will overwrite same index values again and again.
Inside your while loop i and j never move on, so within your while loop you were constantly over-writing the same positions inside getallen.
Just trace through what the code does and it should be obvious. i and j are 0. It then loops through pulling everything from the scanner and setting it into getallen[0][0]. It's then exhausted the scanner so it moves on with 0,0 containing the last scanner value. For every other step (unless something new comes into the scanner) hasNextInt() returns false so it never even executes and getallen[i][j] is not modified, which means it keeps its default value of 0.

Display triangle shape using asterisk using the substring method

I would like for my program to be in the shape of a triangle with space in between like the photo below.
Heres my code so far.
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String space= " ";
space.replaceAll("", " ");
int i = input.nextInt();
while (i > 0) {
for (int j = 0; j <1; j++)
System.out.print("*"+space.substring(0,0)+"*");
System.out.println();
i--;
}
}
when i run this code the output is this
**
**
**
**
**
**
**
**
**
I would like the output to look like this:
First of all your inner for loop doesn't serve any purpose. It runs only once. The logic would be same even if you remove it.
for (int j = 0; j <1; j++)
Secondly, I feel you wanted to do something like this :
System.out.print("*"+space.substring(i)+"*");
Make sure your string is big enough than the index i
String space= " ";
Scanner input = new Scanner(System.in);
int i=input.nextInt();
for (int j=0; j<(i-1); j++)
System.out.print(" ");
System.out.println("*");
for (int j=1; j<(i-1); j++)
{
for (int k=0;k<(i-1-j); k++)
System.out.print(" ");
System.out.print("*");
for (int k=0;k<(j*2)-1; k++)
System.out.print(" ");
System.out.println("*");
}
for (int j=0; j<(i*2-1); j++)
System.out.print("*");
System.out.println("");
Using something like String.format("%3s, "*") you can define the width (here: 3) and therefore the white-space of the output. If you add some clever code to define the width for each line, you can save yourself a lot of headaches.
In addition it is important to know that only a font with a fixed letter spacing will do the trick (like Currier New).

Categories

Resources