Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Brand new to Java and programming

1. ## Brand new to Java and programming

As part of my homework, actually this part is for extra credit. I am supposed to write a program that prompts the user to input a decimal number and outputs the number to the nearest integer. Using only things I have learned to this point. I couldn't figure it out. I read ahead in the book about if else statements and came up with the following, but is there a way to do it with out if, else statements?(I am only 1 week into this class, so I can't use anything like the Math round method. I am supposed to do this programmatically):

```//Chapter 2 programming exercises 6.)

import java.util.*;

public class Ch2_PrExercises6
{
public static void main(String[] args)
{
Scanner tv = new Scanner(System.in);

int numResult = 0;
double numEntered;

System.out.println("Enter in a decimal number to be rounded to the nearest whole number, then press Enter: ");
System.out.println();

numEntered = tv.nextDouble();

if(numEntered % 1 >= (1/2))
{
numResult = (int)(numEntered) + 1;
}

else
{
numResult = (int)(numEntered);
}

System.out.println("You number rounded to the nearest whole number = " + numResult);

}
}```

2. ## Re: Brand new to Java and programming

I can't use anything like the Math round method
Odd you can't use Math.round() :p
If you want your current method to work, replace (1/2) with 0.5;

Edit: Rewrote post

3. ## Re: Brand new to Java and programming

replace (1/2) with 0.5 because 1/2 will be computed using integer arithmetic and gives a result of 0

4. ## Re: Brand new to Java and programming

is there a way to do it with out if, else statements?
Yes, you can do it with a little bit of arithmetic and the fact that floating->int conversion discards the fractional part. Think of simple arithmetic that converts .5 and greater fractional parts to 1.0 or greater, but not to 2.0!