how do you find the sum of a sequence in Java - java

I really don't understand how to find the sum of a sequence in Java. For instance, the program will ask for the input of the first and last number of the sequence and add the sum of the sequence(3 + 4 + 5 = 12). My System.out.println() isn't working as well. Why is this?
import java.util.Scanner;
public class SumOfASequenceTheSequel {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("First number?");
int first = Integer.valueOf(scanner.nextLine());
System.out.println("Second number?");
int second = Integer.valueOf(scanner.nextLine());
int sum = 0;
int i = first;
while (i <= second) {
sum = sum + i;
i = i++;
}
System.out.println("The sum is " + sum);
}
}

i = i++; This statement is incorrect. Because you used post incremental. In this statement first assign i's value to i after increment value. but i's value not changes. Then this while loop become infinity loop. So you need remove assignment part and only need i++;. Also you can use pre incremental (++i;). If you use pre incremental, then i = ++i; statement fine. But value assignment is not need.
If you can replace while loop using for loop, then you don't meet this problem. For loop solution below. Below Code sum += i; equals to sum = sum + i
for (int i = first; i <= second; i++) {
sum += i;
}

i++; is called Post Increment equal to i = i + 1; So you just need i++;, not i = i++;.

As others have pointed out, because you are doing post-increment and assignment in the same statement, (i = i++;), your program is running in an infinite loop.
You might want to change it to either a pre-increment assignment (i = ++i;) or even better a plain pre or post increment (i++;).
Look at this link to understand the difference between pre and post increment operators.
I will recommend a for loop instead of while loop for better readability. See the following snippet:
for(int i = first; i <= second; i++) {
sum = sum + i;
}
If you like Stream API instead of traditional loops, you can also print the sum the following way:
System.out.println("The sum is " + IntStream.rangeClosed(first, second).sum());
On a side note, you might want to close the Scanner resource after you are done using it to avoid resource leak, like so: scanner.close();

Related

How do I create a program that calculates the sum of a set of numbers (Java)?

I'm learning Java from a MOOC and am stuck on this one exercise:
Really having trouble with this one. I'm able to create a program that counts up to the user's chosen number (below) but stuck on how to add all the numbers up to variable n.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int start = 0;
System.out.println("Until which number? ");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Counting begins now...");
while (start <= (n - 1)) {
System.out.println(start += 1);
}
}
Any help is appreciated.
You on the right track, firstly to get input on the same line (like in the expected output of your task) use print rather than println.
Then basically just keep track of two "helper" variables count and sum and only print the value of the variable sum once outside the while loop:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Until what?");
int n = scanner.nextInt();
int count = 0;
int sum = 0;
while(count <= n) {
sum += count; // increment the sum variable by the value of count
count++; // increment the count variable by 1
}
System.out.println("Sum is " + sum);
}
}
N.B. Also above I have made use of the Scanner method nextInt() rather than your Integer.parseInt solution, in the future you may want to look into pairing this with hasNextInt() that returns a boolean to ensure your program does not crash if the user inputs something other than an Integer.
Example Usage 1:
Until what? 3
Sum is 6
Example Usage 2:
Until what? 7
Sum is 28
Try it here!
int sum = 0;
while (start <= n) {
sum += start;
++start;
}
System.out.println(sum);
According to your guidelines you need to keep a record of the number of iterations start and you need to calculate the sum stored in its own variable sum.
start needs to increment every iteration
sum needs to be its previous value plus the current value of start

Subtraction using while loop Java

So i'm trying to write a programme whereby the user enters two integers .
The programm is supposed to subtract 5 from the second integer entered in a loop depending on the first number entered. (so the first number should dictate how many times it will loop.
public int getScheme1() {
while (Mark >= 20) {
System.out.printf((Mark = Mark - 5) + Mark + " ");
}
for (int Day = 1; Day <= 20; Day++) {
System.out.printf("( " + Day + "):" + Mark + " ");
}
return Mark;
}
All my code does is print the user's second input integer 20 times.
Also im sorry im totally new to java
you must call this function in your main program.
public int getScheme1 (int num1, int num2){
for(int i = 1 ; i >= num1 ; i++ ){
num2 -= 5;
}
return num2;
}
to call it simply use getScheme1(num1,num2);
Based on what you described, you are looking for something like this:
Scanner input = new Scanner(System.in); //create a scanner to get user input
int a1 = input.nextInt(); //get 2 ints from the user
int a2 = input.nextInt();
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies
a2-=5; //subtract 5 from a2 each time it loops
}
System.out.println(a2);
The key part of this is the for loop, which works in the following:
for(variable; condition; increment),
basically, what the for loop I wrote is saying:
Set i = 0 at the start. If i is meeting the condition (in this case being less then a1), then loop. The increment part is called when it finishes running the code block, it now makes i bigger (in this case 1 bigger using ++) Another important thing to note is that the first time the loop runs, i = 0.
So for example, if I wanted to loop 10 times, with a starting variable of 3 and incremented 5 each time, I'd do:
for(int i = 3; i <= 53; i+=5) {}
Also, one last thing: please look at variable naming conventions, variables shouldn't start with caps like that, they should be camelCase

Print sum of unique values of an integer array in Java

I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;

Java Double Array

I'm having trouble setting up and placing values into an array using a text file containing the floating point numbers 2.1 and 4.3 each number is separated by a space - below is the error I'm getting:
Exception in thread "main" java.util.NoSuchElementException
import java.util.*;
import java.io.*;
public class DoubleArray {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("mytestnumbers.txt"));
double [] nums = new double[2];
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++;
nums[index] = in.nextDouble();
}
}
}
Thanks, I'm sure this isn't a hard question to answer... I appreciate your time.
You should always use hasNext*() method before calling next*() method
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[1] = in.nextDouble();
}
}
but I think you are not doing the right, I'd rather
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[counter] = in.nextDouble();
}
}
NoSuchElementException is thrown by nextDouble method #see javadoc
I would suggest printing the value of index out immediately before you use it; you should spot the problem pretty quickly.
It would appear you're not getting good values from your file.
Oli is also correct that you have a problem with your index, but I would try this to verify you're getting doubles from your file:
String s = in.next();
System.out.println("Got token '" + s + "'"); // is this a double??
double d = Double.parseDouble(s);
EDIT: I take this partly back...
You simply don't have tokens to get. Here's what next double would have given you for exceptions:
InputMismatchException - if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
I did not understand what you are trying to do in your loop ?
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++; <--------
nums[index] = in.nextDouble();
}
You are declaring index = 0 then incrementing it to 1 and then using it.
Why are you not writing int index = 1; directly ?
Because it is getting declared to be zero each time loop is run and then changes value to 1.
Either you should declare it out side the loop.
You should initialize index outside of your for loop.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
index++;
nums[index] = in.nextDouble();
}
Your index was getting set to zero at the beginning of each iteration of your for loop.
EDIT:
You also need to check to make sure you still have input.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
if(!in.hasNextDouble())
break;
index++;
nums[index] = in.nextDouble();
}
Every time the cycle does an iteration, it's declaring the variable index and then you increase index with index++. Instead of using index, use counter, like this: num [counter] = in.nextDouble().
Check your mytestnumbers.txt file and ensure that the data that you are trying to scan is in the correct format. The exception that you are getting implies it is not.
Keep in mind that in.nextDouble() will be searching for double numbers separated by white space. In other words, "4.63.7" is not equal to "4.6 3.7" — the space is required. (I do not remember off the top of my head, but I believe that nextDouble() will only search for numbers containing a decimal point, so I do not believe that "4" is equal to "4.0". If you are seeking decimal numbers with this method, then you should have decimal numbers in your file.)

not a statement error, illegal start of type

import java.util.*;
public class ulang {
public static void main(final String[] args) {
int a;
int b;
int sum;
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
a = in.nextLine();
System.out.println("Enter num 2: ");
b = in.nextLine();
{
sum = a + b;
}
for (i = 0; i < 5; i++) {
(sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}
}
}
I'm weak on looping especially in Java. So I need some corrections on my coding, but I have no idea how to fix it.
The coding should run like this: User need to insert 2 numbers and the program will calculate the sum of both number. After that, the program will determine if the total of sum is >=10 or <10. If the sum >=10, "Congratulations" will appear but if it is <10, then "The sum of number less than 10" will appear. How to fix it?
This is the immediate problem:
(sum>=10)
I believe you meant that to be an if statement:
if (sum>=10)
Additionally:
You're trying to use an in variable, but the Scanner variable is called scan
Scanner.nextLine() returns a String - I suspect you wanted Scanner.nextInt()
Your for loop uses a variable that hasn't been declared. You probably meant:
for (int i = 0; i < 5; i++)
A few other suggestions though:
The sum isn't going to change between the loop iterations... why are you looping at all?
You've got a new block in which you're calculating the sum, but for no obvious reason. Why?
It's generally a good idea to declare variables at the point of initialization, e.g.
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
int a = scan.nextInt();
System.out.println("Enter num 2: ");
int b = scan.nextInt();
int sum = a + b;
Given that you want to take the same basic action (writing a message to the screen) whether or not the user was successful, you might consider using the conditional operator like this:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
System.out.println(message);
That would then allow you to refactor the loop to only evaluate the condition once:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
for (int i = 0; i < 5; i++)
{
System.out.println(message);
}
(sum>=10)
This line needs an if at the beginning, or it won't be read as a branch.
if (sum >= 10)
You also should name your main-class Ulang, because java class identifiers should start with an upper case letter, for readability.
The loop should look like the following:
for (int i = 0; i < 5; i++) {
The first part defines the counter and assigns zero to it. The second is your condition and the last counts for you.
for (int i = 0; i < 5; i++) {
if (sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}

Categories

Resources