Running a simple multiplication table but it's not giving me a desired output. I want each multiplication to be on different column separated with a little space. for example let 1 multiply numbers ranging from 1 to 12 should be on single column , 2 multiply numbers ranging from 1 to 12 on another column. I don't want all to be on just one column.
public class multiplicationTable{
public static void main(String[] args){
for(int i=1; i<=12;i++){
System.out.println(i);
for(int j=1; j<=12; j++){
int mult=i*j;
System.out.println(i + "*"9 + j +" = " + mult +" \t");
}
}
}
}
You should use System.out.print() method instead of System.out.println() method if you want to print stuff on the same line. Your program should look like this:
public class multiplicationTable
{
public static void main(String[] args){
for(int i=1; i<=12;i++){
System.out.println(i);
for(int j=1; j<=12; j++){
int mult=i*j;
System.out.print(i + "*"9 + j +" = " + mult +" \t");
}
System.out.println();
}
}
}
Whenever you call System.out.println(), it moves to the next line. So if you want to print all of the numbers times x on one line, you will have do something like this:
public static void main(String[] args){
// Print the headers
for (int i = 1; i <= 12; i++) {
// Two tabs because the calculations take up room on the console
System.out.print(i + "\t\t");
}
// Start at the next line
System.out.println();
// Let's define each multiplication as x * j
// For each j...
for (int i = 1; i <= 12; i++) {
// ...print all of the x's and their products
for (int j = 1; j <= 12; j++) {
System.out.print(j + " * " + i + " = " + j * i + "\t");
}
// Move to the next line for the next row of j's
System.out.println();
}
}
In this table:
1 * 1 = 1 2 * 1 = 2 3 * 1 = 3
What is changing? The first operand. Therefore, you need to nest the for loops
as the for loop for the first operand nested in the loop for the second operand to get the desired results.
Think about it this way: for each of the second operand, print all of the calculations for the first operands in a row. This way, you get the desired columns.
If this is not what you meant, please let me know in the comments.
Hope this helps.
Related
I have no idea how to phrase the title so feel free to make changes! I am stuck on this program that I have made involving a loop. I want the input to be 1 5 which means the code starts adding from 1 and all the way until 5, the expected output would be 1 + 2 + 3 + 4 + 5 = 15 but my code (see below) would print something like 1 + 2 + 3 + 4 + 5 + = 15. How do I get rid of that unwanted addition symbol?
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int start = keyboard.nextInt();
int end = keyboard.nextInt();
double dend = (double)end;
double dstart = (double)start;
double n = (dend - dstart + 1);
double sum = (n/2)*(dend+dstart);
int intsum = (int)sum;
for (int i =start; i <= end; i++) {
System.out.print(i+" + ");
}
System.out.print(" = "+intsum);
}
You could reduce the looping by one, and then print again
for (int i =start; i < end; i++) {
System.out.print(i+" + ");
}
System.out.print(end);
System.out.print(" = "+intsum);
or you could have if logic in your loop
for (int i =start; i <= end; i++) {
System.out.print(i);
if (i != end) System.out.print(" + ");
}
The logic could be something like:
for (int i =start; i <= end; i++)
{
if (i > start)
System.out.print(" + ");
System.out.print(i);
}
The idea is you only print "+" AFTER the first iteration of the loop.
Another option is to use a StringJoiner:
StringJoiner sj = new StringJoiner(" + ");
for (int i =start; i <= end; i++)
{
sj.add( i + "" ); // converts the "i" to a string
}
System.out.print( sj.toString() );
The StringJoiner will add the delimiter for you automatically as required.
As already mentioned by Scary Wombat you can reduce the lopping by one but in your code you are doing string concatenation for each element which not good (because of immutability nature of string in java).
So better to use some mutable string object (either StringBuilder/StringBuffer) and also you can have look at Collectors.joining() (which is introduced in Java8) if you would like implement this using streams.
An alternate solution would be to count the number of iterations and check if it is on it's last iteration. If not, then print a "+".
public class Main {
public static void main(String[] args) throws IOException {
int i;
int sum=0;
for(i=1;i<=5;sum+=i++)
System.out.println(sum);
}
...
}
Actual Output:15
I don't know how it did the math?
The syntax for the for loop is:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
and is basically equivalent with the following while loop:
[ForInit]
while (Expression) {
Statement
[ForUpdate]
}
That mean that all the following are the same:
for(i=1;i<=5;sum+=i++);
i = 1;
while (i <= 5) {
sum += i++;
}
i = 1;
while (i <= 5) {
sum += i;
i++;
}
for (i = 1; i <= 5; i++)
sum += i;
So it is calculating 1 + 2 + 3 + 4 + 5 = 15
What confuses you is the part
sum += i++
In this statement, first sum=sum+i gets calculated. Once sum has been calculated, value of i is incremented by 1.
Since the loop runs five times, previous value of sum gets added to current value of i, which keeps increases by 1.
Try printing out each iteration through the loop to help you visualise what is going on. Swap your for loop for this.
for(i=1;i<=5;sum+=i++)
{
System.out.println("sum = " + sum);
System.out.println("i = " + i);
}
In this code, the statement sum+ = i++ means sum = sum + i++ In this statement, every sum printed in the loop adds to one increment of i and when the loop ends it will display 15.
So it is calculating 0 + 1 + 2 + 3 + 4 + 5 = 15
I am not sure what I am doing wrong here. Here is the original prompt:
"Write a for-loop that prints: 1 2 .. userNum. Print a space after each number, including after the last number. Ex: userNum = 4 prints:
1 2 3 4"
Here is my code:
import java.util.Scanner;
public class CountToNum {
public static void main (String [] args) {
int userNum = 0;
int i = 0;
userNum = 4;
for (userNum = 1; userNum <= 4; ++userNum) {
System.out.print(userNum + " ");
}
System.out.println("");
return;
}
}
Your for-loop needs to use two different variables, one for checking against, and one for incrementing. You're also incrementing your variable before running the loop (++userNum), which means that you're counting from 2 to 4 instead of 1 to 4 like you meant to.
So, in your case, you would do the following:
for (i = 1; i <= userNum; i++) {
System.out.print(i + " ");
}
for (i = 1; i <= userNum; i++) {
System.out.print(i + " ");
}
What else did you declare i for?
You should use it when you declare it ;)
To print a range of numbers using a for-loop from 1 to a provided ending point, use this:
for (int x = 0; x <= end; x++) {
System.out.println(x + " ");
}
I believe that the problem with the code that you presented is that you're mixing up the ending point (where you call it userNum) and the temporary variable with which you iterate (which I call x, though different conventions may use i).
I have written a simple program in java to find the factorial, which works fine. I am now trying to refine the output, but I'm not sure how to do it.
My Program:
import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
int fact = 1;
Scanner number = new Scanner(System.in);
System.out.println("Enter the number : ");
int n = number.nextInt();
if (n < 0) {
System.out.println("Enter positive number");
} else {
System.out.print("Factorial Sequence is :");
for (int i = n; i >= 1; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("Factorial of number " + n + " is :" + fact);
}
}
}
Output shown is in this format (a single line, * after the 1):
Factorial Sequence is :5*4*3*2*1*Factorial of number 5 is :120
I want output in this format:
Factorial Sequence is :5*4*3*2*1
Factorial of number 5 is :120
Since 1 is not going to modify the factorial result your code can be rewriten as:
for (int i = n; i >= 2; i--) {
fact = fact * i;
System.out.print(i + "*");
}
System.out.println("1");
Another option is to use string concatenation during your for loop:
String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
fact = fact * i;
s += i + (i > 1 ? "*" : "");
}
System.out.println(s);
Only 'benefit' this has over the other options is it saves calling System.out.print each iteration, at the expense of a string concatenation operation. Probably no performance difference at all, and certainly not significant here, but it is an alternate means to the same end.
EDIT: Use #demostene's excellent suggestion to avoid the final '*' after the final '1' - it avoids the conditional expression within the for loop, which is really nice as your factorial becomes larger.
To make the gap, you can add an \n literal to represent a newline.
System.out.println("\nFactorial of number " + n + " is :" + fact);
And for the last *, you can either remove it at the end or not add it if i is 1..
System.out.print(i + (i > 1?"*":""));
This says if i is greater than 1, return a *, otherwise return an empty string.
Just add a print line statement:
System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);
Hi I am a beginner so please don't use any complicated stuff.
Here is a SS of what i mean. http://prntscr.com/1ffec0
as of now don't worry about having numbers vertically and horizontally that display what columns and row number it is.
I have my code but am totally confused on how to go about it and how to make them multiply.
import java.util.Scanner;
public class test
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
int x=0, y=0;
System.out.print("Enter rows ");
x = keyboard.nextInt();
System.out.print("Enter columns ");
y = keyboard.nextInt();
for (int i=1; i<=x; i++)
{
for (int j=1; j<=y; j++)
{
System.out.print(" "+i+j);
}
System.out.println();
}
}
}
I'm not going to give you the answer straight out, but I'm going to help you understand the problem better with some pseudocode. Assume that your x-range goes from 1 to 3, and your y-range also goes from 1 to 3.
You did correctly set up 2 loops
Loop x = 1 to 3
Loop y = 1 to 3
//Do stuff
End innerloop
End outerloop
Now consider the values that will be printed at //do stuff, in pairs like (x, y):
(1, 1) , (1, 2), (1, 3), (2, 1), (2, 2), and so on until (3, 3);
Obviously you want the product to be displayed, so create some variable z = x * y inside the loops
//Do stuff:
z = x * y
Print z + " "
Print z out and leave a space, because you want to print the next value without it being adjacent to the first value.
This will print all your solutions in a straight, single line. But you want it to be in a matrix obviously. The answer is to simple a simple change, taking only one line of code. After each full cycle of your inner loop, you essentially finish one row of multiplication (think about why). So the solution is that after your inner loop finishes running, right before going to the next outer loop value for x, you want to print a new line. All in all we have something like:
Loop x = 1 to 3
Loop y = 1 to 3
z = x * y
Print z + " "
End innerloop
Print NewLine // "\n" is the way to do that
End outerloop
And you're done. You just need to put it into code, as well as accept user input instead of hard coding the range as from 1 to 3, or whatever. This is trivial and I'm sure you'll be able to put it together.
change the i+j by i*j
btw you are printing only half of the matrix
You need to use "*" instead of "+" ?
Like this:
public static void print(int x, int y) {
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
System.out.print(" " + i * j);
}
System.out.println();
}
}
And after that you might want to think about the formatting!? My advice: think about the length of the longest value (is always x*y) and "reservice" enought space for it!
Change:
System.out.print(" "+i+j);
To:
if ((i + j) <= 9) {
System.out.print(i + j + " ");
} else if ((i + j) <= 99) {
System.out.print(i + j + " ");
} else
System.out.print(i + j + " ");