I've recently been teaching myself Java and I made a piece of code to produce Pascal's triangle. However, I can't get it to print out properly in a triangle. I can't figure out how to take into account numbers with multiple digits. Here's what I have so far:
public class Pas{
public static void main(String[] args){
pas(20);
}
public static void pas(int rows){
for(int i = 0; i < rows; i++){
String spaces = "";
int counter = (rows + 30)/2 - i;
for(int f = counter; f > 0; f --){
spaces += " ";
}
System.out.print(spaces);
for(int j = 0; j <= i; j++){
System.out.print( ncr(i, j) + " ");
}
System.out.println();
}
}
public static long ncr(int n, int r){
return fact(n) / (fact(r) * fact(n - r));
}
public static long fact(int n){
long ans = 1;
for(int i = 2; i <= n; i++){
ans *= i;
}
return ans;
}
Please keep in mind I'm a complete beginner and have never had any actual instruction. Everything I know is from the internet and messing around in Eclipse.
So the problem you're having is with spacing.
You are using always one space after a number, which is a problem because one number can be of length 1 - i.e: 1,2,3,4,5,6,7,8,9 - and another can be of length 5 - i.e. 31824. Because of that your triangle is wider on the right side.
To change that you have to reserve equal space for all your numbers - so if your biggest number is 184756 then for every number you print you have to reserve place for 6 digits and 1 empty space after them.
Also your initial spacing is not related to the number of rows, which in general can generate problems (if you would like to make triangle bigger than 30 - your current constant).
So there are two places where I would suggest changes:
First is this (1):
int counter = (rows + 30)/2 - i;
Here 30 is a constant that works for your 20 dimention triangle, but it's not elegant and won't work for bigger triangles. So I would suggest something like this (2):
int counter = (maxNumberLength*(numberOfRows - i))/2;
maxNumberLength is the maximum length the numbers in your triangle can get. How to calculate it? I'have estimated like that (3):
Math.pow(2d, numberOfRows.doubleValue());
This power will always be bigger than the biggest value in the triangle, but not by much. You can do it differently - it's first that came to my mind.
So back to (2)... the numberOfRows is the number of rows in the triangle. You substract i before multiplying to get the initial space maximumNumberLength/2 smaller in every row (so that it has a left slope).
The second thing that I would suggest changing is this:
System.out.print( ncr(i, j) + " ");
That's the most important part as you always add 1 space. If maximum number length is 6, then you should add 6 spaces after 1, 5 spaces after 20 and so on. Thats why I suggest creating a method that would return you the number of spaces you need (4):
private String spaces(final Long number, final int maxNumberLength)
{
StringBuilder spaces = new StringBuilder("");
for (int i = 0; i<maxNumberLength - number.toString().length(); i++)
{
spaces.append(" ");
}
return spaces.toString();
}
In (4) you take number as first param (that's the number that is to be followed by spaces) and maxNumberLength from (3). This way all of your numbers would take the same amount of spaces in the output. I build the spaces with StringBuilder which is more effective for String concatenation.
So that's it - two changes and it should work.
I attach my full code so if you need you can test it:
public class TraingleTest
{
private final BufferedReader input;
private Integer numberOfRows;
public static void main(String args[])
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
new TraingleTest(input).run();
}
private TraingleTest(final BufferedReader input)
{
this.input = input;
}
private void run()
{
boolean validNumber = false;
System.out.print("Please enter number of rows for Pascals Triangle: ");
do
{
String usersInput = readUserInput();
validNumber = validateInput(usersInput);
} while (!validNumber);
makeTriangle();
}
private String readUserInput()
{
try
{
return input.readLine();
}
catch (final IOException e)
{
System.out.print("Error while reading input. Please try one more time: ");
return "";
}
}
private boolean validateInput(final String input)
{
try
{
Integer inputValue = Integer.parseInt(input);
if (inputValue > 2 && inputValue < 22)
{
numberOfRows = inputValue;
return true;
}
System.out.print("Value must be an integer between 3 and 21. Please insert valid number: ");
return false;
}
catch (final Exception e)
{
System.out.print("Error while parsing input. Please insert valid number: ");
}
return false;
}
private void makeTriangle()
{
int maxNumberLength = Double.valueOf(Math.pow(2d, numberOfRows.doubleValue())).toString().length();
for(int i = 0; i < numberOfRows; i++){
String spaces = "";
int counter = (maxNumberLength*(numberOfRows - i))/2;
for(int f = counter; f > 0; f --)
{
spaces += " ";
}
System.out.print(spaces);
for(int j = 0; j <= i; j++)
{
long number = ncr(i, j);
System.out.print(number + spaces(number, maxNumberLength));
}
System.out.println();
}
}
private String spaces(final Long number, final int maxNumberLength)
{
StringBuilder spaces = new StringBuilder("");
for (int i = 0; i<maxNumberLength - number.toString().length(); i++)
{
spaces.append(" ");
}
return spaces.toString();
}
public long ncr(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}
public long fact(int n)
{
long ans = 1;
for(int i = 2; i <= n; i++)
{
ans *= i;
}
return ans;
}
}
// I have not inputted the rows you can just give an input statement and input no of rows
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for(int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j = 0; j <= i; j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
this code will help you
int rows = 10;
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
The simplest thing to is to decree that every number you output will use a set number of characters, and to add extra blanks if necessary when outputting each number. For example, you can decide that each number will take 4 characters (if all the numbers are 9999 or less--actually, with Pascal's triangle with 20 rows, you'll need at least 5 characters). Then you'll need to adjust the number of spaces you print out in each row of the triangle.
To convert a number to a 4-character string where the number is pushed over to the right of the 4-character "box", and you add blanks on the left if necessary, use String.format:
String output = String.format("%4d", number);
If you want the number to be at the left of the "box",
String output = String.format("%-4d", number);
If you want the number to be centered in the "box", this is harder. Here's a method that will pad a string on both sides with blanks, making the padding as close to equal on both sides as possible:
public static String center(int desiredLength, String input) {
if (input.length() >= desiredLength) {
return input;
}
int leftPadding = (desiredLength - input.length()) / 2;
int rightPadding = desiredLength - input.length() - leftPadding;
StringBuilder result = new StringBuilder();
for (int i = 0; i < leftPadding; i++) {
result.append(' ');
}
result.append(input);
for (int i = 0; i < rightPadding; i++) {
result.append(' ');
}
return result.toString();
}
and then you could say
System.out.print(center(4, Integer.toString(number)));
or, if number is a long,
System.out.print(center(4, Long.toString(number)));
(P.S. Instead of StringBuilder, you could declare result to be a String and use things like result += " " like you did in your original question. That would work just as well, except maybe a few nanoseconds slower.)
package myjavapractice;
import java.util.Arrays;
import java.util.Scanner;
public class pascaltriangle
{
public static void main(String args[]) {
int i;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] pascal=new int[n][];
for(i=0;i<n;i++)
{
pascal[i]=new int[i+1];
}
pascal[0][0]=pascal[1][0]=pascal[1][1]=1;
for(int j=2;j<n;j++) {
pascal[j]=getNextRow(pascal[j]);
}
//print
for(int k=0;k<n;k++)
{
System.out.println(Arrays.toString(pascal[k]));
}
}
static int[] getNextRow(int[] p)
{
int[] current = new int[p.length];//row
System.out.println("length "+p.length);
current[0]=current[current.length-1]=1;//colmn
for(int m=1;m<current.length-1;m++)
{
current[m]=p[m]+p[m-1];
System.out.println("pof m is"+p[m]);
}``
return current;
}
}
Related
Example:
If i give a number 12345 , i should get an answer like 15243
in the same way if it is 123456 , i should get 162534
i have already tried getting the first value and appending the last value using reverse technique
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345";
String val = str;
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()/2; i++) {
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0){
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString(n);
}
}
System.out.println(num);
}
}
i should get the result if they give even number or odd number
Without doing what is presumably homework for you, imagine you have a loop in which there are two integer variables a and b. Variables a and b are string indexes.
You are taking characters from the string at positions a,b,a,b,a,b etc.
BUT the values of a and b need to change for each iteration. If the length of the String is n, a will follow the sequence 0,1,2,3... and b will follow the sequence (n-1),(n-2),(n-3) etc
The loop should continue while a < b.
This is my solution for your exercise:
Method parameter "A" is Integer number you want to parse.
First you create Char Array from given number and then iterate through it. If i%2 == 0 it means that you take number from beginning otherwise from the end
public static int algorithm(int A) {
StringBuilder shuffleNumber = new StringBuilder();
char[] numbersArray = Integer.toString(A).toCharArray();
for (int i = 0; i < numbersArray.length; i++) {
if (i % 2 == 0)
shuffleNumber.append(numbersArray[i / 2]);
else
shuffleNumber.append(numbersArray[numbersArray.length - i / 2 - 1]);
}
return Integer.parseInt(shuffleNumber.toString());
}
If you want a solution without string methods, there is a not so complicated one:
public static void main(String[] args) throws IOException {
String str = "1234567";
int len = str.length();
int num=0;
char a;
for(int i = 0; i < len / 2; i++) {
a = str.charAt(i);
num = num * 10 + Character.getNumericValue(a);
a = str.charAt(len -1 - i);
num = num * 10 + Character.getNumericValue(a);
}
if (len % 2 == 1) {
a = str.charAt(str.length() / 2);
num = num * 10 + Character.getNumericValue(a);
}
System.out.println(num);
}
will print
1726354
Check the last if that takes care the case of odd number of digits in the number.
public class MyFirstJavaProgram {
public static void main(String []args) {
String str = "12345678";
int val = str.length();
char a;
int num=0;
int d=0;
int n;
for(int i=0; i<=str.length()-2; i++)
{
a = str.charAt(i);
num = num*10+Character.getNumericValue(a);
if(Integer.parseInt(str)!=0)
{
d=Integer.parseInt(str)%10;
num = num*10+d;
n=Integer.parseInt(str)/10;
str = Integer.toString( n );
}
}
if(val%2!=0)
{
num = num*10+Integer.parseInt(str)%10;
System.out.println(num);
}
else{System.out.println(num);}
}
}
this is working for my question... Thanks all
Following is my solution -
public static void solution(String s) {
StringBuffer st = new StringBuffer();
for (int i = 0; i < s.length() / 2; i++) {
st.append(s.charAt(i));
st.append(s.charAt(s.length() - 1 - i)); // appending characters from last
}
if (s.length() % 2 != 0) {
st.append(s.charAt(s.length() / 2));
}
System.out.println(Integer.parseInt(st.toString()));
}
my logic is to keep appending first and last character to new string till i < s.length/2.
If string is of odd length , it means only last character is remaining, append it to your resultant string.
Else , no character is left and you have your complete string.
I was trying to solve the Maximum Integer Value problem form Geeksforgeeks.
The problem states the following:
Given a string S of digits(0-9), your task is to find the maximum value that can be obtained from the string by putting either '*' or '+' operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
Input:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input denoting the string.
Output:
For each testcase, print the maximum value obtained.
this is what I did:
class GFG
{
public static void sort(int[] numbers)
{
int n = numbers.length;
for (int i = 1; i < n; ++i)
{
int key = numbers[i];
int j = i - 1;
while (j >= 0 && numbers[j] > key)
{
numbers[j + 1] = numbers[j];
j = j -1 ;
}
numbers[j + 1] = key;
}
System.out.println(numbers.length - 1);
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
int [] maxNum;
for(int i = 0; i< testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
maxNum = new int [cNumbers.length];
for(int j = 0; j + 1 < cNumbers.length; j++)
{
int sum = 0;
int mult = 0;
sum = cNumbers[j] + cNumbers[j + 1];
mult = cNumbers[j] * cNumbers[j + 1];
int maxNumber = Math.max(sum, mult);
maxNum[i] = maxNumber;
}
sort(maxNum);
}
}
}
an example of Input:
2
01230
891
My Output:
-1
4
Correct Output:
9
73
What is wrong with my code?!
Just quick glance it would seem if your digit is less than two it should be added. 2 or larger should get multiplied. Not at a PC to test though.
The idea is to put the operators alternatively and choose the maximum results.
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
int max = 0;
for (int j = 0; j + 1 < numbers.length(); j++) {
int next = Integer.parseInt(numbers.substring(j, j+1));
if (max + next > max * next)
max = max + next;
else
max = max * next;
}
System.out.println(max);
}
sc.close();
}
}
After the execution of
int testCases = sc.nextInt();
the buffer contains a new line character. So when executing the line
String numbers = sc.nextLine();
it read '\n' into numbers, so you got -1 as the first output.
Also you need to convert character to Integer before using it any arithmetic operations.
sum = cNumbers[j] + cNumbers[j+1];
mult = cNumbers[j] * cNumbers[j+1];
So the above code will give you wrong results.
I tried the following sample and worked.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputAsString = sc.nextLine();
int testCases = Integer.parseInt(inputAsString);
int maxNumber = 0;
for (int i = 0; i < testCases; i++) {
String numbers = sc.nextLine();
if(!numbers.matches("\\d+")){
System.out.println("Only numeric values are expected.");
continue;
}
char[] cNumbers = numbers.toCharArray();
int sum = 0;
int mult = 1;
for (int j = 0; j < cNumbers.length; j++) {
int nextNumber = Character.getNumericValue(cNumbers[j]);
sum = sum + nextNumber;
mult = mult * nextNumber;
maxNumber = mult > sum ? mult : sum;
sum = maxNumber;
mult = maxNumber;
}
System.out.println(maxNumber);
}
sc.close();
}
I read your description and what you do is wrong. please read question carefully specially the example in reference site.
as mentioned in comments by moilejter you use sc.nextInt() which doesn't read '\n' and make problem. the next sc.nextLine() will read only a empty string and your program throw exception.
Second problem is that you must calculate max continuously and you don't need an int array (you calculate max result of operation between two successive number and save them in an array which is not correspond to max integer value. you only find max between each two digit but not max of operation on all digit).
Third problem is that you use character as numbers which is made incorrect result. (you must convert them to integer)
So there is a code that works for your output:
public class GFG
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = Integer.valueOf(sc.nextLine());
for (int i = 0; i < testCases; i++)
{
String numbers = sc.nextLine();
char[] cNumbers = numbers.toCharArray();
long maxUntilNow = cNumbers[0] - '0';
for (int j = 1; j < cNumbers.length; j++)
{
int numberOfThisPlace = cNumbers[j] - '0';
maxUntilNow = Math.max(maxUntilNow + numberOfThisPlace,
maxUntilNow * numberOfThisPlace);
}
System.out.println(maxUntilNow);
}
}
}
I hope this is what you want.
As per the problem statement, we need to obtain maximum value from the string by putting either * or + operators in between the digits while traversing from left to right of the string and picking up a single digit at a time.
So, this can be solved in O(n) without using any sorting algorithm.
The simple logic behind the solution is whenever you find "0" or "1" in any of the operands use "+" and the rest of the places use "*".
Here is my solution which got successfully submitted:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int T = Integer.parseInt(scan.nextLine());
while(T-- > 0) {
String str = scan.nextLine();
maxValue(str);
}
}
static void maxValue(String str) {
long maxNumber = 0;
for(int i = 0; i < str.length(); i++) {
int n = Character.getNumericValue(str.charAt(i));
if (maxNumber == 0 || maxNumber == 1 ||
n == 0 || n == 1) {
maxNumber += n;
} else {
maxNumber *= n;
}
}
System.out.println(maxNumber);
}
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}
}
All numbers reverse well but I have problem with reversing numbers that end with zero e.g numbers like 10000 instead of reversing result being 00001 it gives the result as 1 which is not what the question wants is there a way to use integers or string will be the best and easier approach? Thank you
Try the reversing of string concept
String s ="10000";
String n= "";
for(int i=0; i<s.length(); i++){
n = s.charAt(i) + n;
}
System.out.println(n);
You can create a variable length, and use System.out.printf to format output.
With %0 + length + d, it will add 0 on the left to make the output have this length.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
for (int i = 0; i < 4; i++)
{
int number = input.nextInt();
int reverse = 0;
int length = String.valueOf(number).length();
while (number != 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
System.out.printf("%0" + length + "d", reverse);
}
}
}
You could also solve it with a StringBuilder. It already has a method called reverse:
public String reverseInput(int number) {
String s = Integer.toString(number);
return new StringBuilder(s).reverse().toString();
}
You can't have a Integer beginning with 0 except 0 itself. So you will have to work with Strings or other datastructures.
I'm new in Java and I try to find the sum of first three digits in int number.
I have a number 123456 I want to find the sum of first three digits 123 and then find sum of last three digits 456 and then compare it. I can't understand how to do this. I code next:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int length = (int) Math.ceil(Math.log10(number));
for (int i = 1; i <= 3; i++) {
System.out.println(i);
}
System.out.println(length);
System.out.println(number);
}
I think that I shoud to use for loop, but I'm not sure. I know how to count the length of a number. But how to how to find the sum of the first three numbers and last three?
Assuming your length is constant (6):
String first = (""+number).substring(0, 3);
String second = (""+number).substring(3, 6);
int firstSum = 0;
int secondSum = 0;
for (int x = 0; x < first.length; x++)
firstSum += Integer.parseInt(first.charAt(x)+"");
for (int x = 0; x < second.length; x++)
secondSum += Integer.parseInt(second.charAt(x)+"");
System.out.println("Sum of first 3: " + firstSum);
System.out.println("Sum of second 3: " + secondSum);
Read the String API- it has a lot of useful methods. For small programs like this, it's usually pretty easy to convert to String, use String methods, then parse back to int.
EDIT: Andy Turner and Jeremy Kato informed me about Character.getNumericValue(). Thus, the statement:
firstSum += Integer.parseInt(first.charAt(x)+"");
Could be changed to:
firstSum += Character.getNumericValue(first.charAt(x));
Likewise for secondSum.
First, probably should correct your spelling of length - though maybe not, because you don't really need that variable to do this.
What your code should do to make this easier for you is to not convert the input into an int immediately. You'll first want to split the input string into two pieces, then take the two numbers and sum them up with a loop.
Here's my idea of what I'd do:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
String input = scanner.nextLine();
String firstHalf = input.substring(0, 3); // note that depending on how
// many digits you want to change, these numbers must change as well.
String secondHalf = input.substring(3);
int sum1 = 0;
int sum2 = 0;
// don't forget: start at 0, not 1!
for(int i = 0; i<=3; i++){
sum1 += Character.getNumericValue(firstHalf.charAt(i));
sum2 += Character.getNumericValue(secondHalf.charAt(i));
// this call to the Character class converts a character to an int.
}
System.out.println(sum1);
System.out.println(sum2);
}
Just note that this code is made to work with your input being 6 characters, and it assumes they're going to be numbers. It'll crash if you enter too few characters in or if you put letters in, but you can always worry about that later.
Here's a straightforward way of doing it, making the assumption that your integer has an even number of digits...
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int[] count = new int[2];
for (int i = 0; i < s.length(); i++) {
int digit = Integer.parseInt(s.substring(i, i + 1));
int countIndex = (int)Math.floor(i * 2 / s.length());
count[countIndex] += digit;
}
int half = s.length() / 2;
System.out.println("First Sum of " + s.substring(0, half) + ": " + count[0]);
System.out.println("Second Sum of " + s.substring(half) + ": " + count[1]);
}
}
Alternate Method
Here's another way of doing it without using the arrays above, and actually simplified the logic by abstracting the sum to a method.
public class Test {
public static void main(String[] args) {
// Makes the assumption that the input integer contains an even number of digits.
int x = 123456;
String s = Integer.toString(x);
int half = s.length() / 2;
String firstHalf = s.substring(0, half);
String secondHalf = s.substring(half);
System.out.println(firstHalf);
System.out.println(secondHalf);
int sum1 = sumString(firstHalf);
int sum2 = sumString(secondHalf);
System.out.println("Sum 1: " + sum1);
System.out.println("Sum 2: " + sum2);
}
private static int sumString(String s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += Integer.parseInt(s.substring(i, i + 1));
}
return sum;
}
}
Here is an alternative solution which doesn't use Strings or arrays:
public static void main(String args[]){
int num=123456;
int second = 0;
int first = 0;
second = addLastThree(num);
num /= 1000;
first = addLastThree(num);
System.out.println("first -- > " + first);
System.out.println("second -- > " + second);
}
static int addLastThree(int num){
int sum = 0;
for (int i =0; i<3; i++){
sum += (num/Math.pow(10,i)) % 10;
}
return sum;
}
you can try this code and every line was explained in comments.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
int number = scanner.nextInt();
int n=number; //duplicating the value for the reference.
int l = (int) Math.log10(number) + 1; //Length of the number
int half = l/2; //to find half length of the number to sum first and last digits seperately.
int last_Sum = 0; //to store sum of last digits
int first_Sum = 0; //to store sum of first digits
for(int i=0; i<half && number>0; i++){ //to sum last digits
last_Sum = last_Sum + number%10;
number = number/10;
}for(int i=0; i<half && number>0; i++){ //to sum first digits
first_Sum = first_Sum + number%10;
number = number/10;
}
System.out.println("Length of the number "+l);
System.out.println("Number is "+n);
System.out.println("Sum of last digits "+last_Sum);
System.out.println("Sum of first digits "+first_Sum);}}
This is a homework question so I would like help, not an answer.
I'm trying to create 2 triangles out of numbers based on a number entered by the user.
"Enter a number between 2-9: "3"
1
12
123
1
21
321
IE2:
"Enter a number between 2-9: "5"
1
12
123
1234
12345
1
21
321
4321
54321
I have been able to get the first triangle complete. But when I add my nested loop it messes up my first triangle with the numbers developed from the nested loop. It also puts all the numbers in a straight vertical line. I've tried variations for different nest loops and even tried messing with a StringBuilder, but was still unsuccessful.
Here's what I have in code so far:
import java.util.Scanner;
public class NestedLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a Number between 2-9: ");
int width = input.nextInt();
String r = "";
for (int i = 1; i <= width; i++)
{
r = r + i;
System.out.println(r);
}
}
}
Again, I'm looking for help/understanding and not just an answer.
There are two aspects the 2nd part of the question.
You need to generate strings with the numbers in the reverse order:
You could do this by adding the numbers at the other end.
You could do this by reversing the strings.
You need to arrange that there are spaces to the left.
You could do this by adding the required number of spaces to the left end of the string.
You could do this by using the System.out.format(...) with a template that right aligns the string in a field with the required number of characters. (OK, that's a bit too obscure ...)
Or, you can build the string in a character array or string builder rather than using string concatenation.
The "trick" is to figure out what strategy you are going to use ... before you start cutting code.
try
int width = 5;
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// print numbers from 1 to current line number
for (int n = 1; n <= line; n++) {
System.out.print(n);
}
// end of line
System.out.println();
}
// add empty line between triangles
System.out.println();
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// printing padding spaces, number of spaces = with - line number
int nSpaces = width - line;
for (int i = 0; i < nSpaces; i++) {
System.out.print(" ");
}
// print numbers from number of current line to 1
for (int n = line; n >= 1; n--) {
System.out.print(n);
}
// end of line
System.out.println();
}
Can you just add another loop after your first loop like
String r = "";
String space = "";
for (int i = width; i >= 1; i--)
{
r = r + i;
System.out.println(r);
}
Try it. not yet tested
You need to use a queue.
eg. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html
Enque the numbers till you reach the max, and then start dequing them.
And while you dequeue, you need to apply the reverse
Queue<String> q = new LinkedList<String>();
for (int i = 1; i <= width; i++)
{
r = r + i;
q.add(r);
System.out.println(r);
}
while(!q.isEmpty()){
String j = q.remove();
//reverse j
System.out.println(reverse(j));
}
I leave the reversing part for you to do :)
public static void main(String[] args)
{
int n = 5;
for(int i=1; i<=n; i++)
{
for (int j=(n*2), k=n; j>1; j--)
{
if (k <= i)
{
System.out.print(k);
}
else
{
System.out.print('*');
}
k += (j)-1 > n ? -1 : 1;
}
System.out.println();
}
}
Just tried to implement in scala. Ignore if you don't like it..:-)
class Triangle extends App
{
val width = Console.readInt()
if (width < 2 || width > 9)
{
throw new RuntimeException()
}
var i, j = 1;
for (i <- 1 to width)
{
for (j <- 1 to i)
{
print(j)
}
print("\n")
}
for (i <- 1 to width)
{
for (dummy <- 1 to width-i)
{
print(" ")
}
for (j <- i to 1 by -1)
{
print(j)
}
print("\n")
}
}