I need to make two to the input value inclusive - java

/*
* Application the reads an integer and prints sum of all even integers between two and input value
*/
import java.util.Scanner;
public class evenNumbers{
public static void main(String [] args){
int number;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer greater than 1:");
number = scan.nextInt();
printNumber(number);
}// end main
/*declares an int variable called number and displays it on the screen*/
public static void printNumber(int number){
if (number < 2){
System.out.println("Input value must not be less than 2");
}
int sum = 2;
if(number % 2==0){
sum+= number;
}
System.out.println("Sum of even numbers between 2 and " + number + " inclusive is: " + sum);
}//end printnumber
}
I need to calculate the sum of 2 to the input number inclusive however, it only takes the last number and add two to it. COuld someone help me fix this.

You need a loop. Your comment hints at the right direction, but you should look at the Java tutorials to see how to correctly write a 'for' loop. There are three parts: the initial declaration, the terminating condition and the loop step. Remember that the ++ operator only adds one to the variable. You can add other values using +=. If you use += to add a different value (like 2) to the loop variable, you can skip the 'if' test for even numbers. You can test for boundaries inclusively using the <= and >= comparison operators (for primitives). So you want something like this (in pseudocode, not Java):
input the test value
Optional: reject invalid test value and **exit with message if it is not valid!**
initialize the sum variable to zero
for ( intialize loop variable to 2; test that loop var <= test value; add 2 to loop var )
{
add 'number' to the sum variable
}
display the sum

int sum = 0;
for (int current = 2; current <= number; current += 2)
sum += current;

Related

The Largest/Smallest Outputs do not showcase the right values

Should receive an output of the largest/smallest numbers within the inputs, what seems to be the problem? I have tried looking it up online, the source code appears to be the same. Thank you for your assistance.
Source code:
package counting.largest.smallest;
import java.util.Scanner;
public class CountingLargestSmallest {
public static void main(String[] args) {
Scanner TheN = new Scanner(System.in);
int counter = 0;
int number;
int smallest = Integer.MIN_VALUE;
int largest = Integer.MAX_VALUE;
while (counter < 10) {
System.out.print("Integer=");
number = TheN.nextInt();
counter++;
if (number < smallest) {
number = smallest;
} else if (number > largest) {
number = largest;
}
}
System.out.println("\nSmallest=" + smallest);
System.out.println("Largest=" + largest);
}
}
Output:
Integer=1
Integer=2
Integer=3
Integer=4
Integer=5
Integer=6
Integer=7
Integer=8
Integer=9
Integer=10
Smallest=-2147483648
Largest=2147483647
there were 3 bugs:
1.
int smallest=Integer.MIN_VALUE;
int largest=Integer.MAX_VALUE;
number=smallest;
number=largest;
Using else if
1: When you want to find a min number keep it Integer.MAX_VALUE and when you want to find max keep it has Integer.MIN_VALUE.
Why for min we Initialize Integer.MAX_VALUE and for max we Initialize Integer.MIN_VALUE?
Say you want to multiple n numbers from the user. So we will declare and initialize mul variable to 1. cause we know any number multiple by 1 will give us the same number.
Whereas if we initialize mul with 0 it will give us 0 only.
So we say 1 for multiplication is identity.
Similarly, for finding Minimum number we use an identity that is Integer.MAX_VALUE.
So that number that less then Integer.MAX_VALUE are saved in Samllest variable.
int smallest=Integer.MAX_VALUE;
Similarly for max we initialize it with Integer.MIN_VALUE SO that number that are greater then Integer.MIN_VALUE are stored in largest variable.
int largest=Integer.MIN_VALUE;
2: You are assigning number variable the value of smallest and largest it should be like smallest=number and largest=number
when you write x=0 it says x is 0 that means x is changed, Similarly when you write number=smallest its number = Integer.MAX_VALUE and smallest is not changing at all.
So you should write like smallest = number, It means smallest is the number and smallest is changing every time condition satisfies.
3: When you write
if(condition){
}else if(conditon){
}
else if is only excuted when first if statement if false and if first condition is true second if is never executed.
if we have descending number then second if will never be excuted which would result in having Integer.MIN_VALUE in largest variable.
And here you want to check for both min and max so we should have indepent if statement for each
if(condition){
}
if(condition){
}
Code:
Scanner TheN= new Scanner(System.in);
int counter=0;
int number;
// changed
int smallest=Integer.MAX_VALUE;
int largest=Integer.MIN_VALUE;
while(counter<10){
System.out.print("Integer=");
number=TheN.nextInt();
counter++;
if(number<smallest){
// changed
smallest= number;
}
if(number>largest){
// changed
largest=number;
}
}
System.out.println("\nSmallest="+smallest);
System.out.println("Largest="+largest);
Output:
Integer=1
Integer=2
Integer=2
Integer=4
Integer=3
Integer=6
Integer=7
Integer=8
Integer=9
Integer=10
Smallest=1
Largest=10

Java program infinite loop in sum of even integers

I am creating a program that prints the sum of the even numbers from a range of 0 to the number that the user entered. For example, if the user entered the number 20, the program would calculate the sum of all of the even numbers between 0 and 20.
When I tested the program out with the number 10, it worked. But I tried using a different number, 35, and it was just stuck in an infinite loop. I would appreciate any and all help. The code will be posted below:
(Edit) Thanks for the feedback everyone! After talking with a friend, we realized that the solution is actually pretty simple. We were just making it complicated. Still, thanks for all of the suggestions.
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// #me
// #version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
Why are you writing loop for this, there are efficient way to do it.
Sum of numbers between 1-N = (N(N+1))/2
Sum of even numbers between 1-N = (N(N+2))/4
where N = user given input number till which you would like to add even numbers
NOTE: you can add validation on input number that it’s even by (n%2 == 0) and return error if it’s not
The variable you have used in condition (i.e. sum & user_num) no one changes in case of odd number and your code stuck in never-ending loop.
You should use counter variable ( e.g. i from 1 to user_num) and use that number in the condition. Example:
// starts adding the values
sum = 0;
for (int i = 0; i <= user_num; i++)
{
if (i % 2 == 0) // checks if the number is even
sum+=i; // add the number to sum
}
Your for loop should be like this.
int total_sum = 0;
for (int sum = 0; sum <= user_num; sum++)
{
if (sum % 2 == 0) // checks if the number is even
total_sum+=sum; // add the number to total sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
// note print total sum
System.out.println(totalsum);
your initial program just kept on checking entered number is even or odd.
And the entered number to sum.
So sum was always double of the entered number is even.
If entered number is odd it would go to infinite loop as entered_num(odd) % 2 == 0 always false and execute else statement.

Simulating Logarithms by repeated Integer division

I'm trying to write a program that simulates logarithms by repeated integer division. A user inputs a base number and a value X that they want to take the log of. The code runs through a loop and increments a count after each successive division. The code is set to stop after the value of X gets smaller than the base because I'm only using int type variables.
This code works fine for some numbers and bases but for others it gives the wrong value. It does " log_2(64) is 6 " however it doesn't do log_10 of 100. It gives a count of 10.
public static void main(String[] args) {
Scanner inScan = new Scanner(System.in);
int base;
int X;
int response;
int n=0;
do{
System.out.println("Java Lab 3 Logarithm Solver.");
System.out.println("Please enter a base > 1");
base = inScan.nextInt();
System.out.println("Please enter a number, X>0.");
X = inScan.nextInt();
if (X > 0 && base > 1){
System.out.println("Logarithm base " +base+ " of " +X+" is ");
for ( ; X>base ;n++){
X=(X/base);
}
System.out.println(n);
} else {
System.out.println("Invalide numbers.");
}
System.out.println("Would you like to go again? Press 1, press 0 to quit");
response = inScan.nextInt();
} while (response == 1);
}
}
You are declaring n as a global variable; I suspect that if you check your tests, this algorithm works only the first time through every time you compile and run it. Instead of having n as global, declare it in your for loop like
for(int n = 0; X < base; n++)
since it looks like you need the value of n later, I suggest having a variable with a wider scope, perhaps declared in the do-while loop, to store the n in, like
do
{
int numberOfTimesThroughLoop = 0;
...
for(...)
{
x = x/base;
numberOfTimesThroughLoop = n;
}
}
as a side note, most of the time variables (even single letter variable, like your 'X') being with a lower case character

Understanding methods. Java code

Write a method that computes the sum of the digits in an integer. Use
the following method header: public static int sumDigits(long n)
Programming problem 5.2. Page 212.
Please forgive my newness to programming. I'm having a hard time understanding and answering this question. Here's what I have so far. Please assist and if you dont mind, explain what I'm doing wrong.
import java.util.Scanner;
public class PP52v2 {
public static void main(String [] args) {
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}//main
public static int sumDigits(long n) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
n = input.nextLong();
int num = (int)(n);
int sum;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}//loop
return sum;
}//sumDigits
}//class
Basically, you should not be handling the user input inside of the method. You should be passing the user input into your method. Other than that, everything looks good. I've made that slight change below:
import java.util.Scanner;
public class PP52v2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
long n = input.nextLong();
int sum = sumDigits(n);
System.out.println("The sum is: " + sum);
}// main
public static int sumDigits(long n) {
int num = (int) (n);
int sum = 0;
while (num > 0) {
sum += num % 10; // must mod - gives individual numbers
num = num / 10; // must divide - gives new num
}// loop
return sum;
}// sumDigits
}// class
Do the prompt
System.out.println("Enter your digits");
n = input.nextLong();
in your main(String[] args) method because n is not currently declared in the scope of the main method.
public static int sumDigits(int num) {
int sum = 0;
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new number
} //End loop
return sum;
}
For one, you should not read in the number within this method, as it accepts the number as a parameter. The method should be invoked after calling long inputNum = input.nextLong(); by using int digitSum = sumDigits((int)inputNum).
When writing a method, you have input, output, and side effects. The goal is to choose the right combination of the three so that the method, and program as a whole, words as expected.
It seems like your method is supposed to take a number as input and return each digit added together into one final sum.
Write A Test
Usually when you program, you come up with some code that uses your imaginary function. This is called a test. For a test, this could work:
System.out.println("123 should be 6: " + sumDigits(123));
Choose A Signature
You've already managed to right the correct signature. Nice!
Implement Method
Here's where you're a bit confused. Read through what every line of code does, and see if it is accomplishing your goal.
// set up a scanner for reading from the command line
// and print a message that you expect digits
Scanner input = new Scanner(System.in);
System.out.println("Enter your digits");
// read the next long number from the input stream
n = input.nextLong();
Why is this part of your method? You already have the number passed in as the argument n.
// cast the number to an integer
int num = (int)(n);
Again, not sure what this is accomplishing, besides the possibility of a bug for large numbers.
// initialize the sum variable to 0.
int sum;
Would be clearer to explicitly set the sum to 0. int sum = 0;
// add the last digit and truncate the number in a loop
while(num > 0) {
sum += num % 10; //must mod - gives individual numbers
num = num / 10; //must divide - gives new num
}
// actually return the calculated sum
return sum;
This seems like the only part of the method you need. Hopefully this helps!
Since the input number can be either positive or negative, you need to convert it to its absolute value to get the sum of digits. Then for each iteration, you add the remainder to the total sum until the quotient is 0.
public static int sumDigits(long n) {
int sum = 0;
long quotient = Math.abs(n);
while(quotient > 0) {
sum += quotient % 10;
quotient = (long) quotient / 10;
}
return sum;
}
Your code works fine for me.
i just changed int sum = sumDigits(n) to int sum = sumDigits(0) since n wasn't declared.
To have it done correctly, you just would have to put your scanner into the main method and pass the result of it (the long value) to your method sumDigits(long n).

Result no initialized?

import java.util.*;
//Creates a program which allows the user to find the factorial of a number
public class forLoop {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number you want the factorial from: ");
int number = input.nextInt(); // user input
input.close();
int result_2 = getFactorial(number); //initializes getFactorial method
System.out.println("The factorial of " + number + " is " + result); //prints results
}
public static int getFactorial (int num1) {
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
return result; // returns results (here is the problem)
}
}
The compiler cannot assume that the loop would execute at least once - a necessary condition for the result to get assigned.
Change declaration of result as follows to fix the problem:
int result = 1;
This would help your code compile, but it would not fix the logical error in calculating the factorial: currently, your loop would run indefinitely because of a wrong loop condition.
You should be multiplying numbers from 1 to num1, inclusive. Change the loop condition so times >= 1 instead of times <= 1, and the loop body to result *= times to fix this error.
You need to intialize this variable:
int result;
Like this:
int result = 0; //Which ever intial value you want
Because compiler will not be sure that for loop will be always executed.
The condition of for loop is incorrect
it shoud be
for (int times = num1; times >= 1; times--)
{
result *= times; //this wil calculate right factorial
}
also initialize result to 1 before for loop
since you are assigning the function return value to result_2, you should print that instead of result
try
System.out.println("The factorial of " + number + " is " + result_2);
And you are need to initialize local variable before using them
int result;
for (int times = num1; times <= 1; times--) { //repeats loop until times <=1
result = num1 * (num1 - 1); //does the factorial equation
}
This block is causing the error. If the loop does not run even once due to this
times <=1
condition java wont have anything to print here
System.out.println("The factorial of " + number + " is " + result);
So here comes the need of initialization which acts as a default value to print.
So the solution will be to replace
int result;
with
int result=1; // note that I am not initializing with 0 as that will cause every factorial to become zero.
there is another mistake in your code instead of
times <= 1
it should be
times >= 1
Your code will probably not run even once for this error.
Just initialize int result to something:
int result = 0;
Because your loop isn't executing (times is already greater than 1), it is trying to return an uninitialized variable.

Categories