Reversing the order of displayed numbers in a nested loop - java

I've been doing some solo exercises to prepare for starting college next year and this one is stumping. The output is current
1
12
123
1234
and I want to get it to
1
21
321
4321
Here's the code I've been playing with for a while.
Scanner stdIn = new Scanner (System.in);
int n;
do
{
System.out.println("Please enter the value number: ");
n = stdIn.nextInt();
}
while ( n < 1 || n > 9);
for (int i = 1; i <= n; i++)
{
for (int k = i; k < n ; k++)
{
System.out.print(" ");
}
for (int j = 1; j <= i; j++)
{
System.out.print(j);
}
System.out.println();
}
stdIn.close();

One simple way is to make the second for loop start from i, and go down to 1:
for (int j = i; j >= 1; j--)
{
System.out.print(j);
}
Alternatively, print i - j + 1:
for (int j = 1; j <= i; j++)
{
System.out.print(i - j + 1);
}
Also, you should not close the Scanner, which is "connected to" System.in You didn't open System.in, so don't close it.

You can convert the numbers to String and print its reverse:
Scanner stdIn = new Scanner (System.in);
int n;
String str;
do
{
System.out.println("Please enter the value number: ");
n = stdIn.nextInt();
}
while ( n < 1 || n > 9);
for (int i = 1; i <= n; i++)
{
str = "";
for (int k = i; k < n ; k++)
{
System.out.print(" ");
}
for (int j = 1; j <= i; j++)
{
str = str + j;
}
System.out.println(new StringBuffer(str).reverse().toString());
}
stdIn.close();

Related

Making a specific pattern in Java

How do I make this pattern using a input from the user?
input=3
(1st line)+
(2nd line)--
(third line)+++
I have tried using the for loops but just couldn't figure out how to get it to work.
First, we can judge the parity of a value by taking the remainder of 2
get the input value;
loop i = 1 & i <= input value:
when i is odd output char is "+"
when i is even output char is "-"
loop j = 0 & j < i
print i times output char
codeļ¼š
int inputVal = 3;
for (int i = 1; i <= inputVal; i++) {
String outputTag = i % 2 == 0 ? "-" : "+";
for (int j = 0; j < i; j++) {
System.out.print(outputTag);
}
System.out.println();
}
Scanner inp = new Scanner(System.in);
System.out.println("Enter Input");
int input = inp.nextInt();
for (int i = 0; i < input; i++) {
String symbol = i%2 == 0 ? '-' : '+';
for (int j = 0; j < i; j++) {
System.out.print(symbol);
}
System.out.print("line" + (i+1) + "\t");
}

I want to create a pattern of nxn in java with the help of loops

I want to create a pattern like this, why is this code wrong?
x x x x
x x x
x x
x
for any value of n( its a nxn pattern )
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = n; i <= n; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
You condition is wrong it should be i >= 0. In your case where i <= n, "i" is decremented and will never reach "stop condition".
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = n; i >= 0; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}

String,which repeats ,but not starts from the beginning in Java (diamond pattern

This is the work that i done so far:I have to print diamond pattern which always starts with uppercase from string, which repeats,but not always starts from the beginning.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
userInput = Character.toUpperCase(userInput.charAt(0)) + userInput.substring(1);
int i;
int j;
if (userInput.length() % 2 != 0) {
for(i = 1; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
} else {
for(i = 2; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
}
}
For example my input is "Peter".
So my output is:
P
Pet
Peter
Pet
P
but it must be:
P
Ete
Rpete
Rpe
T
I dont know what to change to make this work
Here's a shorter version of your code:
public static void main(String[] args) {
String userInput = "Peter";
int length = userInput.length();
int m, j, i, n = 0;
for (m = length % 2 > 0 ? 1 : 2; m < length * 2; m += 2) {
i = m < length ? m : length * 2 - m;
for (j = 0; j < length - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
char c = userInput.charAt(n++ % length);
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
}
System.out.println("");
}
}
You need some few changes:
Declare int n=0; after int j;
Always print userInput.charAt(n++ % userInput.length()) instead of charAt(j)
In order to get only the first character in line in uppercase:
char c = userInput.charAt(n++ % userInput.length());
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
Check the modulo operator.
With these changes, you'll get this output:
P
Ete
Rpete
Rpe
T
Given the fact that the input itself gets printed in a cylic manner, we can make use out of it. My proposal would be to concatenate the input string and print out the substrings which are determined by the structure of the diamond pattern.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
String concatenated = userInput;
// build up the index array
int i, cumSum = 0;
ArrayList<Integer> helperIndex = new ArrayList<>();
for(i = 1; i < userInput.length(); i += 2) {
helperIndex.add(i);
cumSum += i;
}
for(i = userInput.length(); i > 0; i -= 2) {
helperIndex.add(i);
cumSum += i;
}
int numOfWordRepitition = cumSum / userInput.length() ;
for (i = 0; i < numOfWordRepitition; i++){
concatenated += userInput;
}
// print out diamond
String substr;
int prev = helperIndex.get(0);
int next = helperIndex.get(0);
substr = concatenated.substring(0 , helperIndex.get(0));
System.out.println(Character.toUpperCase(substr.charAt(0)) + substr.substring(1));
for(i = 1; i < userInput.length(); i++){
next += helperIndex.get(i);
substr = concatenated.substring(prev , next);
substr = Character.toUpperCase(substr.charAt(0)) + substr.substring(1);
System.out.println(substr);
prev = next;
}
}

initialize only some elements of array in java

So I want to skip the first and last elements of the array to initialize. What am I doing wrong?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Here is my output:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
You need to change the if condition inside the loop like following:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
In this line:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
You are testing for the equality of values within your array. You should be comparing whether the indices you are looking at are the beginning or end of the array.
That is to say, you want to compare whether (in pseudo code):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
I have deliberately omitted the literal answer, because this looks a tiny bit like homework.
You compare the value of arr[i][j] with the value of arr[0][0]. You should instead compare i==0 && j==0 || i==m -1 && j==n -1
As your array was empty, and as you start the loop, arr[i][j] was equal to arr[0][0], skipping the first element. but for the next loop, arr[i][j] was still empty, and as you compare it to a non-initialised value, it's always true, skipping in each step
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
You don't need to check whether the array items are equal, you just want to check whether the row and column are equal to the last and first.

replace every second line of my triangle with a blank line for loops

instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this
5
555
55555
This is my code:
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print("5");
}
System.out.println();
}
you need small modification in your code and you can get what you want.
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
if(i%2==0)
System.out.print("*");
}
System.out.println();
}
check it out.
Just test for i % 2
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print(i % 2 == 0 ? "*" : " ");
}
System.out.println();
}
edit
If you want to print 5 instead or * then modify the code to use 5
Check this:
int num= 5; // 'num' denotes the number of lines
int numOfSpaces;
for(int i = 1; i <= num; i++) {
if( i%2 != 0) // checks whether the line number is odd. If odd, prints '*'
{
numOfSpaces = (num-i) / 2; // find the number of blank spaces
for(int j = 1; j <= numOfSpaces; j++) {
System.out.print(" ");
}
for(int k = 1; k <= i; k++) { // number of '*'s to be printed = current line number = i
System.out.print("*");
}
System.out.println();
}
else{
System.out.println(); // leaves every second line blank (ie.,if line number is even.)
}
}
//try this code. It may help you to achieve your output
[Check screen shot for the output of the below code][1]
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5 - i; j++)
{
System.out.print(" ");
}
for (int k = 0; k <= i; k++)
{
if(i%2!=0)
{
System.out.print(" ");
}
else{
System.out.print("* ");
}
}
System.out.println();
}
The Code below is Working now.
A simple if condition will solve your problem. Just check if the
value of i is divisible by 2. If it is true then print a
blank line. Else Print * and you are done!
* will be printed on 1st, 3rd and 5th lines.
Blank Space will be printed on 2nd and 4th lines.
public class PrintPattern{
public static void main(String []args){
int lineNo=0; // New Variable for Line Number (Can Use variable 'i' also)
for(int i = 0; i < 5; i++) {
lineNo++;
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
if(lineNo%2!=0){
for(int k = 0; k <= (i*2); k++)
System.out.print('*'); // Will print '*' (or '5') Sequence for Odd Lines - 1st, 3rd, 5th Lines
System.out.println();
}
else
System.out.println();// Will print Blank Line for Even Lines - 2nd and 4th Lines
}
}
}
Try this
for(int i = 0; i < 5; i++) {
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print("5"); //Use 5 instaed of * to draw
}
System.out.println();
System.out.println(); //This one will solve your problem
}
Output will be:
5
555
55555
5555555
555555555
I think that you can just enter one more print statement inside the loop:
for(int i = 0; i < 5; i++) {
System.out.println();
for(int j = i; j < 5; j++) {
System.out.print(" ");
}
for(int k = 0; k <= (i*2); k++) {
System.out.print("*");
}
System.out.println();
}
Output
*
***
*****
*******
*********

Categories

Resources