Using a scanner in Java - java

I'm working on a Java assignment and whenever I insert a decimal into my scanner, the code returns errors. I went far enough to realize that it wasn't because the number was a decimal, but because whenever any character that is not a number is entered this error is returned.
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.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at population.main(population.java:14)
If anyone can help me get decimals to work that would be cool, here is my bad code.
import java.util.Scanner;
public class population {
public static void main(String[] args) {
System.out.print("Enter the amount of years:"); // Prompts the user
Scanner input = new Scanner(System.in); // Defines the scanner
double value = input.nextInt(); // Defines the variable
double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
double B = ((60.0 / 7.0) * A); // Births per year
double C = ((60.0 / 13.0) * A); // Deaths per year
double D = ((60.0 / 45.0) * A); // Immigration per year
double E = (B + D - C); // Change per year
double F = ((E * value) + 312032486.0); // Change in population after 5 years
System.out.println(F);
}
}

input.nextInt(); accepts an integer. Change it into input.nextDouble()

Scanner#nextInt()- Scans the next token of the input as an int.
and throws
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
input.nextInt() takes an input of type int
use
input.nextDouble()

Exception occur because of invalid input. you can add try catch block. See the below code.
For More information see this
public static void main(String[] args) {
try
{
System.out.print("Enter the amount of years:"); // Prompts the user
Scanner input = new Scanner(System.in); // Defines the scanner
double value = input.nextInt(); // Defines the variable
double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
double B = ((60.0 / 7.0) * A); // Births per year
double C = ((60.0 / 13.0) * A); // Deaths per year
double D = ((60.0 / 45.0) * A); // Immigration per year
double E = (B + D - C); // Change per year
double F = ((E * value) + 312032486.0); // Change in population after 5 years
System.out.println(F);
}
catch(Exception e)
{
System.out.println("Invalid Input");
}
}

Related

scanner input undefined for String? JAVA [duplicate]

This question already has an answer here:
Scanner only reads file name and nothing else
(1 answer)
Closed 5 years ago.
This program prompts the store owner for the amount of cash at the beginning and end of the day, and the name of the file. It should check whether the actual amount of cash at the end of the day equals the expected value.
I have a txt file where each line contains three items: The invoice number, the cash amount, and the letter P if the amount was paid or R if it was received. Items are separated by spaces.
I am having trouble with this piece in my code
while (filename.hasNext()) {
invoice.add(filename.nextInt());
cash.add(filename.nextDouble());
PR.add(filename.next());
}
It is a syntax error saying I cannot use .nextInt() .nextDouble() .next() hasNext()
Here is the full source code:
import java.io.*;
import java.util.*;
/**
* Code for P11.11. This program takes in a list of baby names and outputs a list of boys and
* girls names.
*
* #Michael Goedken
*/
public class BalanceTransactions {
public static void main(String[] args) throws FileNotFoundException {
// The following lines ask the user to enter the file name and the balances at the beginning and the end
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name for input: ");
String filename = in.next();
System.out.print("Please enter the cash amount at the start: ");
double start = in.nextDouble();
System.out.print("Please enter the cash amount at the end: ");
double end = in.nextDouble();
ArrayList<Integer> invoice = new ArrayList<Integer>();
ArrayList<Double> cash = new ArrayList<Double>();
ArrayList<String> PR = new ArrayList<String>();
while (filename.hasNext()) {
invoice.add(filename.nextInt());
cash.add(filename.nextDouble());
PR.add(filename.next());
}
for (int i = 0; i < invoice.size(); i++) {
if (PR.get(i).equals("P")) {
start -= cash.get(i);
}
if (PR.get(i).equals("R")) {
start += cash.get(i);
}
}
if (start == end || (double) Math.round(start * 1000000000) / 1000000000 == end) {
System.out.println("There is the correct amount in the register.");
} else {
Double difference = ((double) Math.round(start * 100000) / 100000) - end;
System.out.println("You are off by: " + difference);
}
}
}
EDIT: I added a new scanner now I get this error
Scanner fileScanner = new Scanner("/Users/MichaelGoedken/Desktop/transactions.txt");
while (fileScanner.hasNext())
{
invoice.add(fileScanner.nextInt());
cash.add(fileScanner.nextDouble());
PR.add(fileScanner.next());
}
ERROR:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at BalanceTransactions.main(BalanceTransactions.java:34)
If you want to scan a file, try to use this constructor:
/**
* Constructs a new Scanner that produces values scanned
* from the specified file. Bytes from the file are converted into
* characters using the specified charset.
*
* #param source A file to be scanned
* #throws FileNotFoundException if source is not found
*/
public Scanner(File source) throws FileNotFoundException {
this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
}
Right now you are using this constructor, it doesn't make any sense, because you pass as a parameter String:
public Scanner(String source) {
this(new StringReader(source), WHITESPACE_PATTERN);
}

java program has error after "bootlean go=true"? [duplicate]

This question already has answers here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 7 years ago.
I'm getting an exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at package1.smth.main(clas1.java:19)
When I remove the while(go) part, everything is working fine. But I added it to be able to reset program, and now there is an exception. I also have a code for another similar program, where I added the same loop and it is working without this exception.
Can someone explain what's the problem?
public static void main(String[] args) {
boolean go = true;
while (go) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double d = 0;
System.out.print("Enter a : ");
a = input.nextDouble();
System.out.print("Enter b : ");
b = input.nextDouble();
System.out.print("Enter c : ");
c = input.nextDouble();
discriminant = (b * b - 4 * a * c);
d = Math.sqrt(discriminant);
if (discriminant >= 0.0) {
System.out.println("first answer : " + (-b + d) / (2.0 * a));
System.out.println("second answer : " + (-b - d) / (2.0 * a));
} else if (discriminant == 0.0) {
System.out.println("first answer : " + (-b) / (2.0 * a));
System.out.println("second answer : " + (-b) / (2.0 * a));
} else {
System.out.println("no asnwers.");
input.close();
}
}
}
I've read everything I could find similar to my problem, and most answers came from this site. I tried to implement the given solutions to my code, and some didn't work, some I could not understand how to use because my code is different from the example in a question. I am total newbie, it is probably third program I wrote.
UPDATE:
The final code I have. The only problem it shows, is "leak: scanner not closed".
package gg;
import java.util.Scanner;
public class hbh {
public static void main(String[] args) {
boolean go = true;
while (go) {
Scanner input = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double d = 0;
System.out.print("Enter a: ");
a = input.nextDouble();
System.out.print("Enter b: ");
b = input.nextDouble();
System.out.print("Enter c: ");
c = input.nextDouble();
discriminant = (b * b - 4 * a * c);
d = Math.sqrt(discriminant);
if (discriminant >= 0.0) {
System.out.println("First answer: " + (-b + d) / (2.0*a));
System.out.println("Second answer: " + (-b - d) / (2.0*a));
}
else if (discriminant ==0.0) {
System.out.println("First answer: " + (-b) / (2.0*a));
System.out.println("Second answer: " + (-b) / (2.0*a));
}
else {
System.out.println("No answers");
input.nextLine();
}
}
}
}
You should delete
input.close();
When you close the System.in once, you can not use it again after having closing it.
I can not find the source but here is a proof that this is causing the problem.
Try running the following code and you'll get the exact same exception.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.close();
Scanner other = new Scanner(System.in);
other.nextDouble();
}
When you call, input.close() it not only closes your scanner but closes your System.in. Now you still keep iterating over the loop even when scanner is closed (and keep scanning values) which causes excpetion.
UPDATE
Your code seems to go in a infinite loop because you do not break from the loop neither do you update the value of go which at some point might terminate the loop.
Thus, the scanner will keep reading values until all the inputs are exhausted and eventually throw java.util.NoSuchElementException exception (when all the inputs are exhausted).

Create a program that prompt user fa a floating point(double) Fahrenheit and then return equal value in Celsius

import java.util.*;
class TempConver {
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
temperature = in.nextInt();
temperature = (temperature - 32) * 5 / 9;
System.out.printf("Censius Temperatre is = " + temperature);
}
}
I've to write program using information given below.
output formatting - "printf()" instead of print() or println()
Do While loops - repeat a question until a user gives you a valid response
Scanner.HasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Please help me how to write output in 2 place decimal using do while loop. !!
You have all the answers you need in the hints.
Do While loops - repeat a question until a user gives you a valid response And Scanner.hasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Here you are telling the user, while the input is not a double, then execute the code. Which will be asking the user for input until you get a double
while (!in.hasNextDouble()) {
// code here
}
To round to two decimals you can use Math.round() to round a value to the nearest integer, and multiply temperature by 100 then divide by 100.
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
Full code:
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
// As long as it is not a double ask for another input
while (!in.hasNextDouble()) {
System.out.printf("Please enter a valid number:");
in.next();
}
temperature = in.nextDouble();
temperature = (temperature - 32) * 5 / 9;
// Use only 2 decimals
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
System.out.printf("Censius Temperatre is = " + temperature);
}

New Java Programmer, whats wrong with this program?

It gets to the point where it has to print the line System.out.printf("%4s%22s%24s\n","Year"...), and then just stops without printing.
public class WorldPopulationGrowth {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner( System.in);
long BasePopulation; //The base, or current population
double GrowthRate; //The rate of increase
double GrowthResult; // The pop after growth rate increase
//Time to obtain the numbers needed for Calculation
//Specifically, the growth rate and the base population
System.out.println("Welcome to the world population calculator");
System.out.print("Enter the current world population:");
BasePopulation = input.nextLong();
System.out.println("Enter the current growth rate: (e.g, 1.14% would be .0114): ");
GrowthRate = input.nextDouble();
int Year = 1; //I need this for the next part
System.out.printf("%4s%22s%24s\n", "Year", "Estimated Population", "Change from prior Year");
while (Year <= 75); {// Start of the while
GrowthResult = BasePopulation * (1 + GrowthRate);
System.out.printf("%4d%22d%24d\n", Year, (long) GrowthResult, (long) GrowthResult - BasePopulation);
BasePopulation = (long) GrowthResult;
}//End of the while
}//End of public static
}//End of class
You've got a semicolon after your while loop. That semicolon is an empty statement, and that's what gets executed in the loop. After that, you have an anonymous block (which is what you want to be executed in the loop). It's equivalent to this:
while (Year <= 75) {
// empty
}
{
// anonymous block
GrowthResult = BasePopulation * (1 + GrowthRate);
...
The fix is to remove the semicolon.
Try removing semicolon from this line
while (Year <= 75); {// Start of the while
Should be:
while (Year <= 75) {// Start of the while

Simple Java present value calculator is not working

I have not used java before and I am confused as to why a simple present value calculator I wrote is not working. The present value formula returns a super small number for some reason? See if you can spot my error:
// Import all utilities
import java.text.DecimalFormat;
import java.util.*;
// Base class
public class Project2
{
// Main function
public static void main(String[] args)
{
// Define variables
double p = 0.0;
double f = 0.0;
double r = 0.0;
double n = 0.0;
String another = "Y";
// Create a currency format
DecimalFormat dollar = new DecimalFormat("#,###.00");
// Create a new instance of the scanner class
Scanner keyboard = new Scanner(System.in);
// Loop while another equals "Y"
while(another.equals("Y"))
{
// Get future value
System.out.println("Future value: ");
f = Double.parseDouble(keyboard.nextLine());
// Get annual interest rate
System.out.println("Annual interest rate: ");
r = Double.parseDouble(keyboard.nextLine());
// Get Number of years
System.out.println("Number of years: ");
n = Double.parseDouble(keyboard.nextLine());
// Run method to find present value and display result
p = presentValue(f, r, n);
System.out.println("Present value: $" + p );
// Ask if user wants to enter another
System.out.println("Enter another?(Y/N) ");
another = keyboard.nextLine().toUpperCase();
}
}
public static double presentValue(double f, double r, double n)
{
// Do math and return result
double p = f / Math.pow((1 + r), n);
return p;
}
}
Assuming you enter the R as % per annum i.e. for e.g. R = 4.3%, you would want to modify the function as :
double p = f / (Math.pow((1 + (r/100.0)), n));
return p;
If this is not what you would want, you might want to enter the value of R=4.3% p.a as
4.3/100 = 0.043 and not 4.3.
Instead of future value Please take an input for Principal.
Your PresentValue Calculation Function will be like this. Try this function, hope you will get your perfect result
public double presentValue(double principal, double yearlyRate, double termYears)
{
// Do math and return result
double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
return pValue;
}
Math.pow expects the first argument to be the base and the second the exponent. ( See The Math javadoc )
In your program the first argument is the power and the second is the base.
Change that to double p = f / Math.pow(n, (1 + r)); and I expect your program to run as expected
Your program works fine. I just tested it.
Future value:
100000
Annual interest rate:
0.4
Number of years:
20
Present value: $119.519642774552
Enter another?(Y/N)
Y
Future value:
100000
Annual interest rate:
40
Number of years:
20
Present value: $5.550381891760752E-28
Enter another?(Y/N)
You're entering the interest rate wrong probably.
If you want to enter an integer value, you can modify the formula:
double p = f / (Math.pow((1 + (r/100.0)), n));
This will result in:
Future value:
100000
Annual interest rate:
40
Number of years:
20
Present value: $119.519642774552
Enter another?(Y/N)

Categories

Resources