Struggles with nested for-loop - java

I am having problems with my code.
The goal with my code is for a user to enter a number which is then used to form
a multiplication-table. For example, if the user enters the number 4, the program is supposed to print following:**
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
This is my current code. Thankful for any kind of help!
import java.util.Scanner;
public class MultiplicationTable {
public static void main (String[] arg) {
Scanner gt = new Scanner(System.in);
System.out.println("Enter a number for multiplication: ");
int N = gt.nextInt();
for(int i = 1; i < N; i++) {
for(int j = 1; j < N; j++);
int product = i * j;
System.out.print(i +" * " +j +" = " +product );
System.out.println();
}
}
}

There are two tiny errors in your code, otherwise you are good to go.
for(int i = 1; i < N; i++) {
for(int j = 1; j < i; j++); //<-- remove this semicolon
{ // <-- use curly braces here for the loop statements
int product = i * j;
System.out.print(i +" * " +j +" = " +product+" "); //<--add an additional space at the end
}
System.out.println();
}

To get that pyramidal structure, you should change the second loop limit to i :
for(int j = 1; j < i; j++)
And remove the semicolon at the end of the loop.

Related

Printing spaces to align numbers according to my pyramid pattern

It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.

Creating N by N diagonal matrix using basic logic

I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0
Currently I have this method:
public static void drawMatrix(){
for (int line = 0; line < N; line++){
for (int j = 0; j < N; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.
j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:
if (j > line) {
System.out.print((N-line+j)%N + " ");
} else {
System.out.print((line-j+N)%N + " ");
}
Demo.
You can also rewrite it without an if using a conditional expression:
int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");
Demo.
A little change in your code works
public static void drawMatrix() {
for(int line = 0; line < N; line++) {
for(int j = 0; j < N; j++) {
System.out.print(Math.abs(line - j) + " ");
}
System.out.println();
}
}
I would do something like :
int n=6;
for(int row=0;row<n;row++)
{
for(int col = 0;col<n;col++)
{
System.out.print(abs(col-row) +" ");
}
System.out.println();
}
assuming you can use abs().
I hoped that help your purpose.
This also works :
public static void main(String[] args) {
int N = 6;
int column = 0;
for (int row = 0; row < N; row++) {
for (column = row; column >= 0; column--) //prints till row number reaches 0
System.out.print(column + " ");
for (column = 1; column < N - row; column++)//from 1 to N-row
System.out.print(column + " ");
System.out.println();
}
}

Java: Shuffling Cards in a Deck using Arrays

I am trying to implement a Perfect Shuffle method where it will split a deck into 2 and then interweave the cards so you have one from each deck being placed into the new deck. When I try to run my current program, the output I would get is:
Results of 3 consecutive perfect shuffles:
1: 0 4 1 5 2 6 3
2: 0 2 4 6 1 3 5
3: 0 1 2 3 4 5 6
I do not understand why I get 0 as my first value for each time I shuffle the deck. Can anyone tell me what I am doing wrong? This is my code:
class Ideone {
/**
* The number of consecutive shuffle steps to be performed in each call
* to each sorting procedure.
*/
private static final int SHUFFLE_COUNT = 3;
/**
* The number of values to shuffle.
*/
private static final int VALUE_COUNT = 7;
/**
* Tests shuffling methods.
* #param args is not used.
*/
public static void main(String[] args) {
System.out.println("Results of " + SHUFFLE_COUNT +
" consecutive perfect shuffles:");
int[] values1 = new int[VALUE_COUNT];
for (int i = 0; i < values1.length; i++) {
values1[i] = i;
}
for (int j = 1; j <= SHUFFLE_COUNT; j++) {
perfectShuffle(values1);
System.out.print(" " + j + ":");
for (int k = 0; k < values1.length; k++) {
System.out.print(" " + values1[k]);
}
System.out.println();
}
System.out.println();
}
public static void perfectShuffle(int[] values) {
int[] temp = new int[values.length];
int halfway = (values.length +1)/2;
int position = 0;
for (int j = 0 ; j < halfway; j++)
{
temp[position] = values[j];
position +=2;
}
position = 1;
for (int k = halfway; k < values.length; k++)
{
temp[position] = values[k];
position +=2;
}
for (int k = 0; k < values.length; k++)
values[k] = temp[k];
}
}
array index begin at 0 and not 1.
for (int i = 0; i < values1.length; i++) {
values1[i] = i;
}
you are copying 0 in values1 in this for loop in your main method which you then pass to perfectShuffle
You fill the "deck" starting at 0 and then shuffle, but your shuffle always puts the "0" card first so it never really gets shuffled in. You can see the same thing with the #1 using:
for (int i = 1; i < values1.length+1; i++) {
values1[i-1] = i;
}
Also, with an even number of cards, your last card will never change either.

Java using for-loop to produce series of numbers

I am trying to write a collection of for-loops that produce the following series of numbers below. I am trying to accommodate my loops to print each series on the same line, with spaces between each term. I am new to java and got really confused on how exactly I can accomplish it. On the right side are the digits I am increasing the counting by.
1. 4 5 6 7 8 9 10 (+1)
2. 6 5 4 3 2 1 (-1)
3. 2 4 6 8 10 12 14 16 (+2)
4. 19 17 15 13 11 9 7 5 (-2)
5. 7 15 23 31 39 (+8)
6. 2 4 8 16 32 64 (*2)
Here is the code the way I tried to accomplish it. I got the first row to work but I'm wondering weather there's an easy way I can create the rest of them without re-duplicating the program.
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run()
{
{
for(int row = 1; row < 2; row++)
{
print(" " + row + ". ");
for (int col = 4; col < 11; col++)
{
print(row*col + " ");
} //col values
println( );
} //row values
}
}
}
I am new to java and right now going over for-loops and trying to accomplish this in for-loop. If someone could help me out, I would really appreciate it.
Thank you!
Edit:
Here is what happens when I increase the number of rows.
Edit:
Here is the solution of what I had tried accomplishing. Thanks to everyone who helped me.
import acm.program.*;
public class ppLoop extends ConsoleProgram
{
public void run()
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
print(i + ". "); // print row number 1
for (int j = 4; j < 11; j++) // loop for row 1
{
print(j + " ");
}
println( );
print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
print(j + " ");
}
println();
print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
print(j + " ");
}
println();
print((i + 3) + ". ");
for (int j = 19; j > 4; j = j - 2) // loop for row 4
{
print(j + " ");
}
println();
print((i + 4) + ". ");
for (int j = 7; j < 40; j = j + 8) // loop for row 5
{
print(j + " ");
}
println();
print((i + 5) + ". ");
for (int j = 2; j < 65; j = j * 2) // loop for row 6
{
print(j + " ");
}
println();
}
} //close outer loop
} //close public run
} //close console program
You can perform this program with a series of nested loops. I have done the first three rows. I took out your package and used a main method. Also, your indentation was very confusing. Since your increment changes each line, I don't know of a way to make it any shorter than this using for loops.
public class ppLoop{
public static void main(String[] args)
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
System.out.print(i + ". "); // print row number
// you can use the same variable for each inner loop
for (int j = 4; j < 11; j++) // loop for row 1
{
System.out.print(j + " ");
}
System.out.println( );
System.out.print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
System.out.print(j + " ");
}
System.out.println();
System.out.print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
System.out.print(j + " ");
}
}
}
}
}
You could create a method that takes:
1. A start number
2. What math operation to perform (add, subtract, or multiply)
3. What number to increment/decrement or multiply by
4. An end number
It would look similar to this:
public void formattedFor(int startNum, String operation, int num, int endNum) {
if (operation.equals("add")) {
for (int i = startNum; i < endNum; i += num) {
System.out.print(i + " ");
}
}
if (operation.equals("sub")) {
for (int i = startNum; i > endNum; i -= num) {
System.out.print(i + " ");
}
}
else if (operation.equals("mult")) {
for (int i = startNum; i < endNum; i *= num) {
System.out.print(i + " ");
}
}
System.out.println( );
}
If I'm understanding the problem, you want to print six series that each start with a different number and increment/decrement that number by some value. Since I see no relationship between the initial value and the increment/decrement, you're going to have to write six separate for loops.
If you're absolutely averse to this, you can store your initial values, your increments/decrements, and your final values in an array and iterate through them using a for loop, an if statement (to deal with the multiplication) and a while loop. The array would look like this:
int[][] values = new int[][] {
{4, 6, 2, 19, 7, 2},
{1, -1, 2, -2, 8, 2},
{10, 1, 16, 5, 39, 64}
};
I could write up the source based on this, but it's not what you asked for.
I strongly suspect that, if this is a homework assignment and you've modified the problem, there's something you've failed to understand about the problem itself. If this is meant to have an simple solution that uses for loops, there should probably be some logic that binds the rows together, unless you're allowed to use arrays/while loops/for loops/objects and methods.
On another note, you should format your code differently. It's somewhat difficult to read right now. In general, indent things that happen inside loops, classes, or functions. For example:
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run() {
for(int row = 1; row < 2; row++) {
print(" " + row + ". ");
for (int col = 4; col < 11; col++) {
print(row*col + " ");
} //col values
println( );
} //row values
}
}

How to display the numbers

I'm new to coding with Java and I'm having trouble writing this program.
User enters an integer from 0 to 9 and a pyramid is displayed. For ex:
User input: 5
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
This is all I have thus far (I'm truly stumped)
import static java.lang.System.*;
import java.util.Scanner'
import java.util.*;
public class pyramid
{
public pyramid()
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++)
{
for (int j = 0; j < num - 1; j++)
{
System.out.println(" ");
}
}
}
}
Any help is welcome and appreciated. Thanks!
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
pyramid();
}
public static void pyramid() {
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++) {
for (int j = 0; j < num - i; j++) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.printf("%d ", j);
}
for (int j = 2; j <= i; ++j) {
System.out.printf("%d ", j);
}
System.out.println();
}
}
}
Start tabulating what you know, to find a pattern. Say you have height 3:
······_1
···_2 _1 _2
_3 _2 _1 _2 _3
Where · is a space for alignment purposes, _ a space reserved for the second digit.
Row 0 1 2
Spaces in front 6 3 0 (3 * (num - i - 1))
So you want to loop j to print that number of spaces, then make another loop (not inside j, but after it) to print the descending numbers to 1, then another loop to print ascending numbers back to i+1. Using System.out.printf with format %2d will print the _ space on single-digit numbers.

Categories