hi guys i am just doing some reading for myself to learn java and came across this problem and is currently stuck.
i need to print out series of number based on the input given by the user.
for example, if input = 5, the output should be as follows
#1#22#333#4444#55555
import java.util.*;
public class ex5{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for(int i=0;i<input;i++){
if(input==1){
System.out.print("#1");
}
if(input==2){
System.out.print("#1#22");
}
}
}
}
this doesnt seem to be working because this is the output i get
Please type a #:
2
#1#22#1#22
im not sure what to put inside the for loop right now and i dont think i am using the for loop here very well either...
any help guys?
for (int i=1; i<=5; i++){
System.out.print("#");
for (int j=1; j<=i; j++) System.out.print(i);
}
out
#1#22#333#4444#55555
you're going to need a nested for-loop to solve this problem.
Yeah, this isn't how you want to do it. You're going to want to build the string inside the for loop.
Start with a new string
String s = "";
As you loop, add to that string.
for(int i=1;i<=input;i++){
s += #;
for(int j=0; j<i; j++) {
s+=i;
}
}
You need to use a nested for loop.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please type a #: ");
int input = kb.nextInt();
for (int i = 1; i <= input; i++) {
System.out.print("#");
for (int k = 0; k < i; k++) {
System.out.print(i);
}
}
}
It is because you are checking for the numbers 1 and 2 in the if statement. It is hard coded to only check for these two numbers and would not work once you go past the values that you have an if statement for
What you want to do is to output the value of your iterator (in your case, i) i times (hint, you can use another loop inside the big loop) and then ad an # sign at the end of the string.
I will try to not give you any code so you can learn it yourself, but feel free to ask more questions.
You are trying to print given number - given number of times?
Then you'll need two loops for this - outer loop for iterating the number and inner - for iterating -times the given number.
It would be something like this:
for(int i = 0; i < input; ++i) {
System.out.print("#");
for(int j = 0; j < i; ++j) {
System.out.print(i);
}
}
Related
So recently a had an exam to make this simple program on java:
You enter a number, then the program needs to repeat a sequence based on the amount you entered, like this: if it was number 3 it should show 01-0011-000111, as you can see the numbers repeat in the same row, if it would be number 5 it should show: 01-0011-000111-00001111-0000011111 without the "-" symbol, I'm just putting it for you to understand better.The only thing I could do was this:
Scanner lea = new Scanner(System.in);
int number;
int counter = 1;
System.out.println("Enter a number");
number = lea.nextInt();
while(counter<=number){
System.out.print("0");System.out.print("1");
counter = counter + 1;
}
thanks in advance!
I have a feeling this is inefficient, but this is my idea:
You'd need to use 1 loop with 2 additional loops inside it. The outside loop will iterate N times (the amount the user specified), and the 2 loops inside will iterate the number of current iterations the outside loop has. One of them is for printing 0s and the other for printing 1s.
In code, it would look like so:
for(int i = 0; i < N; i++){
for(int j = 0; j <= i; j++){
System.out.print(0);
}
for(int j = 0; j <= i; j++){
System.out.print(1);
}
if(i + 1 != N) System.out.print(" ");
}
I'd rather use 1 for loop for this case with a formatted string using String.repeat
for (int i =0; i <= N; i++)
System.out.print(String.format("%s%s ","0".repeat(i),"1".repeat(i)));
I am working on completing the summer assignment for my AP Computer Science A class. The base code for the next portion is this:
public class Stars {
public static void main(String[] args) {
System.out.println("*");
System.out.println("**");
System.out.println("***");
System.out.println("****");
System.out.println("*****");
}
}
RESULT:
*
**
***
****
*****
I am supposed to rewrite the code to output the same result, using two loops as well as only two output statements that I will provide below:
System.out.print(“*”);
System.out.println();
I have found one alternative means to do so:
public class StarsLoop {
public static void main(String[] args) {
for (int i = 0; i < 1; i++)
System.out.print("*\n**\n***\n****\n*****");
}
}
Of course, though, this does not include two loops and the two given output statements as is required; however, I can't really seem to think of how I would do so. So, what is a possible way to do so?
You want to print five lines in total, each line consists of the line number star characters. Loop from one to five (inclusive), and inside that loop - loop again, this time the outer number of times printing stars. After that, print a newline. Like,
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
Of course, you could eliminate a loop by accumulating stars in a StringBuilder - and outputing that on each iteration. Like,
StringBuilder line = new StringBuilder("*");
for (int i = 0; i < 5; i++) {
System.out.println(line);
line.append("*");
}
The following code will produce the desired result:
for (int i = 1; i <= 5; i++) // Loop over each asterisks row to be printed
for(int j = 0;j < i; j++) { // Loop over the number of stars to print for the current line. It is based on the current row number
System.out.print(“*”); // Add an asterisks to the current row
}
System.out.println(); // Move to the next line
}
Could someone explain the basics behind printing simple patterns in Java?
I'll give one specific example.
I'd just like for someone to clarify what each line is doing so I get a better understanding of how this works. Any other explained examples (line by line) would also be appreciated!
public static void drawPyramidPattern() {
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++) {
System.out.print("* ");
}
System.out.println();
}
}
Printing anything or everything via a loop is just about understanding the flow of execution. In your code also, if you'll start watching the flow line by line you'll come to know that how it is working exactly.
If you understand how it works, you would be able to print any pattern, but basics should be clear. Try printing variable i, j and k values after each iteration. See the values that how that gets changed after each cycle of execution and then see the logic you've applied.
Your question is somewhat very broad in scope and can not be answered exactly unless narrowed it down. I would suggest to run this line by line and watch the output, try more changes even if it doesn't make any sense, you'll be having a good understanding over looping even for all of your future tasks. And if after trying yourself, you come to any problem, share here, people are ready to solve them. :)
Hope this helps.
First you must a have complete understanding of loops, nested loops then you come up to patterns designing.
1) First run the loops in hard form like on Register/on Page for understanding the loops.
2) Use debugger to identify the loop progress.
If you think about it in terms of mathematics, loops are just functions.
A single for loop would just be x.
Example
for (int i = 0; i < 5; i++) {
System.out.println("This is function x.");
}
However when you start nesting loops it because a greater function. A for loop inside another for loop would be a function x^2
For example:
for (int i = 0; i < 5; i++) {
for (int j = 0; J < 5; j++){
System.out.println("This is the j loop");
}
System.out.println("This is the i loop");
}
The reason behind this is because in order to finish the first iteration of i, everything inside the loop must be completed. But, the i loop has another loop inside of it, so that must be finished first. So the loop with j must execute until it is finished. (In this case 5 times), Great, now we can increment i. But now we have to step through j again! This process continues until i reaches its threshold of being < 5. So the output would look something like this
Output:
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the j loop
This is the i loop
This is the j loop
This is the j loop
....
This would continue until the i has reached 5, in which case it no longer satisfies the necessary i < 5, and the loop would end. Hopefully this helps
First, since i = 0 & 0<5 is true you enter the first(outer) for-loop.
Remember i = 0.
Then j = 0; but 0 < i = 0 is false so you don't enter the second loop.
For the third loop, k = 0 & 0<=0 is true. So you enter the loop and execute the print statement, i.e print a star.
k++, this will increment k by 1 and check the boolean; You ask yourself is 1 <= 0; clearly no ; so you exit the for-loop and then reach the println statement which will take you to the next line.
And then you go back to the outer loop.
//this code print Diagonal Pattern if matrix is
1 2 3
4 5 6
7 8 9
output is :
1
4 2
7 5 3
8 6
9
import java.util.*;
class DiagonalPattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[][];
int i,j,row,col,p,temp=1,last=0;
System.out.println("how many array wants to create and size of array");
row=sc.nextInt();
col=sc.nextInt();
x=new int[row][col];
System.out.println("Enter " +row*col+ " elements of array of array");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
x[i][j]=sc.nextInt();
last=j;
}
}
for(i=0;i<row;i++)
{
System.out.println("");
int k=i;
for(j=0;j<=i;j++,k--)
{
if(j==col)
{
break;
}
else
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
for(p=x.length;p>0;p--,temp++)
{
System.out.println("");
i=x.length-1;
int k=i;
for(j=temp;j<=last;j++,k--)
{
System.out.print(x[k][j]);
System.out.print(" ");
}
}
}
}
I am in a java bootcamp and had an assignment about reversing an array and printing it out. I figured it out after some searching and etc. But I do not get it here is my code
import java.util.Scanner;
public class Assignment_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner num = new Scanner(System.in);
int[] arr;
arr = new int[5];
for(int i = 0; i < arr.length; i++) {
System.out.println("Please enter numbers for array");
arr[i] = num.nextInt();
}
for(int i = arr.length; i > 0; i--) {
System.out.print(arr[i - 1] + " ");
}
}
}
I do not get why the - 1 is added to the array. I tried to read other articles here but for some reason it is just getting past me. I am sorry for bothering you all but I know I need to be able to understand it. Thank you very much for your help
Thats pretty simple: in Java all indexes are being stored from 0, not from 1.
So, arr.length actually returns lastArrayIndex + 1, and you can't access arr[arr.length], because there is no element with such index.
And as the last index of array if arr.length-1, we start from it.
Your code is actually equal to this one (may be you will find it more straightforward):
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i] + " ");
}
Sorry for posting it a seperate answer - not enough reputation for writing comments.
Remember that the last index of an array is arr.length-1. Therefore, if you want to print the value starting from the last index it should be i-1. (Your i has been set to arr.length). If you don't want to have the arr[i-1]. You can do the following instead:
//change i from arr.length to i = arr.length-1
//change i>0 to i>=0
//change arr[i-1] to arr[i]
for(int i = arr.length-1; i >= 0;i--){
System.out.print(arr[i ]+" ");
}
Im working on an assignment for a beginners Java course, and Im having a problem with printing out an array the way that its asking for. The problem is as follows:
"Write a program that asks the user "How many numbers do you want to enter?" With that value, create an array that is big enough to hold that amount of numbers (integers). Now ask the user to enter each number and store these numbers into the array. When all the numbers have been entered, display the numbers in reverse order from the order in which they were entered."
I have everything except the last part, displaying the numbers in reverse order.
Any help on this would be appreciated.
Heres What I have so far:
import java.util.Scanner;
public class ArraysNickGoldberg
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to enter?");
final int NUMBER_OF_ELEMENTS = input.nextInt();
int[] myList = new int[NUMBER_OF_ELEMENTS];
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++) {
System.out.println("Enter a new number: ");
myList[i] = input.nextInt();
}
for( int i = 0; i < NUMBER_OF_ELEMENTS; i++){
System.out.print(myList[i] + " ");
}
}
}
try
for( int i = NUMBER_OF_ELEMENTS - 1; i >= 0; i--){
System.out.print(myList[i] + " ");
}
You may also want to look at
Java Array Sort
to print it in reverse order, you just need to simply reverse your for loop :)
so instead of
for(int i=0; i< NUMBER_OF_ELEMENTS; i++){
}
use this instead:
for(int i=NUMBER_OF_ELEMENTS - 1; i >= 0; i--){ //remember to minus 1 or else you'll get index of out of bound
}