I'm trying to make a Java program that creates multiplication tables using nested for loops by asking the user for upper bounds and display the following result such as this (first image attached). Desired format
However, my code is causing it the program to only print out the multiple of the two inputs and looping that the same amount of times as the multiple. For example in here (second image attached), if it put in the input as 3 and 5, it is displaying 15 to me 15 times. My displayed format
This is what my code looks like (last image attached):
My code
Thank you all so much in advance. Please help me out!!! I've been stuck on this for a while.
Try this:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int firstFactor = 0;
int secondFactor = 0;
System.out.print("Enter the first factor: ");
firstFactor = s.nextInt();
System.out.print("Enter the second factor: ");
secondFactor = s.nextInt();
for(int i=1; i<=firstFactor; i++) {
for(int j=1; j<=secondFactor; j++) {
System.out.println(i + " * " + j + " = " + i*j);
}
System.out.println();
}
}
Output:
Enter the first factor: 3
Enter the second factor: 5
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
Modifications:
Change firstFactor*secondFactor to i*j. Since firstFactor was 3 and secondFactor was 5. Hence you were getting 15 as an output each time.
I would strongly suggest not using an image for your code. You can just add it as part of your question using the provided edit tools (or Ctrl+k).
Anyway, from a quick look your code looks fine with one bug. You just need to do this:
System.out.println(i*j)
Where you had:
System.out.println(firstFactor*secondFactor)
Those are set to input values and do not change during the loop.
Change your first and second factor to i and j.
for(int i=1;i<=3;i++) {
for(int j=1; j<=5; j++) {
System.out.print("i: "+i+" j: "+j);
System.out.println(" Value: "+i*j);
}
}
Related
Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;
Overview
I'm sure this is a simple problem for most of you on here, but I have been struggling with a small spacing problem and was hoping I can learn from someone more experienced. I need to produce a triangle similar to the one below. You can see that the numbers are aligned correctly no matter the length.
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
My Code
Here is what I have so far. It isn't the prettiest, but it seems to give me the correct values at least.
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
My Results
This is the console output when 6 rows are chosen. Everything looks good until row 5 when a 2 digit number (16) appears. What are some efficient ways to align the results properly?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
You calculate length as the number of digits in rows, but it needs to be number of digits in largest number in triangle.
E.g. for rows = 6, largest number is 32, so length should be 2.
For rows = 8, largest number is 128, so length should be 3.
Largest number is 2rows, which in Java means 1 << rows, so change length calculation to:
int length = ("" + (1 << rows)).length();
You are also adding one too many blanks on the left.
Change code to this:
a = rows - 1;
First of all i can recommend to determine the largest number in pyramid. Then count digits in this number. For 8 rows this number is 128, it has 3 digits. According this information we can decide that we need 3+1=4 (including spaces) characters to print every value in pyramid.
After it you have to complete every output number by spaces (from the left) to achive string size of 4 characters.
And the global prefix for every pyramid line will contain (rows - i) * 4 spaces.
how do I make a loop that checks 1, 4 times and then moves to 2, and checks it 4 times, and moves to 3, and checks it 4 times.
For example:
//Btw, isNextFree is a boolean that returns true or false if the next line is free.
while(linenumber.isNextFree()){
int linenumber=1;
username = line(linenumber,usernamefile);
linenumber+=1;
}
So, what that loop does is it checks linenumber of usernamefile.txt and stores that value in a hashmap, I need to check use that string value in line one which is stored in that hashmap to make a 4 strings on what is on linenumber 1 on username file concatenate with 1 same passwordstring on passwordfile.txt.
By the way, I'm using scanner, so the line and linenumber.isNextFree doesn't exist, it is like scanner's .isNext basically.
I don't understand the second part of the question, for the first:
for(int i=1; i<4; i++)
{
for(int j=1; j<5; j++)
{
//Do somethings for check
//Example
System.out.println("It's "+ i + " = " j ");
}
System.out.println(""); //only a new line like \n
}
With this code, it do somethings with 1, 4 times
after do something with 2, 4 times
and after do somethings with 3, 4 times
the output is:
It's 1 = 1
It's 1 = 2
It's 1 = 3
It's 1 = 4
It's 2 = 1
It's 2 = 2
It's 2 = 3
It's 2 = 4
It's 3 = 1
It's 3 = 2
It's 3 = 3
It's 3 = 4
I hope this helps.
How will do a program that displays a multiplication table based on the size that the user inputs? And will add each row and each column? Something like this:
Enter a number: 4
1 2 3 4 10
2 4 6 8 20
3 6 9 12 30
4 8 12 16 40
10 20 30 40
I tried this:
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = s.nextInt();
for(int i = 1; i <= x; i++)
{
for (int j = 1; j <=x; j++)
{
System.out.print((i*j) + "\t");
}
System.out.println();
}
Sample Output:
Enter a number: 4
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
How I will do to add each row and each column?
Since this seems like homework, I wouldn't feel comfortable writing your code for you. However, keep the following things in mind.
Your matrix will always be a square, as the user only enters a single number, of n x n numbers.
Since these numbers increment by one along the row and column, the sum of each row and column pair will be the same. In other words, the total of row[n] will equal the total of column[n].
Using that, you can create a single array of size n to store the sum of each row. For example:
Enter a number: 3
1 2 3 x
2 4 6 y
3 6 9 z
x y z
When you're looping through each row, you can store the row total in the array.
Row 0: Add 1 + 2 + 3 and store in array[0]
Row 1: Add 2 + 4 + 6 and store in array[1]
Row 2: Add 3 + 6 + 9 and store in array[2]
At the end of each row you can simply display the total in array[row]. When you finish drawing all rows, you'd simply loop through array and display each total value.
Hope this points you in the right direction!
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter size of table: ");
int x = s.nextInt();
int r = 0;
int l = 0;
int f = 0;
for(int i=1;i<=x;i++){
for (int j=1; j <=x; j++)
{
r = r + j;
System.out.print(i*j+"\t");
}
System.out.print(r);
System.out.println();
System.out.println();
l=l+i;
}
for(int k = 1; k<=x;k++)
{
f=f+l;
System.out.print(f + "\t");
}
This is the code for an upcoming university practical I have:
import java.util.Random;
public class Practical4_Assessed
{
public static void main(String[] args)
{
Random numberGenerator = new Random ();
int[] arrayOfGenerator = new int[100];
int[] countOfArray = new int[10];
int count;
for (int countOfGenerator = 0; countOfGenerator < 100; countOfGenerator++)
{
count = numberGenerator.nextInt(10);
countOfArray[count]++;
arrayOfGenerator[countOfGenerator] = count + 1;
}
int countOfNumbersOnLine = 0;
for (int countOfOutput = 0; countOfOutput < 100; countOfOutput++)
{
if (countOfNumbersOnLine == 10)
{
System.out.println("");
countOfNumbersOnLine = 0;
countOfOutput--;
}
else
{
if (arrayOfGenerator[countOfOutput] == 10)
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
else
{
System.out.print(arrayOfGenerator[countOfOutput] + " ");
countOfNumbersOnLine++;
}
}
}
System.out.println("");
System.out.println("");
String occurrencesReport = "";
String graph = "";
for (int countOfNumbers = 0; countOfNumbers < countOfArray.length; countOfNumbers++)
{
occurrencesReport += "The number " + (countOfNumbers + 1) +
" occurs " + countOfArray[countOfNumbers] + " times.";
if (countOfNumbers != 9)
graph += (countOfNumbers + 1) + " ";
else
graph += (countOfNumbers + 1) + " ";
for (int a = 0; a < countOfArray[countOfNumbers]; a++)
{
graph += "*";
}
occurrencesReport += "\n";
graph += "\n";
}
System.out.println(occurrencesReport);
System.out.println(graph);
int max = 0;
int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
test = counter + 1;
}
}
System.out.println("The number that appears the most is " + test + ".");
}
}
The program creates an array that will store 100 integers (all of which are between 1 and 10), which are generated by a random number generator, and then print out ten numbers of this array per line. It then scans these integers, counts up how often each number appears and store the results in a second array.
Following this, it outputs a horizontal bar chart of asterisks showing how often each number appears before finally outputting the number that appears the most often.
I thought I had the code totally and completely done, but I've just realised that if multiple numbers occur the same amount of times, the last part of my code can't handle this, e.g. if the numbers 3 and 5 both appears 12 times, the code can only produce one of them.
Does anyone have a way around this?
Thanks,
Andrew
There are a couple of ways to address this, which range from quick to complex. The easiest way is to brute force it like such:
int max = 0;
//int test = 0;
for (int counter = 0; counter < countOfArray.length; counter++)
{
if (countOfArray[counter] >= max)
{
max = countOfArray[counter];
//test = counter + 1;
}
}
System.out.print("The number that appears the most is");
boolean first = true;
for(int i = 0; i < countOfArray.length; i++)
{
if(countOfArray[i] == max)
{
if(first)
first = false;
else
System.out.print(",");
System.out.print(" " + (i+1) );
}
}
System.out.println(".");
Here's the output:
6 2 6 5 6 8 9 3 5 8
9 8 10 10 4 5 8 9 8 5
1 7 8 5 6 7 10 4 5 4
2 7 9 2 3 3 1 2 10 3
5 2 10 1 1 6 3 3 8 10
2 6 10 2 5 1 4 10 8 7
7 8 7 3 7 8 3 4 5 5
7 8 9 8 6 6 8 1 10 3
2 5 4 6 9 9 10 10 1 10
9 4 10 9 7 3 4 3 2 4
The number 1 occurs 7 times.
The number 2 occurs 9 times.
The number 3 occurs 11 times.
The number 4 occurs 9 times.
The number 5 occurs 11 times.
The number 6 occurs 9 times.
The number 7 occurs 9 times.
The number 8 occurs 13 times.
The number 9 occurs 9 times.
The number 10 occurs 13 times.
1 *******
2 *********
3 ***********
4 *********
5 ***********
6 *********
7 *********
8 *************
9 *********
10 *************
The number that appears the most is 8, 10.
There are much cleaner ways to go about it, but hopefully that gives you a decent start!
I am assuming this is not some kinda homework, so i am providing you another approach than this.
- Use Collection like ArrayList instead of Array.
- Use method like Collections.frequency(Object o) to know the number of time the value got occurred in that Collection.
Instead of just doing
System.out.println("The number that appears the most is " + test + ".");
Again loop through countOfArray, do the print for each element that has the same value as max.