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

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

Related

Formatting returned Strings?

I'm really new to coding and just got assigned my first coding homework involving methods and returns. I managed to struggle through and end up with this, which I'm pretty proud of, but I'm not quite sure it's right. Along with that, my return statements are all on the same lines instead of formatted how my teacher says they should be ("n is a perfect number", then the line below says "factors: x y z", repeated for each perfect number. Below are the exact instructions plus what it outputs. Anything will help!
Write a method (also known as functions in C++) named isPerfect that takes in one parameter named number, and return a String containing the factors for the number that totals up to the number if the number is a perfect number. If the number is not a perfect number, have the method return a null string (do this with a simple: return null; statement).
Utilize this isPerfect method in a program that prompts the user for a maximum integer, so the program can display all perfect numbers from 2 to the maximum integer
286 is perfect.Factors: 1 2 3 1 2 4 7 14
It should be
6 is perfect
Factors: 1 2 3
28 is perfect
Factors: 1 2 4 7 14
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
System.out.print("Enter max number: ") ;
int max = input.nextInt() ;
String result = isPerfect(max) ;
System.out.print(result) ;
}
public static String isPerfect(int number) {
String factors = "Factors: " ;
String perfect = " is perfect." ;
for (int test = 1; number >= test; test++) {
int sum = 0 ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
sum += counter ;
}
}
if (sum == test) {
perfect = test + perfect ;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
factors += counter + " " ;
}
}
}
}
return perfect + factors ;
}
}
Couple of things you could do:
Firstly, you do not need two loops to do this. You can run one loop till number and keep checking if it's divisible by the iterating variable. If it is, then add it to a variable called sum.
Example:
.
factors = []; //this can be a new array or string, choice is yours
sum=0;
for(int i=1; i<number; i++){
if(number % i == 0){
sum += i;
add the value i to factors variable.
}
}
after this loop completes, check if sum == number, the if block to return the output with factors, and else block to return the output without factors or factors = null(like in the problem statement)
In your return answer add a newline character between perfect and the factors to make it look like the teacher's output.
You can try the solution below:
public String isPerfect(int number) {
StringBuilder factors = new StringBuilder("Factors: ");
StringBuilder perfect = new StringBuilder(" is perfect.");
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
factors.append(" " + i);
}
}
if (sum == number) {
return number + "" + perfect.append(" \n" + factors);
}
return number + " is not perfect";
}
Keep separate variables for your template bits for the output and the actual output that you are constructing. So I suggest that you don’t alter factors and perfect and instead declare one more variable:
String result = "";
Now when you’ve found a perfect number, add to the result like this:
result += test + perfect + '\n' + factors;
for (int counter = 1; counter <= test/2; counter++) {
if (test % counter == 0) {
result += counter + " ";
}
}
result += '\n';
I have also inserted some line breaks, '\n'. Then of course return the result from your method:
return result;
With these changes your method returns:
6 is perfect.
Factors: 1 2 3
28 is perfect.
Factors: 1 2 4 7 14
Other tips
While your program gives the correct output, your method doesn’t follow the specs in the assignment. It was supposed to check only one number for perfectness. Only your main program should iterate over numbers to find all perfect numbers up to the max.
You’ve got your condition turned in an unusual way here, which makes it hard for me to read:
for (int test = 1; number >= test; test++) {
Prefer
for (int test = 1; test <= number; test++) {
For building strings piecewise learn to use a StringBuffer or StringBuilder.
Link
Java StringBuilder class on Javapoint Tutorials, with examples.

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

Loops with no body,i got the code from a book but i dont understand the math in the code

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

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.

Making a basic multiplication table in java using loop

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

Categories