1,105,380 Community Members

Java homework

Member Avatar
djcrab
Light Poster
30 posts since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello. I'm hoping someone will be willing to help me out. I'm pretty much done except for one part I've been scratching my head over. I'm sure this headache I have is not helping. Below are the instructions and the code for my problem area.

Output the sum of all numbers between firstNum and secondNum exclusive. 

The portion im working on begins on line 52. Thank you for your time!

import java.io.*;
import java.util.*;
import java.text.*;

class A2{

    //user inputs and checks

    public static void main(String[] args) throws Exception{
        Scanner input=new Scanner(System.in);
        System.out.print("Enter Num1: ");
        int firstNum =input.nextInt();

        System.out.print("Enter Num2: ");
        int secondNum =input.nextInt();
        while(firstNum<0){
            System.out.print("Number should be positive.!Re-enter: ");
            firstNum =input.nextInt();
        }
        while(secondNum<0){
            System.out.print("Number should be positive.!Re-enter: ");
            secondNum =input.nextInt();
        }
        while(secondNum>1000){
            System.out.print("Second Number should be less than 1000!Re-enter: ");
            secondNum =input.nextInt();
        }
        while(secondNum<firstNum){
            System.out.print("Second Number should be at least 10 greater than firstNum.Re-enter: ");
            secondNum =input.nextInt();
        }

        int sum=0;

        //write new file always
        File f;
        f=new File("A2 OUTPUT.txt");
        BufferedWriter bw=new BufferedWriter(new FileWriter(f,false));

        bw.write("Odd numbers from "+Integer.toString(firstNum)+" to "+Integer.toString(secondNum)+",one number per line:");  //Odd numbers one per line
        bw.newLine();

            for(int i=firstNum;i<=secondNum;i++){
                sum+=i;
                if((i%2)!=0){
                    bw.write(Integer.toString(i));
                    bw.newLine();
                }
            }
            bw.newLine();

           //sum of all numbers excluding input values
                   bw.write("Sum of all numbers in between "+Integer.toString(firstNum)+ " and " +Integer.toString(secondNum)+":"+sum_between );  
                   for (int i=(firstNum+1);i < secondNum; i++) {
                    sum+=i;{
                        bw.write(Integer.toString(i));
                }}


            bw.newLine();
            bw.newLine();

           // all numbers in reverse order with comma separating
           bw.write("Output all numbers from "+Integer.toString(secondNum)+" to "+Integer.toString(firstNum)+":");  
            bw.newLine();

            for(int i=secondNum;i>=firstNum;i--){
                bw.write(Integer.toString(i)+",");
            }
            bw.newLine();
            bw.newLine();


           //date and time formatted
           Date d=new Date();     
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            bw.write(sdf.format(d));
            bw.close();
    }
}
Member Avatar
djcrab
Light Poster
30 posts since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Just saw this but "sum_between" is not at the end of line 53 anymore. I was trying something when I was stuck. That is blank at the moment.

Member Avatar
stultuske
Posting Expert
5,332 posts since Jan 2007
Reputation Points: 938 [?]
Q&As Helped to Solve: 776 [?]
Skill Endorsements: 35 [?]
Featured
 
0
 

what exactly are you having trouble with? it's easier to check what might be wrong if we know what we should be looking for.

Member Avatar
djcrab
Light Poster
30 posts since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I'm trying to get the mentioned part of the code to write the sum of all the numbers excluding the inputs (firstNum and secondNum)that are entered into the terminal by the user into a text document. I have everything working as is except for that portion. I have either gotten it to print the sum including the input numbers which I don't want or it prints the numbers in between the firstNum and secondNum w/o giving the sum. Here is the last text output I got.

Odd numbers from 1 to 11,one number per line:
1
3
5
7
9
11

Sum of all numbers in between 1 and 11:2345678910

Output all numbers from 11 to 1:
11,10,9,8,7,6,5,4,3,2,1,

2013-02-08 03:38:03
Member Avatar
stultuske
Posting Expert
5,332 posts since Jan 2007
Reputation Points: 938 [?]
Q&As Helped to Solve: 776 [?]
Skill Endorsements: 35 [?]
Featured
 
0
 

you're making your code way too dificult. just to print a value, you can use

System.out.print("value");

or

System.out.println("value"); // if you want a new line to be started.

so, if you want to print one number a line, println is the one you want.

just iterate over an int, value 1, while that int is less then 12, in that iteration,
print the int and add two to that int.

that's your first job done.

in your second part, you are just printing Strings and adding the number to it, there is no mathematical functionality there.

so, create an int, total, which you set to 0.

next, iterate (yet again) over an int, again, from 1, while the int is less than 12
just add the value of the int to your total variable, and end your iteration, by increasing your int with 1.

when this iteration ends: print the value of total, there you go.

Member Avatar
djcrab
Light Poster
30 posts since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

First off thank you for trying to help me. I'm trying to self teach after not messing with any of this stuff for a couple of years so please excuse my ignorance. Here is what I came up with that works for me when I run it. It works except for when it outputs the sum to the text file, it prints a line for each number that is between the inputs. If you compile/run and look at the output text file you will see what I mean.

I would like to take the multiple lines of text that say the same thing down to one. I've searched but could not find a command to do this.

I'm sure I am doing this the most awkward way possible so any more suggestions are welcome as well.

import java.io.*;
import java.util.*;
import java.text.*;

class HW2{

    //user inputs and checks

    public static void main(String[] args) throws Exception{
        Scanner input=new Scanner(System.in);
        System.out.print("Enter Num1: ");
        int firstNum =input.nextInt();

        System.out.print("Enter Num2: ");
        int secondNum =input.nextInt();
        while(firstNum<0){
            System.out.print("Number should be positive.!Re-enter: ");
            firstNum =input.nextInt();
        }
        while(secondNum<0){
            System.out.print("Number should be positive.!Re-enter: ");
            secondNum =input.nextInt();
        }
        while(secondNum>1000){
            System.out.print("Second Number should be less than 1000!Re-enter: ");
            secondNum =input.nextInt();
        }
        while(secondNum<firstNum){
            System.out.print("Second Number should be at least 10 greater than firstNum.Re-enter: ");
            secondNum =input.nextInt();
        }

        int sum=0;

        //write new file always
        File f;
        f=new File("A2 OUTPUT.txt");
        BufferedWriter bw=new BufferedWriter(new FileWriter(f,false));

        bw.write("Odd numbers from "+Integer.toString(firstNum)+" to "+Integer.toString(secondNum)+",one number per line:");  //Odd numbers one per line
        bw.newLine();

            for(int i=firstNum;i<=secondNum;i++){
                sum+=i;
                if((i%2)!=0){
                    bw.write(Integer.toString(i));
                    bw.newLine();
                }
            }
            bw.newLine();

           //sum of all numbers excluding input values
           int finalSum=0;
            for (int total=firstNum;total <= secondNum; total++) {
                int sumMinusFirstNum=sum-firstNum;
                finalSum=sumMinusFirstNum-secondNum;
                bw.write("Sum of all numbers in between "+Integer.toString(firstNum)+ " and " +Integer.toString(secondNum)+":  "+finalSum);
                bw.newLine();
                }


                bw.newLine();

           // all numbers in reverse order with comma separating
           bw.write("Output all numbers from "+Integer.toString(secondNum)+" to "+Integer.toString(firstNum)+":");  
            bw.newLine();

            for(int i=secondNum;i>=firstNum;i--){
                bw.write(Integer.toString(i)+",");
            }
            bw.newLine();
            bw.newLine();


           //date and time formatted
           Date d=new Date();     
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            bw.write(sdf.format(d));
            bw.close();
    }
}

Here is what the text file that is output shows. Notice the several lines of the same text. That is what I would like to take down to only one line.

Odd numbers from 1 to 11,one number per line:
1
3
5
7
9
11

Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54
Sum of all numbers in between 1 and 11:  54

Output all numbers from 11 to 1:
11,10,9,8,7,6,5,4,3,2,1,

2013-02-08 08:20:57
Member Avatar
bguild
Posting Whiz
339 posts since Oct 2012
Reputation Points: 163 [?]
Q&As Helped to Solve: 84 [?]
Skill Endorsements: 8 [?]
 
0
 

Those repeated lines are produced by this loop:

for (int total=firstNum;total <= secondNum; total++) {
    int sumMinusFirstNum=sum-firstNum;
    finalSum=sumMinusFirstNum-secondNum;
    bw.write("Sum of all numbers in between "+Integer.toString(firstNum)+ " and " +Integer.toString(secondNum)+": "+finalSum);
    bw.newLine();
}

I am curious to know why you have a loop if you want to write the line just once. A for loop is usually only used when someone wants to do something repeatedly, so I'd like to know what inspired you to use one in this case. I would never have guessed that the repeated line was unintentional from reading that loop.

Member Avatar
needhelp88
Newbie Poster
7 posts since Feb 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi djcrab,

I am not sure if this will help you but I recently wrote a program that reads in positive integers from keyboard input, and prints the order of the numbers, order in reverse, minimum, maximum, average, mean, mode, and median of the entire array.

It wouldn't be hard to get working for file i/o.

public class math {

    public static void main(String[] args) throws Exception {

      int count = 0;
      int sum = 0;
      int temp = 0;

      Scanner sc = new Scanner(System.in);

      int [] array = new int[500]; // create array of ints of size 500

      for(int i = 0; i < array.length; i++) // loop through the array
         {
            System.out.println("Enter a positive value" +
            " (a negative will cause the program to exit): ");
            array[i] = sc.nextInt();
            count++;
            System.out.println(" ");

            if(array[i] < 0) 
            {
               temp = array[i];
               array[i] = 0;
               break;
            }
        }

      if(temp < 0 && count == 1)
      {
         System.out.println("\nThanks for playing. Bye!");
         System.exit(0);
      }

      count = count -1; // subtract 1 from count (-1 will not be used)


      // Sort the array and print it to the screen
      Arrays.sort(array, 0, count);

      System.out.println("\nThe numbers in order are: ");
      for (int j = 0; j < count; j++) 
        {
            System.out.print(array[j] + " ");
        }


      // Print the array in reverse order
      System.out.println("\n\nThe numbers in reverse order are: ");
      for (int index = count-1; index >= 0; index--){
         System.out.print(array[index] + " ");
      }


      // Print the sum
      for(double nums : array)
         {
               sum += nums;
         }
      System.out.println("\n\nThe sum of all numbers is: " + sum);


      // Print the count
      System.out.println("\nTotal positive numbers entered: " + count);


      // Print the average value
      double average = sum/count;
      System.out.println("\nThe average is: " + average);


      // Print the max value
      System.out.println("\nMax value is: " + array[count-1]);


      // Print the min value
      System.out.println("\nMin value is: " + array[0]);


      // Get the median value
      if (count % 2 == 1)
         {
            int median = count / 2;
            System.out.print("\nMedian value is: " + array[median] + "\n");
         }
      else
         {
            int median = 0;
            median = array[median-1] + array[median] / 2;
            System.out.println("\nMedian value is: " + array[median] + "\n");
         }


      // Get the mode
         int mode = array[0];
         int m1 = 1;
         int m2 = 1;

         for(int i = 1; i < count; i++)
            {
               if(array[i-1] == array[i])
                  {
                        m1++;
                     }
               else
                  {
                        m1 = 1;
                  }

                 if(m1 > m2)
                  {
                        mode = array[i];
                        m2 = m1;
                  }

                 if(m1 == m2)
                  {
                     mode = -1;
                  }
            }

            if(mode == -1)
            {
                System.out.println("\nThere are multiple modes.");
            }
            else
            {
                System.out.println("\nMode value is: " + mode);
            }

    } // end main class

} // end math class

Of course it would be much neater to put all of the calculations into separate methods.

Member Avatar
djcrab
Light Poster
30 posts since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks for all the help everyone. I did finally get it to work with the for loop this way.

//sum of all numbers excluding input values
            for (int total=firstNum;total <= secondNum; total++) {
                int sumMinusFirstNum=sum-firstNum;
                finalSum=sumMinusFirstNum-secondNum;}
                    bw.write("Sum of all numbers in between "+Integer.toString(firstNum)+" and "+Integer.toString(secondNum)+" : "+finalSum );
                bw.newLine();       
                bw.newLine();

However, I ended up with this after bguild questioned my for loop and I gave it some thought.

//sum of all numbers excluding input values

            i = (firstNum + 1);
            while (i < secondNum) {
                sum += i;
                i++;
            }   
                bw.write("Sum of all numbers in between "+Integer.toString(firstNum)+" and "+Integer.toString(secondNum)+" : "+sum );
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article