Simple Java way to input decimal and round to nearest integer - java

I am using the Java SDK to compile. Need I say, I am a beginner.
Here is the code I tried to use to "Ask user to input decimal and code should output an integer. (round to nearest integer)
import java.util.*;
public class readDecimal {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println(“Please enter a decimal number:“);
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
“ rounded to the nearest integer is “ + intNumber);
}
}
What am I doing wrong? I saw the other posts however they seem much to complicated for a beginner. Can you please help?
Thank you,
Diane

Your quotation marks are incorrect; they are unicode for some reason. Replace all the quotations by manual typing them in, in you System.out.println statements.
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double decimalNumber;
long intNumber;
System.out.println("Please enter a decimal number:");
decimalNumber = input.nextDouble();
intNumber = Math.round(decimalNumber);
System.out.println(decimalNumber +
" rounded to the nearest integer is " + intNumber);
}

You can round double numbers using Math.round method.
import java.util.*;
public class RoundingDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
double num1;
double num2;
System.out.print("Please enter a decimal number: ");
num1 = sc.nextDouble();
num2 = Math.round(num1);
System.out.println(" Rounded to the nearest integer is " + num2);
}
}

Related

scanner skips double type numbers

Hello I'm new in java and as i was making a program practicing input/output methods I came to this error:
When I input a int value the program works well, but when I input a double value it shows me this:
Here is my code:
import java.util.Scanner;
public class InpOutp
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); // creates a scanner
System.out.print("Enter price of a six-pack beer: ");
double packPrice = in.nextDouble();
System.out.print("Give the ml of a can: ");
double canMl = in.nextDouble();
final double CANS_PER_PACK = 6;
double packMl = canMl * CANS_PER_PACK;
// find the price per ml of a pack
double pricePerMl = packPrice / packMl;
System.out.printf("Price per ml: %8.3f", pricePerMl);
System.out.println();
}
}
The problem is the separator. If you wish to use period try this
Scanner in = new Scanner(System.in).useLocale(Locale.US);
EDIT:
Also it is worth to mention, you should use in.nextLine();
after every nextInt() or nextDouble() otherwise you will encoder problems with nextLine when entering text.
Try this
System.out.print("Enter price of a six-pack beer: ");
double packPrice = in.nextDouble();
System.out.println("this will be skipped" + in.nextLine());
System.out.print("Give the ml of a can: ");
double canMl = in.nextDouble();
in.nextLine();
System.out.print("And now you can type: ");
System.out.println(in.nextLine());
The fault was that I was typing the values with . (5.4) and I should type them with , (5,4).

how do you deal with Exception in thread "main" java.util.NoSuchElementException?

i still new at coding, and i am wonder if anyone could help me with java code.
additionally, explaining how to deal with this issue.
here is my code below:
import java.util.Scanner;
public class SumAverage {
public static void main(String[] args) {
// create a Scanner to obtain input from the command window
Scanner input = new Scanner(System.in);
int number1, number2, sum;
System.out.print("Enter first integer: "); // prompt
number1 = input.nextInt(); // read 1st number from user
System.out.print("Enter second integer: "); // prompt
number2 = input.nextInt(); // read 2nd number from user
sum = number1 + number2;
double average = (double) sum / 2;
String message = "Sum is";
System.out.printf("%s %d\n", message, sum);
System.out.printf("Average is %.2f\n", average);
} // end main method
} // end class SumAverage

How do you find the average of three numbers with input and output dialog boxes with JAVA?

I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{
public static void main(String[] args)
{
System.out.println("Enter 3 numbers: ");
Scanner input = new Scanner (System.in);
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1=input.nextInt();
num2=input.nextInt();
num3=input.nextInt();
avg=(double)(num1+num2+num3)/3.0;
System.out.println("The average is: " + decimalFormat.format(avg));
}
}
I don't know what you find hard here. I think you are looking for this:
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1"));
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2"));
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3"));
avg=(double)(num1+num2+num3)/3.0;
JOptionPane.showMessageDialog(null, "The average is: " + decimalFormat.format(avg));
Please note that this code could be written better but for the sake of answering I just replaced the JOptionPane in your code where you need them.
It's really not that much harder. On the input side, using one of the showInputDialog(...) methods of JOptionPane is almost an exact replacement for input.nextInt();. The only difference it that showInputDialog(...) returns the user's input as String, not an int, so you'll have to use Integer.parseInt to convert the returned String into an int. As for the output, showMessageDialog(...) is an almost exact replacement for System.out.println(...); just use the --- as the message text argument.
public static void main(String[] args) {
int num, count=0;
double total =0, avg;
for(int i = 1; i <= 3; i++){
num = Integer.valueOf(JOptionPane.showInputDialog("Enter number "+ count++));
total += num;
}
avg = total / count;
JOptionPane.showMessageDialog(null, "The average is: " + (double)Math.round(avg * 100) / 100);
}
/*
*AverageOfThreeNumnber.java
*calculating the Average Of Four Numnberand diaply the output
*using JOptionpane method in java
*/
import javax.swing.JOptionpane;
public class AverageOfThreeNumbers {
public static void main(String[] args) {
int fristNumber; // FRIST INTEGER NUMBER
int SecondNumber; // SECOND INTEGER NUMBER
int ThridNumber; // THRID INTEGER NUMBER
int sum; // SUM OF THE FOUR INTEGER NUMBERS
double avarage; // AVERAGE OF THE FOUR NUMBERS
String input; // INPUT VALUE
String result; // OUTPUT GENERATING STRING
// ACCEPT INTEGER NUMBERS FROM THE USER
input = JOptionpane.showInputDialog(null, "Enter frist nmuber: ");
FristNumber=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Second nmuber: ");
SecondNumberr=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Thrid nmuber: ");
ThridNumber=Integer.parse.Int(Input);
//CALCULATE SUM
sum = fristNumber + SecondNumber + ThridNumber;
//CALCULATE AVERAGE
average = sum/4.0
//BUILD OUTPUT STRING AND DISPLAY OUTPUT
result = "Average of" + fristNumber + ", " + SecondNumber + " And " + ThridNumber +" is = " + average;
JOptionpane.showMessageDialog(null, result, "Average of 3 Numbers", JOptionpane.INFORMATION_MESSAGE);
}
}

BigDecimal Method returns vague results, why does this happen?

Code:
package tk.vivekpatani.www;
import java.math.BigDecimal;
import java.util.Scanner;
public class SimpleCalc {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
try{
System.out.println("Welcome to the Calculator!");
System.out.println("Enter Number 1:");
double num1 = sc.nextDouble();
System.out.println("Enter Number 2:");
double num2 = sc.nextDouble();
BigDecimal bd1 = new BigDecimal(num1);
BigDecimal bd2 = new BigDecimal(num2);
BigDecimal result = addition(bd1,bd2);
System.out.println("Result:"+result.toString());
}
finally{
sc.close();
}
}
static BigDecimal addition(BigDecimal input1, BigDecimal input2){
BigDecimal result = input1.add(input2);
return result;
}
}
Results:
Welcome to the Calculator!
Enter Number 1:
90
Enter Number 2:
10.2
Result:100.199999999999999289457264239899814128875732421875
I'm using Eclipse IDE Mars and Java 1.8.
The double can't handle 0.2 properly due to the precision it uses.
Try doing this instead to create the numbers, you need to construct the BigDecimal using the Strings so that you don't carry over the double precision issue.
System.out.println("Enter Number 1:");
String num1 = sc.nextLine();
BigDecimal bd1 = new BigDecimal(num1);
System.out.println("Enter Number 2:");
String num2 = sc.nextLine();
BigDecimal bd2 = new BigDecimal(num2);
Quoting the javadoc of the BigDecimal(double) constructor:
The results of this constructor can be somewhat unpredictable. [...] When a double must be used as a source for a BigDecimal, [...] use the static valueOf(double) method.
So, always use BigDecimal.valueOf(double), never new BigDecimal(double).
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number 1: ");
double num1 = sc.nextDouble();
System.out.print("Enter Number 2: ");
double num2 = sc.nextDouble();
BigDecimal bd1 = BigDecimal.valueOf(num1);
BigDecimal bd2 = BigDecimal.valueOf(num2);
System.out.println("Result: " + bd1.add(bd2));
Output
Enter Number 1: 90
Enter Number 2: 10.2
Result: 100.2

Input and Output in Java

I have been asked to create a simple input output code for a training exercise in a new job using Java. I am a complete novice with Java so therefore I have hit a bit of a wall. This is my current code...
import java.util.*;
public class Task3
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
{
int Number1;
int Number2;
int Number3;
int Sum;
Number1= console.nextInt();
Number2= console.nextInt();
Number3= console.nextInt();
Volume = Number1 * Number2 + Number3 ;
}
System.out.printIn("Answer:" + Sum ) ;
}
}
Effectively I want this code to read 3 numbers as input from the user and then produce the sum of Number1 x Number2 + Number3 as output. I'm sure there are a few ways to do this but the way I have started above is the way we have been asked to do it. Any help would be much appreciated as I am keen to learn more about this and where I am having trouble... Thanks in advance, John
Check this:
import java.util.*;
public class MyJavaProgram
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int number1 = console.nextInt();
int number2 = console.nextInt();
int number3 = console.nextInt();
System.out.println("Volume = "+ ((number1 * number2) + number3));
}
}
Changes from your code:
Removed a set of brackets which were creating a local scope where Sum was defined, yet you were trying to use Sum outside of that local scope
Variable defined as Sum but then referred to as Volume; I assume this was a copy & paste error.
Just for adding three numbers. Program should be
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
int num1= s.nextInt();
int num2= s.nextInt();
int num3= s.nextInt();
System.out.println("Sum= "+ (num1+ num2+num3));
// or play any game with those variables here
}
You are adding extra {} and variables without any use.Get rid off those.

Categories