How do I accumulate a sum of a series of input values? - java

//Modify the program from the previous exercise, so that it displays just the sum of all of the numbers from one to the input number. Be sure to test your program with several inputs.
// Example5.java
import java.util.Scanner;
public class Example5 {
public static void main(String[] args) {
int count = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = in.nextInt();
while (count <= number) {
System.out.println(count);
++count;
}
}
Given that code I have to modify the program that it displays the sum from 1 to the input number.

You asked
How do I accumulate a sum of a series of input values?
In the mentioned practice you need to separate your numbers with whitespace, there are many more advance approach like using IntStream api.
public class Example5 {
public static void main(String[] args) {
int sum = 0;
System.out.println("Add your numbers to sum: ");
Scanner in = new Scanner(new Scanner(System.in).nextLine());
while (in.hasNext()) {
sum += in.nextInt();
}
System.out.println(sum);
}
}

This code gives an output based on the statement, "Given that code I have to modify the program that it displays the sum from 1 to the input number."
import java.util.Scanner;
public class Example5 {
public static void main(String[] args) {
int sum = 0, number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
number = in.nextInt();
for (int i = 1; i <= number; i++) sum += i;
System.out.println(sum);
}
}

Related

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

How to compare user input in array?

Hi guys sorry I'm a newbie to Java, this is one of the exercise in my class.
I supposed to ask user input 5 numbers, then compare them if they are the same number that entered before.
These are my code so far, but I can't get it work.
Thanks.
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
You may want something like this:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}

Separating an integer and adding the values with support for a negative integer

I have an assignment to break an integer into it's individual digits, report them back to the user, and add them. I can do that, but I'm struggling with supporting negative integers. Here's my code, which works exactly the way I want it to, but only for positive integers:
import java.util.*;
public class Module4e
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i]);
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
I've found plenty of hints for getting this to work with positive integers, but none for negatives.
Use RegExp
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestDigits {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Validate Input
String number = console.nextLine();
Pattern p = Pattern.compile("(-?[0-9]{1})+");
Matcher m = p.matcher(number);
if (!m.matches()) {
throw new IllegalArgumentException("Invalid Numbers");
}
// Calculate
p = Pattern.compile("-?[0-9]{1}+");
m = p.matcher(number);
int result = 0;
System.out.print("The digits of the number are: ");
while (m.find()) {
System.out.print(m.group() + " ");
result += Integer.valueOf(m.group());
}
System.out.println("");
System.out.println("Result " + result);
}
}
// I think you can use this code //also you can multiply the number by -1
int positive = 0;
//positive give you information about the number introduced by the user
if (myNum.charAt(0)=='-'){
positive=1;
}else{
positive=0;
for (int i=positive; i<myNum.length(); i++){
//be carefull with index out of bound exception
if ((i+1)<myNum.length()){
upNum[i]=myNum.substring(i,i+1);
}
}
Change the statement String myNum=console.nextLine() to String myNum = String.valueOf(Math.abs(Integer.valueOf(console.nextLine())));
You do not have to use String to solve this problem. Here's my thought.
import java.util.*;
public class Module4e throws IllegalArgumentException {
static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter an integer: ");
if (!console.hasNextInt()) throw new IllegalArgumentException();
int myNum=console.nextInt();
myNum = Math.abs(myNum);
int sum=0;
System.out.println("\n");
System.out.print("The digits of the number are: ");
While (myNum > 10) {
System.out.print(myNum % 10);
System.out.print(" ");
sum += myNum % 10;
myNum /= 10;
}
System.out.println(myNum);
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}
Try this. I gave -51 as input and got -6 as output. This is what you are looking for?
import java.util.*;
public class LoggingApp
{
static Scanner console=new Scanner(System.in);
public static void main(String[] args)
{
int multiple = 1;
System.out.print("Enter an integer: ");
String myNum=console.nextLine(); //Collects the number as a string
Integer myNumInt = Integer.parseInt(myNum);
if (myNumInt < 1){
multiple = -1;
myNum = Integer.toString(myNumInt*-1);
}
int[] asNumber=new int[myNum.length()];
String []upNum=new String[myNum.length()]; //updated
int sum=0; //sum starts at 0
System.out.println("\n");
System.out.print("The digits of the number are: ");
for (int i=0;i<myNum.length();i++)
{
upNum[i]=myNum.substring(i,i+1);
System.out.print(upNum[i]);
System.out.print(" ");
sum=sum+Integer.parseInt(upNum[i])*multiple;
}
System.out.println("\n");
System.out.print("The sum of the digits is: ");
System.out.println(sum);
}
}

How to sum any amount of user inputted numbers from a single line

Trying to figure out how I would take any amount of inputted numbers from a user and add them together
Example user input: 1 2 3 4
Sum = 10
The user can put any amount of numbers in not a specified amount so if he wanted to add 1 2 3 4 5 6 7 8 9 10 11 12 13, it would sum them all up to 91
Thanks for the help in advance.
import java.util.Scanner;
public class test
{
public static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
while (score >= 0) {
if (score <= -1) {
score = kb.nextInt();
sum += score;
score = 0;
}
System.out.println(sum);
}
}
}
Thanks to libik for all his time and help, here is the finished code.
import java.util.Scanner;
public class JavaApplication1156 {
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
if (sum <= -1)
System.out.println("Application ended");
else if (sum >= 0)
System.out.println("Sum = " + sum);
} while (sum != -1);
}
}
It is very easy actually
import java.util.Scanner;
public class JavaApplication115 {
public static void main(String[] args) {
System.out.println("write numbers, if you write zero, program ends");
Scanner input = new Scanner(System.in); //just copy-and paste this line, you dont have to understand it yet.
int number;
int sum = 0;
do {
number = input.nextInt(); //this reads number from input and store its value in variable number
sum+= number; //here you add number to the total sum
} while(number != 0); //just repeat cycle as long as number is not zero
System.out.println("Sum is : " + sum);
}
}
Working code based on your code :
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println(sum);
}
Also if you are interested in "minimal" version, which is the same as the one before, but using as less code as possible, here it is :
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter numbers here");
Scanner kb = new Scanner((new Scanner(System.in)).nextLine()); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
sum += kb.nextInt();
}
System.out.println(sum);
}
Find sum of each line as long as sum is not zero (based on second block of code) :
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println("Sum = " + sum);
} while (sum != 0);
}
//Input the number in a single line (but be in size limit of integer)
import java.util.Scanner;
public class Sum_of_integers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while(num >= 1) { //base value
int lastval = num % 10; //the logic
num = num / 10;
sum += lastval;
}
System.out.println(sum);
}
}
Question - Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.
Scanner sc = new Scanner(System.in);
int input = 0;
int sum = 0;
while (true){
sum = sum+input;
if (input==5){
System.out.println("Loop is stopped");
System.out.println("The sum is " + sum);
break;
}
else {
System.out.println("Take the inputs");
input = sc.nextInt();
}
}

Creating a method with a for loop to find odd abundant sigma function numbers

I'm trying to create a method that will take a number and determine whether the number is an odd, abundant number with the sigma function. An abundant number is any number that when put into the sigma function generates a sum greater than the number given.
For instance, sigma(12) is abundant because sigma(12) = 1+2+3+4+6+12 = 28. However, it is not odd, so my method would not consider it. I can't figure out why my loop function isn't working , because when I try to input a range it spits up a bunch of number gibberish. Here's what I have so far:
import java.util.*;
public class OddAbundant {
static Scanner input = new Scanner(System.in);
public static void findOddAbundant(){
System.out.println("Please enter the start of the range you want to test for odd abundant integers");
int startRange = input.nextInt();
System.out.println("Please enter the end of the range you want to test for odd abundant integers");
int endRange = input.nextInt();
for(int b = startRange; b <= endRange; b++) {
if (Sigma.Sigma(b)<(b*2))
continue;
else{
if (b % 2 == 1)
System.out.println(b);
}
}
}
public static void main(String[] args) {
findOddAbundant();
}
}
I go through the loop and I can't figure out what's going wrong. I've tested the sigma method, which I can provide if it will help you guys, and it does spit out the correct value when given an integer. Thoughts?
Here is my sigma function:
import java.util.*;
public class Sigma {
static Scanner input = new Scanner(System.in);
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
System.out.print(a);
return a;
}
public static void main(String[] args) {
System.out.println("Please enter the number you want to perform the sigma function on");
int s = input.nextInt();
Sigma.Sigma(s);
System.out.print(" is the sum of all the divisors of your input" );
}
}
The silly problem it was; remove the print statement from Sigma function.
public static int Sigma(int s){
int a = 0;
for(int i=1;i<=s;i++){
if(s%i==0)
a = a + i;
}
System.out.print(a); //why do you have it here?
return a;
}

Categories