简体   繁体   中英

Check if # is even or odd, then say how many terms there are and get a sum of all output values printed

This is for school and I'm having a bit of trouble with it. What the teacher wants us to do is this:

  • A count of the number of terms
  • A sum of all of the values

(REFER TO EXAMPLE BELOW IN THE EDIT)

The formula shown in the picture linked is already in the code. I'm having trouble trying to figure out how to do the two things listed above. I know the answer is probably obvious but I've tried everything I could think of so far.

EDIT: The initial purpose of the code is to input a number (via the scanner), and then use the two different formulas on that number until you finally have reached 1.

Example:

Input: 6

Output: 6, 3, 10, 5, 16, 8, 4, 2, 1

What I'm asking for help with:

Terms: 9

Sum: 55

import java.util.Scanner;

class Main {
  public static void main(String[] args) 
  {

    Scanner numInput = new Scanner(System.in);

    System.out.print("Number: ");
    int x = numInput.nextInt();
    int termAmt = 0;

    System.out.println(" ");
    System.out.print(x + " ");

    while (x != 1)
    {
// Checking if number is odd or even
      if ( (x % 2) == 0 ) 
      { 
       // This is the formula for if the number is even
        x = x / 2;
        System.out.print(x + " "); 
      } 

      else 
      { 
// This is the formula for if the number is odd
        x = (x*3) + 1;
        System.out.print(x + " "); 

      }  
    }

    System.out.println(" ");
    System.out.println(" ");

// This is here for when I print out how many terms are printed in the output

    System.out.println("Terms: " + termAmt);


  }
}

Try this update to your code:

import java.util.Scanner;

class Main {
public static void main(String[] args) 
{

Scanner numInput = new Scanner(System.in);

System.out.print("Number: ");
int x = numInput.nextInt();
int value = x;
int termAmt = 1;
int sum = 0;
System.out.println(" ");
System.out.print(x + " ");

while (x != 1)
{
  if ( (x % 2) == 0 ) 
  { 
    x = x / 2;
    System.out.print(x + " "); 
  } 

  else 
  { 
    x = (x*3) + 1;
    System.out.print(x + " ");

  }  
 /*Update starts*/
    //This next line adds one to the termAmt value each time it goes through the loop.
 termAmt = termAmt + 1;
 sum = sum + x;
}
sum += value; 

System.out.println(" ");
System.out.println(" ");

System.out.println("Terms: " + termAmt);
System.out.println("Sum: " + sum);
sum = 0;

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM