I am trying to increment the counter by whatever number the user inputs. I have been at this for almost an hour now and cannot figure it out. Any ideas?
Here's what I have:
if (starting < ending) {
while (i < ending) {
++i;
System.out.println(i);
}
}
else if (starting > ending) {
while (i > ending) {
--i;
System.out.println(i);
}
}
else {
System.out.println(i);
}
No matter what increment is entered, it starts at the starting number and counts up or down by 1.
It counts up or down by 1 because of ++i and --i. The ++ and -- operators are equal to i = i + 1 and i = i - 1, or i += 1 and i -= 1 respectively.
In order to increase or decrease by the amount a user enters, use i = i + userInput and i = i - userInput, or i += userInput and i -= userInput.
For example:
int userInput = 4;
if(starting < ending) {
while(i < ending) {
i = i + userInput;
System.out.println(i);
}
// ... etc
}
In your while loop, you could put:
while (i > ending){
i -= numberUserInput;
}
This will reassign i's value with itself plus the variable that holds the number the user input (named whatever you want). For addition, you could use += instead of -=.
Related
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.
I'm trying to print following pattern:
0
11
0
222
0
3333
0
222
0
11
0
I want to achieve this by using recursion and a loop inside said recursive method, which gets one integer value passed. The int value determines how far this pyramid pattern goes. In the example above the int value would be 3.
I managed to get the bottom half, but I have no idea to get the upper half.
if (arg != 0) {
System.out.println("0");
for (int i = 0; i <= arg; i++) {
System.out.print(arg);
}
System.out.println();
print(arg - 1);
}
How would I be able to somehow implement some increment, which turns to a decrement to this recursion? Since I'm thinking this would be how I could achieve the above pattern.
Thank you very much in advance!
You can pass two arguments. The Max value and start value which will be zero and
then increment start value until reaches max
then decrement Max until reaches zero
call--> printline(3);
private static void printline(int input, int... vars) {
if (input == 0) {
System.out.println(0);
return;
}
int start= vars.length > 0 ? vars[0] : 0;
start++;
System.out.println("0");
for (int i = 0; (i <= start && i <= input); i++) {
System.out.print(start >= input ? input : start);
}
System.out.println();
if (start >= input) {
input--;
}
printline(input, start);
}
}
The program needs to take an odd number and output it in a descending order
For example: if the input is 11 the output needs to be 11 , 9 , 7 , 5 , 3, 1.
I tried using a for loop but I can only seem to get it to work with even numbers not odd numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for (int i = number - 1; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
}
The output is the number in descending order but as even only. If I add a 1 into the descend variable the numbers would seem to descend in an odd manner but its not ideal.
This line returns true if the number is even:
if (i % 2 == 0) {
If you want to know when the number is odd:
if (i % 2 != 0) {
Also, why are you starting your count at 1 less than the input value:
int i = number - 1;
I think you want to do this:
for (int i = number; i > 0; i--) { // tests for numbers starting at the input and stopping when i == 0
Just replace (i%2==0) to (i%2==1)
Asking if the number % 2 is equal to zero is basically asking if the number is even, so what you really have to do is ask if the number % 2 is not equal to zero, or equal to 1
if (i % 2 != 0) {
int descend = i;
System.out.println(descend + " ");
}
Also, there's no need to subtract 1 from the user input so your for loop can be written like this
for (int i = number; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an an odd number: ");
int number = input.nextInt();
while(number%2==0){
System.out.print("Number must be odd number:" +
"(Ex:1, 3,5)\nTry again: ");
number=input.nextInt();
}
for (int i = number; i >= 0; i--) {
if(number%2!=0){
System.out.println(number);}
number-=1;
}
}
class Labo21
{
public static void main(String [] arguments){
int n;
int i;
double somme;
System.out.print("Positive number: ");
n = Clavier.lireInt(); //keyboard
if( n <= 0){
System.out.print("ERROR");
}else{
i = 2;
somme = 1;
while (n <= i){
somme = somme + 1.0 / i;
i = i + 1;
}
System.out.print("Result: " + somme);
}
}
}
I try to know why I cannot enter the while loop.
This code has a problem with its mentality. You are lucky that it is not going into the loop though. If it so, it would run without stopping and you cannot understand it.
BECAUSE: in your code you say the condition of while loop is i should be equal to or greater than n. I guess Clavier.lireInt(); getting value from user. So if user enters 1 condition will be while( 1 <= 2) then it will go through the while loop. Increment the i, then i will be 3 again greater than n, increment i then 4 will be greater than n. It will go like that.
I thing your condition should be :
while(n>=i)
Then you can enter n as 5 and count i = 2 to 5.
Am I correct ?
Your number needs to be greater than 0 based on your if condition. To get into the while loop, your number needs to be less than or equal to 2 since you set i equal to 2. So your options are 1 or 2.
With that being said, once you're inside the while loop, you will never be able to exit (you have created an infinite loop) because n will always be less than i. Your i is incrementing by 1 on each loop iteration, and n is never changing, so it will never be greater than i. You should add a terminating condition (some way to exit the loop).
Provide 1 or 2 as Clavier.lireInt() and you will go inside the loop.
Example :
class Labo21 {
public static void main(String[] arguments) {
int n;
int i;
double somme;
System.out.print("Positive number: ");
n = 1; //Clavier.lireInt(); //keyboard
if (n <= 0) {
System.out.print("ERROR");
} else {
i = 2;
somme = 1;
while (n <= i) {
System.out.println("in loop");
somme = somme + 1.0 / i;
i = i + 1;
}
System.out.print("Result: " + somme);
}
}
}
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.