Sum of all integers defined by user that are divisible by 5 - java

What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.
My code:
import java.util.Scanner;
public class SumH4
{
public static void main(String[] args)
{
//define data
int x;
int sum;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
x = sc.nextInt();
sc.nextLine();
sc.close();
System.out.println();
sum = 0;
//do computation
for(int a = 0; a < x; a = a + 1)
{
if(a%5==0)
{
sum = sum + a;
}
}
//print results
System.out.println("Sum = " + sum);
}
}

You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:
for (int a = 0; a <= x; a = a + 1) {

Change
for(int a = 0; a < x; a = a + 1)
to
for(int a = 0; a <= x; a = a + 1)
At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".

Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like
Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
if (a % 5 == 0) {
sum += a;
}
}
// print results
System.out.println("Sum = " + sum);

Related

How do I make a calculator that multiplies more than two numbers?

I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}

Alternating signs + loops

I'm supposed to recreate this code
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
x = x+-(1.0/i);
}
System.out.print(+x);
}
But with alternating signs in the loop (1 – 1/2 + 1/3 – 1/4 + 1/5 – 1/6 + ... + 1/N) and have it print out the value (Enter an integer: 5
The total is: 0.7833333333333332)
I was wondering how I could do this? I was able to write the original code, but I am unaware as to how I could replicate the code but with alternating signs.
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
if(i%2==0){ //even
x = x-(1.0/i);
}
else{ //odd
x = x+(1.0/i);
}
}
System.out.print(+x);
}
This may be what you are trying to do. The important change is the if(i%2==0) logic - Here I use it as a way of alternating on the different iterations of the for loop based on whether i is even or odd.
Hope this helps, feel free to ask any questions
double s = -1; // Sign factor
for (int i = 1; i <= n; i++) {
s = -s;
x += s/i;
}
Change x = x+-(1.0/i); to x -= Math.pow(-1,i)/i;. That should do the trick.

How to divide doubles in an array in java?

I have in array with some doubles in them. I want to divide them, for example with an array that contains 6.0, 3.0 and 2,0 the result should be 1 (6/3/2). I wrote the following code:
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
for(int k = 0; k < division; k ++) {
double resultDivision = divisionArray[k] / divisionArray[k + 1];
}
System.out.println("Result: " + resultDivision);
but that doesn't seem to work. I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 I'm a complete java beginner. Could anyone help me out? Thanks
Your code has three issues.
resultDivision is defined within the scope of the for loop, so it's not visible afterwards, when you print the result.
With #1 fixed, you'll get an ArrayOutOfBounds exception because the second for loop tries to access divisionArray[k+1].
You don't check the arguments that the user gives you. What if a user specifies that it wants to divide -5 numbers? Your code will try to create an array with a length of -5, causing an Exception. Also, What if a user wants to divide by zero? Are you fine with that?
Here's a slightly better version:
Scanner input = new Scanner(System.in);
int division = 0;
do {
System.out.print("How many numbers do you want to divide? ");
division = input.nextInt();
} while (division <= 0);
double[] divisionArray = new double[division];
for (int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
if (divisionArray[i] == 0 && i>0) { // Remove this if you want to allow the user to divide by zero. Entering zero as the first argument is legal
System.out.println("Zero is an illegal argument, please enter a different number");
i--;
}
}
double resultDivision = divisionArray[0];
for (int k = 1; k < division; k++) {
resultDivision = resultDivision / divisionArray[k];
}
System.out.println("Result: " + resultDivision);
Good luck.
this should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
//remember the first value and divide it trough the second,
//third, fourth and so on...
double result = divisionArray[0];
for(int k = 1; k < division; k ++) {
result = result / divisionArray[k];
}
System.out.println("Result: " + result);
}

Array that takes user input to fill but does not allow duplicate elements

I'm trying to write a part of a program that I have for an assignment. This part of the program should take 8 user inputed integers to fill however if the user inputs a digit that has already been inputed an error is displayed and the user is asked to input a different number. As of yet I haven't written the error code and second attempt part of the code because I am having issues with the checking for duplicates part. At present the out put is True no matter what I put in.
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicates = false;
// Run while not true
while (!duplicates) {
// For loop for input into array
for (int j = 0; j < maxNum; j++) {
System.out.println("Enter digit " + digCounter + ":");
arrayIn[j] = in1.nextInt();
digCounter++;
// Check for duplicates
for (int a = 0; a < maxNum; a++) {
for (int k = a + 1; k < maxNum; k++) {
if (k != a && arrayIn[k] == arrayIn[a]) {
// Quit loop if duplicate found
duplicates = true;
}
}
}
}
System.out.println(duplicates);
}
You should look into a collection called Set. There is a pretty handy function Set.contains that will return true or false depending if a number is already in the Set or not. Something like this would do the trick:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
Set<Integer> numbers = new HashSet<>();
int digCounter = 1;
//Run while we need numbers
while (digCounter <= maxNum) {
System.out.println("Enter digit " + digCounter + ":");
int tempNumber = scanner.nextInt();
if (numbers.contains(tempNumber)) { //If number is already chosen
System.out.println("Sorry that number has already been added");
} else { //If new number
digCounter++;
numbers.add(tempNumber);
}
}
System.out.println(numbers);
Or if you HAVE to use only arrays you can do something like this:
Scanner scanner = new Scanner(System.in);
int maxNum = 8;
int[] arrayIn = new int[maxNum];
boolean duplicate;
int digCounter = 1;
// Run while we need numbers
while (digCounter <= maxNum) {
//reset duplicate
duplicate = false;
//Get user input
System.out.println("Enter digit " + digCounter + ":");
int temp = scanner.nextInt();
for (int i = 0; i <= digCounter - 2; i++) { //Loop through accepted numbers
if (temp == arrayIn[i]) { //We have found a match
duplicate = true;
break;
}
}
//Check if duplicate
if (duplicate) {
System.out.println("Sorry that number has already been added");
} else {
arrayIn[digCounter - 1] = temp;
digCounter++;
}
}
System.out.println(Arrays.toString(arrayIn));
Hope this helps!
This code will also work if you don't want to use set.
// creating the array
int[] array = new int[10];
// Taking the first number
System.out.println("Please enter your numbers: ");
array[0] = input.nextInt();
// taking other inputs
int count;
for (count = 1; count < array.length; count++) {
int num = input.nextInt();
// Scanning the array for the number
int n;
for (n = 0; n < count; n++) {
while (array[n] == num) { // This will also work if the user
// wants to give duplicate after
// duplicate
System.out.println("You have entered this number before! Add another..");
num = input.nextInt();
n = 0;
}
}
array[count] = num;
}

Creating an Array filled with Random doubles and finding the Maximum and Average

I need help with this program, I need to
Ask the user to input rows and column sizes using scanner
if the column size is greater than 4+5, they need to re-enter it
I need to fill all the array elements with doubles in range of 4.0, 11.0 by using random object
Find the above array and call two methods,
Method one, I need to find and print the largest sum of columns in the 2D array
Method two, I need to find the average of all elements in the array and return the average value.
Here's my code, it sort of accomplishes it, but it's also sort of messed up and I'm confused.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size");
int rows = input.nextInt();
System.out.println("Please enter column size");
int columns = input.nextInt();
double n = 4.0;
if (columns < n+5.0){
} else{
System.out.println("The column size is too large, please enter a smaller integer");
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for(int a = 0; a<rows; a++)
for(int b = 0; b<columns; b++)
array[a][b] = rand.nextInt(11-4) + 4;
for(int i = 0; i<rows; i++){
double sum = 0;
int sum2 = 0;
for(int j = 0; j<columns; j++){
sum += array[j][i];
sum2 = sum2 + array[i][j];
System.out.println(Arrays.deepToString(array));
}
double average = sum/array.length;
System.out.println("largest sum of the columns is " + sum);
System.out.println("The average of all elements in the array is " + average);
}
}
}
You can use while loops to check if the input is even a valid integer and then if the columns count is larger than 4 + 5 ( i just assumed 9 ). I made the program flow a bit more structured and made a neat output. Basically you just would have to move the System.out.println out of the Loop like #Codebender pointed out.
package array;
import java.util.Random;
import java.util.Scanner;
public class ArrayUtil {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int columns;
int rows;
Scanner input = new Scanner(System.in);
System.out.println("Please enter row size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
rows = input.nextInt();
System.out.println("Please enter column size :");
while (!input.hasNextInt()) {
System.out.println("That is not a valid Number! Try again.");
input.next();
}
columns = input.nextInt();
while (columns > 9) {
System.out.println("The column size is too large, please enter a smaller integer!");
columns = input.nextInt();
}
Random rand = new Random();
int[][] array = new int[rows][columns];
for (int a = 0; a < rows; a++) {
for (int b = 0; b < columns; b++) {
array[a][b] = rand.nextInt(11 - 4) + 4;
}
}
for (int[] arr : array) {
StringBuilder sb = new StringBuilder();
for (int i : arr) {
sb.append("[");
sb.append(i);
sb.append("]");
}
System.out.println("Array :" + sb.toString());
System.out.println("Average : " + average(arr));
System.out.println("Max : " + max(arr));
}
}
public static double average(int[] values) {
double d = 0;
for (double value : values) {
d = value + d;
}
return (d / values.length);
}
public static double max(int[] values) {
double d = 0;
for (double value : values) {
if (value > d) {
d = value;
}
}
return d;
}
}

Categories

Resources