Scanner Class Error For Decimal Values (double / Float)

Apr 23, 2014

I'm not getting why my program is giving error.

package rockjava;
import java.text.NumberFormat;
import java.util.Scanner;
public class file4 {
public static void main(String[] args)

[Code] ....

Please Input Num of Pods + Num of Keys= 20.5
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at alijava.file4.main(file4.java:14)

(It is not accepting double values. However working fine for integers.)

View Replies


ADVERTISEMENT

Difference Between Big Decimal And Float / Double And Benefits

May 28, 2014

I've recently came into reading that term big decimal, but I still don't fully understand what the benefit it is or why wouldn't you just use double and say have the program stop after a certain range?

View Replies View Related

Compilation Error Type Mismatch - Cannot Convert From Double To Float

Apr 20, 2014

I have a simple doubt

float k = 0;
k+=0.2;
k=k+0.2; // here compilation error

compliation error Type mismatch: cannot convert from double to float

My question is why not a complilation error at k+=0.2;

View Replies View Related

Converting From A Vector Containing Big Decimal To A Float

Mar 13, 2015

I'm having extreme difficulty in working with a Vector storing a column with a BigDecimal value, and converting that single value into a float. I'm not sure why the code was written this way, but basically, I'm working with something called a vector that has a single Big Decimal value/column (not sure what the correct terminology is), and I want to store that value in a float variable called "dp". However, I don't know how to convert from the Big Decimal to a float.

Code is below:

String s = "";
sql = "SELECT DiscountPercentRate FROM Attendees WHERE AttendeeId=" + attendeeId;
  Vector v2 = sqldb.getResults(sql); /*I know that sqldb.getResults(sql) returns a vector with a single BigDecimal column of 15.0, in the test example I'm using*/
if (!v2.isEmpty()) {
Vector data2 = (Vector)v2.elementAt(0);
if (!data2.isEmpty())

[Code] .....

In case you're wondering what the sqldb.getResults() method looks, like, here's a snippet of it - There's an else statement that triggers in my case, adding a BigDecimal column to a vector, and returns that vector.

Vector v = new Vector();
...
else {
BigDecimal bd = rs.getBigDecimal(i);
vCols.add(bd);
}
v.add(vCols);
...
return v;

How can I take the single result of my SQL query in that Vector/Big Decimal thing, and turn that result into a float value?

View Replies View Related

Populating ArrayList Using Scanner Class Logic Error

Sep 12, 2014

My code runs and populates an arraylist. However my break statement, while stopping the loop ends up being added to the arraylist. And I'm not sure how to fix this error.

public static void main(String args[]) throws Exception
{
// declaring variables
String input = "";
// creating array list
ArrayList<String> nameList = new ArrayList<String>();

[Code] ....

View Replies View Related

What Is Difference Between Float And Double

Jan 31, 2011

What is the difference between float and double?

View Replies View Related

Java API - Truncate Float Part Of Double Variable

Jan 13, 2015

Is there a method in Java API that truncate the float part of a double variable after a given number of digits?

Example: if the number of digits to be truncated is 2, so the method truncate (6.9872) to (6.98) ,

I tried to write a method that do that but it was very difficult.

View Replies View Related

String To A Double In Scanner - Performing Calculation?

Apr 23, 2015

This may be a multipart question. Basically I have to write a program that accepts a string, converts it to a double splits it and then performs a calculation.

public static void main(String[] args) {
String input = ""; // initalize the string
boolean isOn = true; // used for the while loop...when false, the program will exit.
String exitCommand = "Exit"; // exit command
String[] token = input.split(("(?<=[-+*/])|(?=[-+*/])"));

[Code] ....

This is the error I get:

Enter a math problemException in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecim al.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at Calculator.main(Calculator.java:22)

[Code] .....

How do I go about actually fixing it. Without that line commented out I get this:

Enter a math problem
2+2 <-What I entered
[Ljava.lang.String;@135fbaa4

Also, how would I go about using the submethods to check for valid operands and operators (also part of the problem) I have the actual lists made obviously, but am unsure how to get those to work with the problem.

View Replies View Related

Converting Double Value To A 2 Decimal Place Value

Jan 28, 2015

I am trying to convert the double grossPay to 2 decimal places but cannot get it to work ,I am unsure of the correct way of doing this but this is how far I can get

public static double grossPay(double Orate, double overtime, double salary) {
double grosspay = 0;
grosspay = (Orate * overtime) + (salary / 26);
DecimalFormat df = new DecimalFormat("#.##");
return(df.format(grosspay));
}//closes grossPay method

View Replies View Related

How To Print Double With 2 Decimal Numbers

May 3, 2014

I am trying to cast an integer into a double. it works but I need two decimal number after the dot and for example I can print 7.51 but how can I get it to print 7.50 and not 7.5

public int compareTo(Money o){
int d1 = (this.dollars * 100) + this.cents;
int d2 = (o.dollars * 100) + o.cents;
return d1 - d2;
}

On my main method I have

public static void main(String[] args){
Money money1 = new Money(10, 49);
Money money2 = new Money(2, 99);
System.out.println("result: " + "$" + (double)money1.compareTo(money2)/100);
}

It prints 7.5 but I want it to print 7.50, how do I do this .....

View Replies View Related

Multiplying Two Strings - Float Values

Jul 1, 2014

I am currently learning about JOption pane. Using Strings I am accepting an input from the user and by using the Interer.ParseInt(variable) option I am able to multiply this two strings using the code below.

String Length;
Length = JOptionPane.showInputDialog("Enter the Length");
String Breadth;
Breadth = JOptionPane.showInputDialog("Enter the Breadth");
System.out.println(" Area is " + (Integer.parseInt(Breadth) * Integer.parseInt(Length)));
System.exit(0);

Now My question is... How Do I make my code accept Decimal values. E.g. My Code should accept 10.02 as Length and 20.42 as Breadth and give the product a Decimal. How Do I do this???

View Replies View Related

Unable To Get Value Out Of Double - It Only Extends To One Decimal Place

Oct 3, 2014

I'm not sure why, but whenever I try to get a value out of a double, it only extends to one decimal place. For instance, (825 / 805) would become 1.0000 (after being run through a DecimalFormat object) instead of 1.0248 like I need it to be (and should be if what I know about primitive variable types is right). Why is the double variable type not giving me the precision I want and, more importantly, how do I fix this?

View Replies View Related

Decimal Format Errors - String Cannot Be Converted To Double

Jun 19, 2014

I am working on a project that just calculates simple interest based upon a principal and a percent interest rate written as .xxxx from user.

I need the Loan amount and the final interest calculation to show up as a currency with commas in appropriate areas, the Rate to be expressed as X.xxx% instead of .xxxx

I keep getting this error when I compile:

C:JavaInterestCalculator.java:46: error: incompatible types: String cannot be converted to double
principal = formatter.format(principal);
^
C:JavaInterestCalculator.java:49: error: incompatible types: String cannot be converted to double
rate = formatter.format(rate);
^
C:JavaInterestCalculator.java:52: error: incompatible types: String cannot be converted to double
totalInterest = formatter.format(totalInterest);
^
3 errors

Tool completed with exit code 1

And here is my code

import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
// class declaration
public class InterestCalculator
{
// main method declaration

[Code] .....

View Replies View Related

Double RelativeFrequency Value Which Does Calculation / End Result Is Number With Lots Of Decimal Numbers

Nov 24, 2014

for (int i = 0; i < letters.length; i++) {
double relativeFreq = (onesAverage()/letters[i]);
char a = characters.charAt(i);
double j = score[i];
System.out.printf();//ToDo

Above is my current code. Basically- There is a string called characters of length 26 (1 char for each letter in alphabet), a double relativeFrequency value which does a calculation and the end result is a number with lots of decimal numbers. The score array has set double values within the array.

What I want to do is create a print f statement where I print out each of the values I initialized above WITH specific amounts of spaces in between. So it should be in this order:

a (spaces) j (spaces) relativeFreq (newLine).

Between J and relativeFreq there should be 4 spaces, however if the value in relativeFreq is greater than 10 (it won't be greater than 100)- then there should be 3 spaces. Everytime I try to create a printf statement my code ends up crooked for some of the values.

for (int i = 0; i < letters.length; i++) {
double relativeFreq = (onesAverage()/letters[i]);
char a = characters.charAt(i);
double j = score[i];
System.out.printf("%c %.4s %.4s%n",a, j, relativeFreq);

View Replies View Related

Error - Invalid Float Literal

Apr 26, 2014

While doing trial and error got caught in the below scenario.

public class Crypt {
public static void main (String args[])
{
/*all I want is calculate a binary number (ex -: 22 , 34) using decimal base (10n).
*So, I have to convert 2 p into 10n form so I have to find n in terms of p . We have x as the input.
* The formula works as below.
*2p =10n
*p ln (2) =n ln (10)
*n = p [ln(2) / ln(10)]
*2 p = 10 p [ln(2) / ln(10)]

[Code] ....

View Replies View Related

Error In Program To Read Int Or Float Type Data From Keyboard

Aug 9, 2014

Here is a code and error .....

View Replies View Related

Decimal Values - JOptionPane

Jul 1, 2014

I am a beginner in Java and I am currently learning about JOption pane.Using Strings I am accepting an input from the user and by using the Interer.ParseInt(variable) option I am able to multiply this two strings using the code below.

String Length;
Length = JOptionPane.showInputDialog("Enter the Length");
String Breadth;
Breadth = JOptionPane.showInputDialog("Enter the Breadth");
System.out.println(" Area is " + (Integer.parseInt(Breadth) * Integer.parseInt(Length)));
System.exit(0);

How Do I make my code accept Decimal values. E.g. My Code should accept 10.02 as Length and 20.42 as Breadth and give the product a Decimal.

View Replies View Related

Calling Out Constructor And Assigning Values To It From A Scanner

Oct 16, 2014

import java.util.Scanner;
public class Try{
static String name;
static int age;
static Scanner a = new Scanner(System.in);
static Scanner b = new Scanner(System.in);
static Scanner c = new Scanner(System.in);
public Try(String name, int age){

[Code] ....

I was trying to make a program that asks the user to create a person or a group of persons and assign names and age to them. So I made a constractor "Try" and a method "AskUser".in AskUser() I use a do/while loop where user is asked to input a name, an age and if he likes to create another person. Now how do I take the input data each time the loop runs, and send it to constractor to create new objects with it? And how these new objects will be called?

View Replies View Related

Using Scanner Class In A Child Or Derived Class?

May 7, 2015

1. I want to use a scanner in my child class so that I may populate my parent class. It won't allow me something about scanner constructor. I posted this issue second which is my child's method Tests

2. I can't call my addTestsAnswers method from main to my child class but can call my child's display method from main.

import java.util.Scanner;
public class Tests extends Assessment{
private String q;
private String a;
private int userInput;
  Scanner scan = new Scanner();
Scanner scn = new Scanner();
Scanner u = new Scanner();
  public void addTestsAnswers(){

[code]....

View Replies View Related

GUI - Calling Int And Double Values From One Panel To Another

May 10, 2014

So I am making a panel project that calls three panels. Panel one holds all information and the other two panels are panels that open up when I press a button. How it works is I call the first panel, press a button, second panel opens. Then in the second panel I plug in a password. If it is correct, a third panel will open. I need to call values from the first panel into the third panel and those values act as sort of like counters. In the third panel it will display all the counters that were added as well as the complete sub total, tax, and total that the program accumulated during its run time duration. I know how to use constructors, accessors and mutators, but the values I need are generated in an event when I press a button. I am trying to figure out how to call those values from the event into the third panel. Here is my code :

Main Class:
import javax.swing.*;
public class AppleRegister {
public static void main(String[] args) {
double subTotalp2 = 0, taxP2 = 0, realTotalp2 = 0;
JFrame frame = new JFrame("Apple Crazy Cola Cash (Apple IIC) Register");

[Code] .....

Here is the main panel holding the information. The counters counterp21 through p24, subTotalp2, taxP2, and realTotalp2 are the values that need to be carried over to the third panel and displayed in the textfields. I will post half of the panel, at least the important parts. Notice that I made my constructor initialize double variables which are the subTotalp2, taxP2, and realTotalp2. In this instance, I am not calling the counters just yet due for the sake of testing purposes. TempListener2 is the event that holds the variables that I am trying to call into the third panel.

Main Panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class AppleRegisterPanel extends JPanel {
private JButton button1, button2, button3, button4, button5, button6;

[Code] ......

And here is how I am trying to call those values into the third panel. If you notice, the class is actually called AppleRegisterPanel2; this is because I made this before the second panel that is now implemented. This panel now acts as the third panel.

Third Panel:
public class AppleRegisterPanel2 extends JPanel {
private JButton b1;
private JTextField t1, t2, t3, t4, t5, t6, t7;
private JPanel panel, panel2, panel3;
private JLabel l1, l2, l3, l4, l5, l6, l7, l8, l9;
private double subTotalp2, realTotalp2, taxP2;

[Code] ....

So my question is; is what I am trying to do even possible? I know the information that is being stored is inside a void that is acting as an event. As it stands the code that is called in the third panel is 0.0. I know this code seems sloppy but I've been trying different things with no result. How I can do this if at all?

View Replies View Related

Converting Double Values (0.0-110.0) To A 4.0 Scale (as Used In GPA Calculation)

Sep 3, 2014

I am new to programming, but am working on a program that takes 6 inputted grade averages on a scale of 0.0 - 100.0 (exceptions in the case someone has exceeded the traditional 100.0 limit) and then divides it by 6 and returns the value in a dialog box. However, I want to take the values inputted and convert them to a 4.0 scale (90.0-100.0 = 4.0, 80.0-89.99 = 3.0, etc.) and then get the average of that so that I can return an average on a 4.0 scale. I have been trying to accomplish. Also, as of right now my program only prompts the user for 6 inputs, but I'd like the user to be able to input as many as he/she would like to, I am pasting the code I currently have below.

import javax.swing.JOptionPane;
public class GPA_Calculation1_0 {
public static void main(String[] args) {
String courseOne = JOptionPane.showInputDialog("Enter numeric GPA of Course One: ");//Course one
double numOne = Double.parseDouble(courseOne);

[Code] ....

View Replies View Related

Area And Perimeter Of Triangle - Decimal Formatting Error?

Sep 28, 2014

I am also having trouble with another program.

Java Code:

import javax.swing.JOptionPane;
import java.util.*;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
public class ShelbyHarms_3_03 {
public static void main (String [] args) {
double a, b, c; //Input sides of triangle
double x; //Perimeter of triangle
double area; //Area of triangle

[Code] .....

Here are the errors:

ShelbyHarms_3_03.java:39: error: variable x might not have been initialized
JOptionPane.showMessageDialog(null, formatter.format(x));
^
ShelbyHarms_3_03.java:42: error: variable area might not have been initialized
JOptionPane.showMessageDialog(null, formatter.format(area));
^
2 errors

Am I not formatting the decimal format right?

View Replies View Related

Using For Loop To Populate Array With Random Double Values

Oct 26, 2014

Write a program that creates an array that can hold 9 double values that represent baseball batting averages for a starting baseball lineup. Use a for loop to populate array with random double values in the range of 0.00 to 0.500. Recall that "double" values are what Java calls "real" numbers. Use a second for loop to print the values in the array with one number per line. Finally, use a third for loop to traverse the array and find and print the maximum batting average in the array. Note: you will need to use String.format to control the precision of a double number when you print it- Here is my code so far:

public class P2F {
public static void main (String[] args) {
double [] player= new double [9];
//player[0]= Math.random();
for (int index=0; index < player.length; index++) {

[Code] ....

When I open the terminal window I get different variations of this [D@4545c5]. I would like to know all the things I am doing wrong.

View Replies View Related

Getting Scanner Class To Accept Strings

Feb 2, 2014

Basically, I'm just trying to let the user enter the name. It crashes whenever the input isn't an int. Also, here's the bit of code I'm using that has to do with that. I don't feel like putting the entire class, so here's that bit of code:

PHP Code: String yourName = user.nextLine(); mh_sh_highlight_all('php');

Anyway, I just haven't figured out how. Also, the scanner is called user in this class.

View Replies View Related

Scanner Class - Can't Seem To Access Methods

May 9, 2014

I have two classes built for this assignment. One with getters, setters and constructor and a test class. The test class works fine up until the point when the user wants to (M)odify an employee that he/she built with the loadEmployee method. What happens is I need to enter multiple "M" inputs before anything pops up, and when something pops up, it's the displayMenu instead of modifyEmployee method. I imagine it has something to do with the amount of sc.nextLine()

import java.util.Scanner; // utilize scanner via console
import java.text.NumberFormat; // allows numbers to be format in form of currency
//Example of "big loop" in main to repeat using a No Trip (0,N) test first
public class EmployeeTest {
// space provided to make code easier on eyes...

[code]...

View Replies View Related

Calculate Distance Between Two Points - All Numbers And Return Values Should Be Of Type Double

Jul 8, 2014

Write method distance to calculate the distance between two points (x1, y1) and (x2, y2). All numbers and return values should be of type double. Incorporate this method into an application that enables the user to enter the coordinates of the points.

Hints:

- The distance between two points can be calculated by taking the square root of

( x2 - x1 )2 + ( y2 - y1 )2

- Use Math class methods to compute the distance.

- Your output should appear as follows:

Type the end-of-file indicator to terminate

On UNIX/Linux/Mac OS X type <ctrl> d then press Enter

On Windows type <ctrl> z then press Enter

Or Enter X1: 1

Enter Y1: 1

Enter X2: 4

Enter Y2: 5

Distance is 5.000000

Type the end-of-file indicator to terminate

On UNIX/Linux/Mac OS X type <ctrl> d then press Enter

On Windows type <ctrl> z then press Enter

Or Enter X1: ^Z

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved