I am new to Java. Just now I'm practing. If I give input as 6, output should be like this:
1
2 3
4 5 6
Here I'm posting code that I tried:
import java.util.Scanner;
public class Number {
public static void main(String args[]){
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
in.close();
int k = 1;
for (int i = 1; i <= n; i++)
{
// k=i;
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
break;
}
k++;
}
System.out.println("\n");
}
}
}
If I input n=4,i t show the output as:
1
2 3
4
4
Your break will only exit the inner loop (the one that loops over j). The outer loop will continue to run, leading to extra numbers being printed.
You need to either replace it with a return; or System.exit(0), or put a label in front of your outer loop (the one that loops over i) and use a labeled break.
Properly indent your code. It helps your brain to understand.
That said, the solution is two loops with three variables.
You need a loop that goes from 1 to n.
An inner loop that goes from 1 to the number of elements per line.
And you need the number of elements per line. This variable increases every time the inner loop is executed.
It's a badly worded question, but I'm going to guess you want to know why the extra 4?
The reason is you have nested loops, so the break only breaks one loop. Here's how you break out of the outer loop:
outer: for (int i = 1; i <= n; i++) {
...
break outer;
The label outer is arbitrary - you can call it fred is you want.
int n = 6; // target
int i = 0;
int nextRowAt = 2;
int currentRow = 1;
while (++i <= n) {
if (i == nextRowAt) {
System.out.println();
nextRowAt = ++currentRow + i;
}
System.out.print("" + i + " ");
}
But unless you understand it and can properly explain the code, you will probably get a fail on your assignment.
My suggestion is to start by creating/understanding on pen and paper. Write out the sequences and figure out how the algorithm should work. THEN you start coding it.
int sum =0;
int n =10;
// n------> number till where you want to print
boolean limtCrossed = false;
for (int i = 0; i < n &&!limtCrossed; i++) {
for(int j=0;j<=i;j++) {
sum++;
if (sum>n) {
limtCrossed = true;
break;
}
System.out.print(+ sum +" " );
}
System.out.println("\n");
}
public static void main(String[] args)
{
int n = 10;
int k = 1;
boolean breakOuter = false;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(" " + k);
if (n==k)
{
breakOuter = true;
break;
}
k++;
}
if(breakOuter) break;
System.out.println("\n");
}
}
Related
I have just started my java course so still cannot understand a lot of things, help me out please.
So here is the base code
import java.util.Arrays;
import java.util.Scanner;
public class Main<i> {
public static void main(String[] args ) {
System.out.println (" Enter count of digits: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int [] sourceNumber = new int [size];
System.out.println("Enter your digits with space");
for (int i = 0; i < size; i++) {
sourceNumber[i] = scanner.nextInt();
[...]
So I have no single idea how to make method to find any count with stepful numbers. Example:
I have counts like: 12405346 534952359 6456934 1234567
so I need system to find 1234567 and print it out
For example I made method to find a count with munimum same numbers like this:
[...]
for (int j = 0; j < 10; j++) {
if (digitsCount[j] > 0)
differentDigitsCount++;
}
mindifferent = differentDigitsCount;
for (int k = 1; k < size; k++) {
int differentDigitsCount1 = 0;
int[] digitsCount1 = new int[10];
while (sourceNumber[k] != 0) {
digitsCount1[(int) (sourceNumber[k] % 10)]++;
sourceNumber[k] /= 10;
}
for (int j = 0; j < 10; j++) {
if (digitsCount1[j] > 0)
differentDigitsCount1++;
}
if (mindifferent <= differentDigitsCount1) {
} else {
mindifferent = differentDigitsCount1;
l = k;
}
}
System.out.println("Digit with minimum same numbers: " + moimassiv[l]);
[...]
This code is huge, but its fine for me now. I just need to make method to find stepful counts
I'm assuming that you want to print those numbers whose digits are sorted from smallest to largest. Is that right?
You can convert the number to String, then you can get each digit by using charAt(int index) method
You can iterate over sourceNumber and call hasSortedNumbers() for each one to know if its digits are sorted.
for (int number : sourceNumber) {
String valueOfNumber = String.valueOf(number);
if (hasSortedNumbers(valueOfNumber)) {
System.out.println(number);
}
}
This is the code for hasSortedNumbers()
public static boolean hasSortedNumbers(String valueOfNumber) {
for (int i = 0; i < valueOfNumber.length() - 1; i++) {
if (valueOfNumber.charAt(i) >= valueOfNumber.charAt(i + 1)) {
return false;
}
}
return true;
}
I'm assuming you're going to use this method from main, so it needs to be static, since main is static.
Basically I'm comparing each digit with the next one, if it turns out that the next one is smaller, it returns false. If not, when it exits the for loop, it returns true.
I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.
I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));
It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}
it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)
Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}
Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.
I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######
Okay I am so tired of struggling with this and right off the bat I feel really stupid so please be gentle.. I've searched the stack overflow and web and still not finding anything. I am using a nested loop to create a triangle that looks like this:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
...etc. through 128 in the center column.
My loop for the left side renders to the right of my triangle instead of to the left. I'm pretty sure that after I receive an answer I will be hitting my head w/the palm of my hand and saying duh repeatedly. Anyway thanks for your help. I especially want an explanation of the logic. Here is the code.
public class Pyramid_center_x2_0519 {
public static void main(String[] args) {
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 1; j--) {
System.out.printf("%7s", "");
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
for (int leftSide = 2; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
System.out.println("");
}
}
}
Here is the way it renders:
Thanks again.......
UPDATED CODE 12 P.M. 5-31-16: I understand Java prints left to right. Below I have placed the left hand loop before the right side loop but my spacing in front of the triangle is not behaving. Thank you all... again
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 0; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
System.out.println("");
}
}
}
There is no way you can print left side after right and center side.
Java prints from left to the right.
(unless you use some arabic encoding)
Well, you already solved most of your Problems and your last updated version already prints the numbers correctly.
The only thing you still need to fix is the formatting to make it look nice.
Starting from your current code there are 2 things that need changing:
All your printed numbers are supposed to take up the same space (7). You already formatted your "right side" printed numbers in that way, all you have to do is do the same for the other numbers.
You currently allways add 8*7 spaces in front of the line, which of course isn't correct. If you look at the pyramid you can clearly see that 8*7 spaces is correct for the first line, but the second line would need 7*7 spaces in front, the third 6*7 etc. pp.
That means to get the correct formatting for you pyramid you have to modify your loop that prints the spaces to run 1 less time with each iteration of your main loop.
Here is one way how you could update your code to add those 2 changes (I added comments in front of the lines i changed as explanation):
public static void main (String[] args) throws java.lang.Exception
{
/** I added this counter to keep track
* of what iteration/line the loop currently is (see 2.)
*/
int iteration = 0;
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
/** Here we changed the loop condition
* from "j > 0" to "j > iteration"
* (So as iteration gets bigger, the loop runs less often)
*/
for (int j = 8; j > iteration; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
/** This should be self explanatory.
* You already did the same for rightSide.
* This will take care of 1.
*/
System.out.printf("%7d", leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
/** Here we increment our counter with each iteration aka line that is printed */
iteration++;
System.out.println("");
}
}
Try this
Edited: First try to put your spaces before putting your number in triangle(here my first inner for loop is doing) then apply some logic to print the number at its position accordingly.
static DecimalFormat df = new DecimalFormat("#");
public static void main(String[] args) {
for (int i = 1; i < 10; i += 2) {
for (int k = 0; k < (4 - i / 2); k++) { // first
System.out.print(" ");
}
for (int j = 0; j < i; j++) { // second
if (Math.pow(2, j) <= i)
System.out.print(df.format(Math.pow(2, j)));
else
System.out.print(df.format(Math.pow(2, i - j - 1)));
}
System.out.println("");
}
}
I think your approach is not good. Try this algorithm:
public class Main {
public static void main(String[] args) {
int levels = 8;
int lastLevelWidth = levels*2 + 1;
for (int i=0; i<levels; i++) {
int blankPositions = (lastLevelWidth - 1)/2 - i;
for (int j=0; j<blankPositions; j++)
print(" ");
int levelWidth = i*2 + 1;
int numberPositionsPerSide = (levelWidth-1)/2;
for (int j=0; j<numberPositionsPerSide; j++) {
print(Math.pow(2, j));
}
print(Math.pow(2, i));
for (int j=numberPositionsPerSide-1; j>=0; j--) {
print(Math.pow(2, j));
}
System.out.println();
}
}
public static void print(String string) {
System.out.print(string);
int spaces = 5 - string.length();
for (int i=0; i<spaces; i++)
System.out.print(" ");
}
public static void print(double n) {
print(Integer.toString((int)n));
}
}
I did an exercise in one of my books to get this output. We are supposed to use nested loops and basic java. I could not format the output in here but the code below produces the correct output. I got it to print the correct output but I feel like it is very redundant, mainly with the loops regarding the * and spaces if you have a better method for doing this please share!
private static void printDesign(){
int astrickStopper = 1;
int slashStopper = 1;
for (int lines = 1; lines <= 7; lines++) {
for (int firstAstrick = 6; firstAstrick >= astrickStopper; firstAstrick--) {
System.out.print("*");
}
for (int spaces = 1; spaces <= slashStopper; spaces++) {
System.out.print(" ");
}
for (int forwardSlash = 6; forwardSlash >= slashStopper; forwardSlash--) {
System.out.print("//");
}
for (int backSlash = 1; backSlash < slashStopper ; backSlash++) {
System.out.print("\\\\");
}
for (int spaces = 1; spaces <= slashStopper; spaces++) {
System.out.print(" ");
}
for (int secondAstrick = 6; secondAstrick >= astrickStopper; secondAstrick--) {
System.out.print("*");
}
astrickStopper = astrickStopper + 1;
slashStopper = slashStopper + 1;
System.out.println();
}
}
The code you wrote seems like it meets the problem description. You could move the inner loop into a function that outputs a given sequence of characters a certain number of times, then you would just be calling the function 6 times instead of having 6 inner loops.
public void printChars(int count, String chars) {
for (int i = 0; i < count; i++) {
System.out.print(chars);
}
}
How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}