Loop error when printing "triangle" of stars - java

I am trying to print the picture below using nested loops (I should use for & while loops):
**
****
******
********
Starts with 5 spaces, decreasing by 2 each line.
Starts with 2 stars, increasing by 2 each line.
Ends at 4 lines.
My code works on the first line, but it does not print the stars on the remaining 3 lines. Can someone see what the error may be? Please do not give the answer, I just need help understanding the logical error!
int m = 6;
int n = 0;
for(int l = 1; l < 5; l++){
while(m > 0){
System.out.print(" ");
m--;
}
while(n < (2*l)){
System.out.print("*");
n++;
}
System.out.println();
m = 5 - (2*l);
n = n + 2;
}

The error is that you don't reset the n variable each loop. You add 2 to it after the first loop at which point is is already larger than 2 * l so no more stars will be printed.
It would be more sensible to structure it as:
for (int l = 0; l < 4; l ++) {
for (int i = 0; i < 5 - 2l; i++)
System.out.print(" ");
for (int i = 0; i < 2 + 2l; i++)
System.out.print("*");
System.out.println();
}

Hint:
look at m=5 - (2×l);
as soon as l=3
the result will be negativ and the first while-loop wont be executed

Just like you add two to n, you have to remove 2 from m. If I understand quite well, m is your number of spaces and n is your number of stars so if you add two stars; n+2 then you have to remove the space too so: m - 2 since the two added stars occupy that space.
m = m - 2;
n = n + 2;
Edit: you also have to change the while loop where the n is edited, in order not to change the n:
int temp = n;
while(temp > (2*l)){
System.out.print("*");
temp++;
}

Use nested for loops the outer loop moves down the rows and the inner loop moves along the columns. Each pass through the inner loop should check whether ro place an empty space or an asterisk. This can be done with an if statement use the integer variables in the for loops to determine when to place a space or an asterisk. The algorithm for this will vary depending on the shape you want.
Alternatively the use of a doubly indexed array might be interesting here. More complext but maybe something to look at if you need to use a while loop. It might be possible to use for loops to fill a doubly indexed char array with either a " " or a "*" and then simply print out ghe contents of the array while setting the value to null after printing and checking to see if the array is empty or not.
Maybe some of this was helpful. Happy coding.

Related

Taking data from one array to create another. What's wrong with this loop?

I am working on an assignment where I need to create two arrays, then look through them and create a new array that holds any values inside of both the first two. Originally, I was close to accomplishing this by making an arraylist but my lab professor told me that wasn't allowed so I needed to re-start and didn't have enough time to figure out the solution.
If you'd like to see the whole code I have now: http://pastebin.com/thsYnj2z
I am really struggling with this loop here:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
My output is remaining 0 for my ArrA[k] array. I can't seem to trouble shoot this issue on my own.
try making these changes
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
note
Assuming OP has correctly initialized ArrA
note2
Assuming that only unique values are required, hence the breaking
Does your solution require that no values are duplicated in ArrA? Or are duplicate values allowed? For example, if some values occur multiple times in each array, you could get multiple matches on the same number.
If duplicates aren't a problem:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++){
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++;
}
}}
As I understand it, the problem is to take 2 arrays, and produce a third array which is a Union of the first 2. Union of 2 sets being the subset of the values found in both sets.
Your code was missing some braces, so put those back in there. Also you wont want to print the k+1th item after you just put a value in ArrA[k] im assuming.
Otherwise you were pretty much there. The break terminates the inner loop and allows the outer loop to increment i and continue on. This is because you have already found a match, no need to continue searching, just move onto the next index in Xarr.
Algorithm goes like this: For each value in X, search Y for a match. If it is found, add this value to A.
for(int i = 0 ; i < Xarr.length ; i++) {
for(int j = 0 ; j < Yarr.length ; j++) {
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++; //you probably want to increment k after you add to ArrA, not before
break;
}
}
}
public static void main(String... args){
int[] xArr = {1, 1,1,1,1,1};
int[] yArr = {1, };
int[] kArr = new int[xArr.length > yArr.length ? xArr.length : yArr.length];
int k = 0;
for(int x = 0; x < xArr.length; x++){
for(int y = 0; y < yArr.length; y ++){
int xNum = xArr[x];
int yNum = yArr[y];
if(xNum == yNum) kArr[k++] = xNum;
}
}
int[] resizedKArr = new int[k];
for(int i = 0; i < resizedKArr.length; i++) resizedKArr[i] = kArr[i];
Arrays.sort(resizedKArr);
for(int x : resizedKArr) System.out.println(x);
}
First, xArr and yArr are given some random numbers, and then kArr is initialized with the size of the lagest array we are comparing with to ensure the array has enough space to hold similar values.
Then, in the next section we do a loop inside of a loop to compare the values against each other and if they are similar then k++ and set the next value in the array. This goes on until the loops are completed, notice there really is never a need to break from either loop until all values are compared. At that point the loops break themselves and move on to the next bit of code.
The last section is just to create an array of the same size as k and move the values over, I don't know the requirements of your studies, although when using primitives like this you may want to do this in case you have a matching 0 as a number. Otherwise you'll have a ton of 0s filling the empty spaces of your array.
And lastly, we just sort the array for good measure and print it out.
Hope I've answered your question and you get something out of this post!
The problem is printing ArrA[k] after k++. Try increasing line after print.

What do I need to do to my current code to make the program run a multiplication table (using a two dimensional array)?

I'm trying to make a Java program that uses the input value from a user to calculate and list the products of two numbers up to the entered number. Like if a user enters 2, the program should calculate the products between the two numbers (1 *1, 1*2, 2*1, 2*2) stores the products in a two-dimensional array, and list the products. I'm not sure that I totally understand arrays and so I feel as though my code is problem not right in many instances, can someone please tell me what I should do to my current code to make it work properly. Thanks in advance! :)
import java.util.Scanner;
public class ProductTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputString;
char letter = 'y';
// Prompt the user to enter an integer
while(letter != 'q') {
System.out.print("Enter a positive integer: ");
int integer = input.nextInt();
// Create an two-dimensional array to store products
int[][] m = new int[integer][3];
for (int j = 1; j <= m.length; j++) {
m[j][0] = input.nextInt();
m[j][1] = input.nextInt();
m[j][2] = input.nextInt();
}
// Display the number title
System.out.print(" ");
for (int j = 1; j <= m.length; j++)
System.out.print(" " + j);
System.out.println("\n--- ");
// Display table body
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
// Prompt the user to either continue or quit
System.out.print("Enter q to quit or any other key to continue: ");
String character = input.nextLine();
inputString = input.nextLine();
letter = inputString.charAt(0);
}
}
}
You can achieve your multiplication table by iterating over 2 counter variables as you already did in your output
// Display table body
// loops running out of bounds (until m.length + 1 instead of m.length-1)
for (int i = 1; i <= m.length + 1; i++) {
System.out.print(i);
for (int j = 1; j <= m.length + 1; i++) { // missed to increment j here
System.out.printf("%4d", i * j);
}
System.out.println();
}
Arrays should be based on 0, that means an array with 3 fields has the indexes 0, 1, 2. So the last index is length-1. Your condition <=m.length+1 runs out of bounds. index<length will work since 2 is less than 3, but not 3 less than 3.
You have also a typo: In the inner loop you are doing an increment of i instead of j, so the loop will run infinite.
Try to create an outer and inner loop as you did, but with start index 0 and end condition index<inputValue. Calculate multiTable[index1][index2] = (1+index1)*(1+index2).
Then do a similar loop and print the array fields. You don't need to use an array, you could output directly as you did. But you wanted to practice handling arrays.
Since you want to learn and understand, I don't like just to write the code. imagine an array with 3 fields having the indexes 0, 1, 2:
index 0 | 1 | 2
value 1 | 2 | 3
Now you would check the length at first, that's 3. You start with 0 and count while the counter does not reach the length since the zero based index is 1 below our natural order (0,1,2 vs. 1,2,3). That is the case as long the index is below the length, meaning index<length.
Try this logic (pseudo code). To simplify the problem we include the 0 in our product table. So we get 0*0, 0*1, 0*2... Doing so, we do not have to ignore index 0 or to calculate between index 0 should represent value 1.
maxNumber = userInput()
outer loop idx1 from 0 to maxNumber
inner loop idx2 from 0 to maxNumber
array[idx1][idx2] = (idx1) * (idx2)
end loop
end loop
Do the same to dump your generated array to screen.
First get it running. Afterwards you could try to alter the logic, so that it shows you only numbers from 1 to max.

Reverse printing of an array

(Java beginner)
I came up with a code that would display an int array in reverse and although I know there's probably a better way to do it, I think this logic should work:
for(int i = 0, j = numList.length - 1; i < j; i++, j--)
{
int temp = numList[i];
numList[i] = numList[j];
numList[j] = temp;
System.out.print("Reverse order: " + temp + " ");
}
What I don't understand is that when I enter 5 numbers, the console only shows the first two numbers and it ends there:
1
2
3
4
5
Reverse order: 1 2
What's wrong here and what can I do to fix it?
That code is just faulty. Use this instead.
for(int i = numList.Length - 1; i >= 0;i--)
{
int temp = numList[i];
System.out.print("Reverse order: " + temp + " ");
}
In your code, you increment i and decrement j, meaning that if you'd loop untill your condition is satisfied, you'd get about half the loop done. Try and create a table of the values of your loop step by step, you'll see what I mean :)
i++ and j-- along with the loop iteration condition of i < j would become false when i and j reach the middle of the array. So essentially your for loop is only working up the first half of the loop. I didnt run you code but this is the first observation i made.

beginner java, showing special characters that correlate to an integer

Doing some homework in my CSC 2310 class and I can't figure out this one problem... it reads:
Write a program that will draw a right triangle of 100 lines in the
following shape: The first line, print 100 '', the second line, 99
'’... the last line, only one '*'. Name the program as
PrintTriangle.java.
My code is pretty much blank because I need to figure out how to make the code see that when i = 100 to print out one hundred asterisks, when i = 99 print ninety-nine, etc. etc. But this is all i have so far:
public class PrintTriangle {
public static void main(String[] args) {
// Print a right triangle made up of *
// starting at 100 and ending with 1
int i = 100;
while (i > 0) {
// code here that reads i's value and prints out an equal value of *
i--;
}
}
}
The rest of the assignment was way more difficult than this one which confuses me that I can't figure this out. Any help would be greatly appreciated.
You clearly need 100 lines as you know. So you need an outer loop that undertakes 100 iterations (as you have). In the body of this loop, you must print i * characters on a single line, so you just need:
for (int j = 0 ; j < i ; j++) System.out.print("*");
System.out.println(); // newline at the end
Hence you will have:
int i = 100;
while (i > 0) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
i--;
}
Or equivalently,
for (int i = 100 ; i > 0 ; i--) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
EDIT Using only while loops:
int i = 100; // this is our outer loop control variable
while (i > 0) {
int j = 0; // this is our inner loop control variable
while (j < i) {
System.out.print("*");
j++;
}
System.out.println();
i--;
}
So to break it down:
We have an outer loop that loops from i = 100 downwards to i = 1.
Inside this outer while loop, we have another loop that loops from
0 to i - 1. So, on the first iteration, this would be from 0-99
(100 total iterations), then from 0-98 (99 total iterations), then
from 0-97 (98 total iterations) etc.
Inside this inner loop, we print a * character. But we do this i
times (because it's a loop), so the first time we have 100 *s, then 99, then 98 etc. (as
you can see from the point above).
Hence, the triangle pattern emerges.
You need two loops, one to determine how many characters to print on each line, and an inner nested loop to determine how many times to print a single character.
The hint is that the inner loop doesn't always count to a fixed number, rather it counts from 1 to (100 - something).
Try this:
public class PrintTriangle {
public static void main(String[] args) {
for(int i = 100; i >= 1; i--){
System.out.print("\n");
for(int j = 0; j < i; j++){
System.out.print("*");
}
}
}
}
Explanation: The nested for loop has a variable named j. j is the amount of times * has been printed. After printing it checks if it is equal to i. i is a variable in the big for loop. i keeps track of how many times a line has been printed. \n means newline.
You could come at it side ways...
StringBuilder sb = new StringBuilder(100);
int index = 0;
while (index < 100) {
sb.append("*");
index++;
}
index = 0;
while (index < 100) {
System.out.println(sb);
sb.deleteCharAt(0);
index++;
}
But I think I prefer the loop with loop approach personally ;)
You could improve the effiency of the first loop by increasing the number of stars you add per loop and reducing the number loops accordingly...
ie, add 2 starts, need 50 loops, add 4, need 25, add 5 need 20, add 10, need 10...
For example
while (index < 10) {
sb.append("**********");
index++;
}

Programming exercise is following: exercise on for-structure. How to write a program, which prints below christmastree?

O
OOO
OOOOO
OOOOOOO
OOOOOOOOO
OOOOOOOOOOO
OOOOOOOOOOOOO
OOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOOOOOOOO
O
Is there some hint for me. I'm stuck. This should be possible to do with for-structure.
_ ~ empty
0 ~ 0-sign
if luku =3 then.
__0__
_000_
00000
So
for( int i=0; i<luku; i++)
for( int j=0; j<luku; j++)
System.out.print(" ");
Here is a hint:
int i, length = 20; //adjust for your needs
for(i = 0; i < 20; i++) {
//print a space for (20-i)/2 times
//print '0' for i times
//print a newline
}
I think this should get you started
Hints :
Looping. You can solve this with two loops.
First will have as limit the number of lines.
Second loop will have a limit of one and will increase by two for each iteration. This until the second to last line.
Then you should print a single 0.
There are plenty of ways to do this. While/for loops. % operator. Try something and come back for more help if you are stuck.
You can start with something like this. Which loops through the rows, and increases the number of innerloops to get more O's
for (int pos = 1; pos < 12; pos++) (
for(int o = 0 ; o < p ; o++)
{
// Draw O
}
}
Where you use p, which is increased each round, as the number of O's you want to print.
You need a number of lines, and on every line there is an increasing number of 0s and a decreasing number of spaces. You create a for-loop, which usually increases a variable up to a certain point and then stops looping.
for(int i = 0; i < 12; i++) {
// print line
}
I think this is already too much help, but oh well. If you can't figure it out now, you should ask your teacher or read the book or look up "for-loops".
EDIT: maybe this solution in Brainfuck helps:
+++++
>>>>>>
++++++++++++++++
++++++++++++++++
>
++++++++++++++++
++++++++++++++++
++++++++++++++++
>
++++++++++
<<<<<<<<
[->+>>>+<<<<]>>>>[-<<<<+>>>>]<<<<
>
[
>>[-]>>[-]+
<<<<<
[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<<
>>
[->->+>++<<<]>>[-<<+>>]<<<<
>>>
[->>>.<<<]
>>
[->>.<<]
>>>.
<<<<<<+<-
]
<
[->>>>>>.<<<<<<]>>>>>>>.>.
Try it, it works: http://koti.mbnet.fi/villes/php/bf.php
The number of '+' signs on the first line is the number of lines you need.
We know that the program has the same start and end point, that is we display a single O
The first thing that must be done is to create a function that can print one O and from there it is easy to implement something that can print N O's. Pseudocode to follow:
function generateOh()
{
return "O";
}
So to print a tree we need a loop like so:
function generateTree(numberOfLevels, ohsToAddPerLevel)
{
treeOutput = generateOh() //Start
ohsThisLevel = 1
while i < numberOfLevels
treeOutput += \n //don't forget the new line
ohsThisLevel+= ohsToAddPerLevel
for j < ohsThisLevel
treeOutput += generateOh()
i++
treeOutput += \n
treeOutput += generateOh() //End
}
The above code will produce output like follows:
O
OOO
OOOOO
OOOOOOO
O
The remainder is for you to center it appropriately.

Categories