This discussion is archived
9 Replies Latest reply: May 2, 2007 6:49 PM by 807599

# Squaring and summing a sequence of numbers

Currently Being Moderated
I really need some help here. I just can't figure this out. I really would like to get some help from somebody since I can't get it from my school.

Here's what I have to code...
*Output all results to a file, placing an appropriate label between each section of output.
*Output all Odd numbers numbers between firstNum and secondNum.                              can't get on one line
*Output the sum of all even numbers between firstNum and secondNum.                               This is done.
*Output the numbers and their square between firstNum and secondNum.                              can't figure out
*Output the sum of the squares of the odd numbers between firstNum and secondNum                       can't figure this out at all

Here's my code...can anyone assist me please. My head is exploding.

import java.util.*;

public class example
{
static Scanner console = new Scanner(System.in);

public static void main(String[] args)
{
int firstNum;
int secondNum;
int counter;
int evenNumbers = 0;
int oddNumbers = 0;
int oddSum =0;
int evenSum = 0;
int counter2 = 0;

System.out.println("Enter your first number?"); System.out.flush();
while (console.hasNext())
{
firstNum = console.nextInt();
System.out.println("Enter your second number?");
System.out.flush();
while (console.hasNext())
{
secondNum = console.nextInt();
if (firstNum > secondNum)
{
System.out.println("First number can't be larger than second number, try again.");
break;
}
else
{
System.out.println("Odd numbers between " + firstNum + " and " + secondNum + " are:");
}
for (counter = firstNum + 1; counter < secondNum; counter++)
{//start for

switch (counter % 2)
{//start switch

case 0: ++evenNumbers;
evenSum = evenSum + counter;
System.out.println(counter); break;

case 1: ++oddNumbers;
System.out.print(counter + " ");
oddSum = oddSum + counter;
break;

case -1: ++oddNumbers;

default: System.out.println (); break;
}//end switch

}//end for

System.out.println();
System.out.println("There are " + evenNumbers + " even numbers, " + "and odd numbers are " + oddNumbers);
System.out.println("The sum of all odd numbers are " + oddSum + " .");
System.out.println("The sum of all even numbers are " + evenSum + " .");

}//end while secondNum

}//end while firstNum

}//end main
}

Here is my output on the above code.
Enter your first number?
1
Enter your second number?
7
Odd numbers between 1 and 7 are:
2
3 4
5 6

There are 3 even numbers, and odd numbers are 2
The sum of all odd numbers are 8 .
The sum of all even numbers are 12 .
• ###### 1. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
*Output all results to a file, placing an appropriate label between each section of output.
You should send the output to a file, not the console.
So, don't use System.out.println

*Output all Odd numbers numbers between firstNum and secondNum. can't get on one line
You can use a Vector or ArrayList to store every element and output it once you find all the elements.
You can't make it on one line because you print it out immediately whether it is even or odd.

*Output the sum of all even numbers between firstNum and secondNum. This is done.
So, you should have no problem on this.

*Output the numbers and their square between firstNum and secondNum. can't figure out
As I have mentioned above, you could use a Vector or ArrayList to store all this number and you should know how to find the squares of these numbers.

*Output the sum of the squares of the odd numbers between firstNum and secondNum can't figure this out at all
Same as above.
If you can't make it, post the code with code tags and ask.
To make your code more readable, you should break down the problem into smaller pieces (i.e. one method for one problem)
• ###### 2. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
hi,

look at this code and adapt i to your needs:
``````import java.io.PrintWriter;

public class TestSquareSum {

public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };//change this => input from user using scanner

int firstNum = 2;//change this => input from user using scanner
int secondNum = 8;//change this => input from user using scanner

PrintWriter pw;

try {

pw = new PrintWriter("D:/results.txt");////change this, choose the file you want
computeOddNumbers(a, firstNum, secondNum, pw);
computeSumEvenNumbers(a, firstNum, secondNum, pw);
computeSquareNumbers(a, firstNum, secondNum, pw);
computeSquareOddNumbers(a, firstNum, secondNum, pw);

} catch (Exception e) {
e.printStackTrace();
}

}

private static void computeSquareOddNumbers(int[] a, int firstNum, int secondNum, PrintWriter pw) {
pw.println("computeSquareOddNumbers start...");
double sum=0;
for (int i = 0; i < a.length; i++) {
if (a[i] >= firstNum && a[i] <= secondNum) {
if(a%2!=0){//only odd number
sum+=Math.sqrt(a[i]);
}
}
}

pw.println("sum="+sum);
pw.println("computeSquareOddNumbers end.");

}

private static void computeSquareNumbers(int[] a, int firstNum, int secondNum, PrintWriter pw) {
pw.println("computeSquareNumbers start...");
for (int i = 0; i < a.length; i++) {
if (a[i] >= firstNum && a[i] <= secondNum) {
pw.println(a[i]+", Square="+Math.sqrt(a[i]));
}
}
pw.println();
pw.println("computeSquareNumbers end.");

}

private static void computeSumEvenNumbers(int[] a, int firstNum, int secondNum, PrintWriter pw) throws Exception {
pw.println("computeSumEvenNumbers start...");
int sum = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] >= firstNum && a[i] <= secondNum) {
if (a[i] % 2 == 0) {// only even number
sum+=a[i];
}
}
}
pw.println("sum="+sum);
pw.println("computeSumEvenNumbers end.");

}

private static void computeOddNumbers(int[] a, int firstNum, int secondNum, PrintWriter pw) throws Exception {
pw.println("computeOddNumbers start...");
for (int i = 0; i < a.length; i++) {
if (a[i] >= firstNum && a[i] <= secondNum) {
if (a[i] % 2 != 0) {// only odd number
pw.print(a[i] + " ");
}
}
}
pw.println();
pw.println("computeOddNumbers end.");
}

}

Hope That Helps ``````
• ###### 3. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
Never mind

Message was edited by:
rym82
• ###### 4. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
Thank you all for helping out. Most of the code provided was a bit more advanced. One thing I forgot to mention was I had to use a while loop. Here is what I finally came up with. If you see something wrong, please let me know. Also I need your opinions of how you like the code. This is a beginners class that I'm taking, but I have programming experience. Also thanks for the advice. Hope this works.
``````import java.util.*;
import java.io.*;

public class countingnumbers
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{

//decaring and initializing variables
int firstNum;            // var for first number
int secondNum;           // var for second number
int oddSqr=0;            // var to calculate squaring Odd numbers
int counter;             // loop counter
int evenNumbers = 0;     // var even numbers within 1st and 2nd number
int oddNumbers = 0;      // var odd numbers within 1st and 2nd number
int oddSum =0;           // var sum of odd numbers
int evenSum = 0;         // var sum for even numbers
int sumOddSqr = 0;       // var sum of squared odd numbers

System.out.println();
System.out.println("This program will will provide various information between");
System.out.println("two whole numbers you provide.");
System.out.println();
System.out.println("Enter your first number?"); System.out.flush();
while (console.hasNext())
{
firstNum = console.nextInt();
System.out.println("Enter your second number?");
System.out.flush();
while (console.hasNext())
{
secondNum = console.nextInt();
if (firstNum > secondNum)
{
System.out.println();
System.out.println("Sorry, but first number can't be larger than second number, try again.");
System.exit(0);
}

else

if (firstNum < secondNum)
{
PrintWriter outFile = new PrintWriter("c:\\test.txt");
outFile.println();
outFile.println("Below are the numbers between " + firstNum + " and " + secondNum + " and their square.");

for (oddSqr = firstNum + 1; oddSqr < secondNum; oddSqr++)
{
outFile.println( oddSqr + " - " + (oddSqr*oddSqr));
outFile.println();
outFile.println("Odd numbers between " + firstNum + " and " + secondNum + " are:");
}

for (counter = firstNum + 1; counter < secondNum; counter++)
{
//start switch case
switch (counter % 2)
{

case 0: ++evenNumbers;
evenSum = evenSum + counter; break;

case 1: ++oddNumbers;
outFile.print(counter + " ");
oddSum = oddSum + counter;
outFile.println(); break;
default: outFile.println (); break;
}//end switch

}//end for
for (counter = firstNum + 1; counter < secondNum; counter++)
{
if(counter%2!=0)
{
sumOddSqr = sumOddSqr + (counter*counter);
}
}
outFile.println();
outFile.println("Sum of Odd Numbered squares is: ");
outFile.println(sumOddSqr);
outFile.println();
outFile.println("The sum of all even numbers is: ");
outFile.println(evenSum);
outFile.close();
System.out.println();
System.out.println();
System.out.println("Thank you for using my program, your results will be located in");
System.out.println("                   c:\\test.txt");
System.exit(0);
}
}//end while secondNum
}//end while firstNum
}//end main
}``````
• ###### 5. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
If you think people have helped you, you should assign duke star to them.

Your program should run fine (I guess). But it could be better.
So, here are the comments:
1) Proper indentation make codes more readable and traceable. Use 4 spaces instead of hitting the TAB button (a matter of taste, but i found it better).
2) When you import classes, don't use java.io.*. Only import the classes you needed. It would be easier to follow and should have better performance.
3) Class Name should be in CamelCase. (i.e. CountingNumbers in your case)
4) It would be better to break down your problem in small piece of problems. As checking 1st and 2nd numbers are similar, you should use 1 method to handle.

Here will be more useful in your future, you may not see the benefits now.
5) If you develop a large application, you would write a technical documentation about the classes and methods. If you use javadoc, it saves your time.
6) Use standard coding style consistence within the team.
• ###### 6. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
with all due respect i don't think your program solves the given problem .... please run it and check the sample output ,

for example if the start and end numbers were say 5 and 10 then your output would be
6 - 36
7 - 49
8 - 64
9 - 81

odd numbers
7 9

sum of squares of odd numbers
130

sum of even numbers
14

I think "java_2006"'s program would be accurate .

If using while loop is a compulsion then you can simply check for the terminal condition as follows
``````number=firstnumber+1;
while(number<second number){
if(number%2==0)
else{
sqauresum();
}
number++;
}``````
I haven't elaborated on the code because java_2006's code is already here.
• ###### 7. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
Flummoxed,

The program does resolve my problem as your sample is what I was looking for. I fixed all the errors as I did pass the assignment. Thanks though. I don't know what java_2006 is about and didn't understand about "it's already here". I'm using what's out of the book. The code you provided is not used within my chapters, so it wouldn't be appropriate to use. However, I did understand a little of your meaning of use.
Thank you.
• ###### 8. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
Now I know what you meant by Java_2006. Sorry Java_2006, I didn't realize it was you that posted the code.
• ###### 9. Re: Squaring and summing a sequence of numbers
Currently Being Moderated
2) When you import classes, don't use java.io.*. Only import
the classes you needed. It would be easier to follow and should
have better performance.
It may be fractionally easier to follow, but the only performance gain is going to be a few nanoseconds at compile time.