I have a simple but hard problem and wanted to get your help on this.
This is the code:
int i = 0;
while (i < 100) {
i++;
System.out.print(i);
}
This is the real issue that I'm having, how do I control the println to display how many numbers per line that I want so I don't just see 100 numbers in a row straight?
Btw please if at all possible, don't give me the answer but help me to answer it myself instead.
while loops? Why not use for loops? They are much better in this kind of situation i.e. when you want to repeat something a known number of times.
You can use a nested for loop to make this happen:
int counter = 0;
for (int i = 0 ; i < 10 ; i++) {
for (int j = 0; j < 10 ; j++) {
System.out.print (counter);
System.out.print (" "); // I think it is best to have spaces between the numbers
counter++;
}
//after printing 10 numbers, go to a new line
System.out.println ();
}
You could do something like:
for(int number = 0; number <= 100; number++) {
if(number % 10 == 0 && number > 0)
System.out.println(number);
else
System.out.print(number + " ");
}
This would create 10 rows of 10 numbers.
Try this one
if (i%10==1){
System.out.println("");
}
Related
How do I count up from 1 to a given number in triangular fashion?
Attempt
while (numbers <= number) {
System.out.println(numbers);
numbers++;
}
Target Output
1
1 2
1 2 3
I recommend you read about looping in Java, this is a base to start from.
int num = 10;
for(int i = 1; i < num; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.print("\n");
}
This should provide the triangular structure you are looking for. Definitely do take a look at the link above. Since you are new to Java, you should take a walk through this code before simply copying it. Really try to see how it works and more importantly, why it works.
I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.
I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
System.out.print(count + ", ");
}
}
Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.
By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.
...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
System.out.print(count + ",");
num++;
}
}
...
You can just simply create some int value e.g.
int i = 1;
...and increment it's value everytime Sysout is running.
Something like this:
int i = 1;
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
if (i%10 == 0)
System.out.print(count+ "\n");
else
System.out.print(count + ", ");
i++;
}
}
Try this:
int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
idx++;
}
}
you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.
I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){
i was wondering how to make a time table from 1-12 with java sysout
here's the time table:
please advise, thanks.
EDIT: this was a question in an interview to be answered in less than 10 seconds, and i couldn't figure it out in time.
BTW, the empty row is not important.
This sounds like homework but I'm giving you a starting point anyway:
for (int y = 1; y <= 12; y++) {
for (int x = 1; x <= 12; x++) {
System.out.print(x * y + " ");
}
System.out.println();
}
This gives you the numbers you are looking for. You will have to find a way to align them and print the headers yourself.
Something like this?
public static void main(String[] args) {
int n = 12;
for (int i = 1; i <= n; i++) {
System.out.print(i + "\t|");
for (int j = 1; j <= n; j++) {
System.out.print((i * j) + "\t|");
if (j == 12) {
System.out.println();
}
}
}
System.out.println();
}
You can represent it by memorising or there is a trick to the nine times table and the other the trick is if you know your five or other times tamales until where you mnow for example I know until my sixes then you will know what one times six is because it is the one times table and you will know what times six is because it is in the two times table you will know it until six times five because know your going to start your sixes