Making a basic multiplication table in java using loop - java

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 + " ");

Related

How to fix loop so that the code does not print "+" behind the last number

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 "+".

for loop wrong, or equation wrong. what do I need to write after my if statement?

I have just started learning java in netbeans at university. I have written a code to multiply the numbers between 4 and 30 by 3, so that my code will only print out the numbers >= to 4 and will not exceed 30 when multiplied by 3.
I would like my code to print out there are 7 integers greater or equal....etc but my code prints out there are 11 integers I always get confused as to what I need to write after my for or while loops, I am pretty sure my maths is right but why is it calculating to 11 instead of 7?
public static void main(String[] args) {
int start = 4, stop = 30, multiple = 3;
countMultiples(start,stop, multiple);
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++)
if(numbers * multiple <= stop)
numbers++;
System.out.println("there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
System.out.println("which multiplied by " + multiple);
}
You have logic mistake at if condition inside for loop you just need to multiply i * multiplein order to get the expected result:
for(int i = start; i <=stop; i++){
if(i * multiple <= stop){
numbers++;
}
}
public static void countMultiples(int start, int stop, int multiple){
int numbers = 0;
for(int i = start; i <=stop; i++) {
if (i * multiple <= stop) { // <-- the numbers should be i
numbers++;
} else {
break;
}
}
}
Basically what you are doing inside the if is
first you are multiplying with the number which starts from 0 and upon multiplication the overall result is <=30 and your if condition satisfies and it increment your count.
*The difference that you are getting in your count is because you are starting from 0 ,but as you mentioned your number should begin from 4.
So instead of
if(numbers * multiple <= stop)
numbers++;
do this
if(i*multiple <=stop)
numbers++;
Since now you start from i which has its initial value as 4, you shoukd get the right count
You missed the logic here if(numbers * multiple <= stop)
Do it like this
for(int i = start; i <=stop; i++)
if(i * multiple <= stop)
numbers++;
okay first thing first, 4 and 30 are not included right ?
so when setting the i add 1 to it.
then in the condition of the loop remove the equal sign , so it will stop before reaching the number 30.
for(int i = start+1 ; i <stop; i++){//start checking from number 5 , remove the equal sign
if(multiple* i < stop){ //also remove the equal sign here
numbers++;
System.out.println(multiple* i+" :there are " + numbers + " integers greater or equal " + start + " and not exceeding " + stop);
}

Writing a For loop that prints 1 2 ... userNum?

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).

Times Table format

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.

Simple program using loops (Beginning Java)

I have to write a program using loops that calculates the sum of all odd numbers between a and b (inclusive), where a and b are inputs.
I made this (below) and it works fine, but I noticed one problem with it: when i enter a larger number followed by a smaller number for the inputs, it returns 0, but when i enter the smaller number first it works perfectly. Any quick fixes for this? :)
import java.util.Scanner;
public class ComputeSumAAndB
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter 2 integers: "); //prompts user for ints
int a = in.nextInt();
int b = in.nextInt();
int sum = 0;
for (int j = a; j <= b; j++)
{
if (j % 2 == 1)
sum += j;
}
System.out.println("The sum of all odd numbers (inclusive) between " + a + " and "+ b + " is " + sum);
}
}
int temp;
if(a > b) {
temp = a;
a = b;
b = temp;
}
Put this right before your for loop starts.
The if checks whether a (the first number entered) is larger than b. If it is, it swaps a and b. Now your for loop will always start with the smallest number and iterate up to the larger number (because after this if, a will always be the smaller number).
Using this method has the added side effect of making your output make sense. Your output will now always say: "between [smaller number] and [larger number]".
rolfl's answer is more elegant and works perfectly fine, but when the user enters the larger number first, your output may look kind of weird: "between [larger number] and [smaller number]", etc.
You can get the smaller and larger inputs by using the Math.min() and Math.max functions....
for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {
if (j % 2 == 1) {
sum += j;
}
}
It's not working because A is larger than B in the for loop, you have it iterate while A is less than or equal to B.
You could do what nhgrif says but it's changing your data.. But he is correct.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.
Actually you should do the following 2 things:
1 It is just just like rolfl mentioned above. You need to put the min and max in the right place in loop.
for (int j = Math.min(a,b); j <= Math.max(a,b); j++)
{
if (j % 2 == 1) {
sum += j;
}
}
2 Use if (j % 2 == 1) it is not enough to check whether the num is odd.
e.g.
a = -5, b =0;
What will be the result?
int sum = 0;
for(int j=-5;j<0;j++)
{
if(j%2 == 1)
{
sum+=j;
}
}
The value for sum will be 0.
We need to change the condition to if(!(j%2 == 0)) Then you will get the expected result.
That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.

Categories