How I should read such information in thist task? InputMismatchException - java

It is attempt to solve second task from Code Jam 2014. Unfortunately, I have an InputMisMatchException? I think problem is that first number is not double.
How I should to read such information? Link to task.
Input:
4
30.0 1.0 2.0
30.0 2.0 100.0
30.50000 3.14159 1999.19990
500.0 4.0 2000.0
My Java code:
public class CookieClickerAlpha {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = (int) sc.nextDouble();
double priceForFarm, plusCookies, goal;
double currentTime = 0.0, timeWithFarm,
timeWithoutFarm, timeForFarm, resultTime;
double currCookies = 0.0, cookiesPerSec = 2.0;
for (int i = 0; i < n; i++) {
priceForFarm = sc.nextDouble();
plusCookies = sc.nextDouble();
goal = sc.nextDouble();
while (currCookies < goal) {
timeForFarm = (priceForFarm - currCookies) / cookiesPerSec;
timeWithFarm = timeForFarm +
goal / (cookiesPerSec + plusCookies);
timeWithoutFarm = (goal - currCookies) / cookiesPerSec;
if (timeWithFarm < timeWithoutFarm) {
currCookies = 0.0;
cookiesPerSec += plusCookies;
currentTime += timeForFarm;
}
else {
currentTime += goal / cookiesPerSec;
currCookies = goal;
}
}
pw.print("Case #" + (i + 1) + ": ");
pw.println(currentTime);
}
sc.close();
pw.close();
}
}

use sc.hasNextDouble() / hasNextInt() to check whether the nxt number is a double / int and then use nextInt(), nextDouble() based on what hasNextXXX returns.
EDIT :
To read integer first , do :
if(sc.hasNextInt()){
n=sc.nextInt();
}

Related

File I/O with methods

In my program, take the user input file name with the scanner. user enter .txt file name in console and I got output in console as well but now if i want to do this program with this method :
public static double deviation(File inputFile)
How can I implement my program?
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
double number = 0;
double n = 0;
double sum = 0;
double sum1 = 0;
int count = 0;
double mean = 0;
Scanner Scanscan = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile);
while(reader.hasNext()){
number = reader.nextDouble();
sum = sum + number;
sum1 = sum1 + Math.pow(number,2);
n++;
}
double n1 = Math.sqrt(n);
double sum11 = Math.sqrt(sum1);
mean = sum / n;
double n12 = Math.pow(n,2) - n;
double n22 = Math.pow(sum, 2);
double x = ( n * sum1 - n22) / (n12);
double deviation = (Math.sqrt(x));
System.out.println( "The standard deviation of the values in this file is: " + deviation);
}
By moving the necessary parts into the new method.
public static double deviation(File inputFile){
double number = 0;
double n = 0;
double sum = 0;
double sum1 = 0;
int count = 0;
double mean = 0;
Scanner reader = new Scanner(inputFile);
while(reader.hasNext()){
number = reader.nextDouble();
sum = sum + number;
sum1 = sum1 + Math.pow(number,2);
n++;
}
double n1 = Math.sqrt(n);
double sum11 = Math.sqrt(sum1);
mean = sum / n;
double n12 = Math.pow(n,2) - n;
double n22 = Math.pow(sum, 2);
double x = ( n * sum1 - n22) / (n12);
return Math.sqrt(x);
}
public static void main(String[] args) throws FileNotFoundException {
Scanner Scanscan = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
double deviation = deviation(inputFile);
System.out.println( "The standard deviation of the values in this file is: " + deviation);
}

Need to set a maximum (100) and minimum (0), for this average test result program

Need to set a maximum (100) and minimum (0), for this average test result program. I understand that i would need to use '<' and'>' somewhere within my work however i am not sure how/where
import java.util.Scanner;
public class ExamResults {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the 5 exam results");
double ExamResult1 = 0.0;
ExamResult1 = Double.parseDouble(keyboard.nextLine());
double ExamResult2 = 0.0;
ExamResult2 = Double.parseDouble(keyboard.nextLine());
double ExamResult3 = 0.0;
ExamResult3 = Double.parseDouble(keyboard.nextLine());
double ExamResult4 = 0.0;
ExamResult4 = Double.parseDouble(keyboard.nextLine());
double ExamResult5 = 0.0;
ExamResult5 = Double.parseDouble(keyboard.nextLine());
double averageScore;
averageScore = ((ExamResult1 + ExamResult2 + ExamResult3 + ExamResult4 + ExamResult5)/5);
System.out.println("The average Score is" + averageScore);
}
}
Try something like:
double min = Math.min(Math.min(ExamResult1, ExamResult2), ExamResult3);//similarly for others
double max = Math.max(Math.max(ExamResult1, ExamResult2), ExamResult3);//similarly for others
I would do this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the 5 exam results");
double[] examResults = new double[5];
double total = 0.0;
for (int i = 0; i < examResults.length; i++)
{
double value = Double.parseDouble(keyboard.nextLine());
while (value < 0 || value > 100)
{
System.out.println("Invalid score, try again");
value = Double.parseDouble(keyboard.nextLine());
}
examResults[i] = value;
total += value;
}
double averageScore;
averageScore = total / examResults.length;
System.out.println("The average Score is" + averageScore);

java: loop produces incorrect output when reading from file?

This loop is producing the average values of hours and amount paid, but the output is mathematically incorrect. How can I edit this code to produce the correct average hours value and average paid values?
Scanner openFile = new Scanner(inFile);
while (openFile.hasNext()) {
if (openFile.hasNextDouble()) {
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble()) {
totalPaid += openFile.nextDouble();
numOfCharges++;
}
else {
openFile.next(); }
}
averageHours = (totalHours/numOfHourInputs);
averagePaid = (totalPaid/numOfCharges);
Below is my file:
The first column is unimportant for calculating the averages. The second column contains the numbers of hours. The third column contains the charges.
This file can have more data added to it by the user - the values inside of the file can be changed.
a 10.0 9.95
b 10.0 13.95
b 20.0 13.95
c 50.0 19.95
c 30.0 19.95
Remove the else:
else {
openFile.next(); //this consumes all input
}
The following code
Double[][] values = {{10.0, 9.95},
{10.0, 13.95},
{20.0, 13.95},
{50.0, 19.95},
{30.0, 19.95}};
Double totalHours = 0.;
int numOfHourInputs = 0;
Double totalPaid = 0.;
int numOfCharges = 0;
for (final Double[] value : values) {
totalHours += value[0];
numOfHourInputs++;
totalPaid += value[1];
numOfCharges++;
}
final double averageHours = (totalHours / numOfHourInputs);
System.out.println("averageHours = " + averageHours);
final double averagePaid = (totalPaid / numOfCharges);
System.out.println("averagePaid = " + averagePaid);
produced the result
averageHours = 24.0
averagePaid = 15.55
so that it's clearly not a mathematical problem. Check your input code especially for the line
openFile.next();
You still need to skip the first token but in the right spot:
public static void main(String[] args)
{
double totalHours = 0.0;
int numOfHourInputs = 0;
double totalPaid = 0.0;
int numOfCharges = 0;
Scanner openFile = null;
try
{
openFile = new Scanner(new File("c:\\temp\\pay.txt"));
}
catch (Exception e)
{
throw new RuntimeException("FNF");
}
try
{
while (openFile.hasNext())
{
// skip the first token
String token = openFile.next();
if (openFile.hasNextDouble())
{
totalHours += openFile.nextDouble();
numOfHourInputs++;
}
if (openFile.hasNextDouble())
{
totalPaid += openFile.nextDouble();
numOfCharges++;
}
}
}
finally
{
openFile.close();
}
double averageHours = (totalHours/numOfHourInputs);
double averagePaid = (totalPaid/numOfCharges);
System.out.println("Total hours: " + totalHours);
System.out.println("Num hours input: " + numOfHourInputs);
System.out.println("----------------------------------------");
System.out.println("Average hours: " + averageHours);
System.out.println("");
System.out.println("Total payments: " + totalPaid);
System.out.println("Num payments input: " + numOfCharges);
System.out.println("----------------------------------------");
System.out.println("Average paid: " + averagePaid);
}
Here is the output that I get:
Total hours: 120.0
Num hours input: 5
----------------------------------------
Average hours: 24.0
Total payments: 77.75
Num payments input: 5
----------------------------------------
Average paid: 15.55

My Java program seems to get...stuck (?) at a point during execution. I'm baffled.

So, I'm trying to create a driver for my method. I apologize in advance, I know very little about what I'm talking about. What the program does, is it calculates sine, cosine, and the exponential function by means of taylor series for a number that the user inputs. The use of Math.pow and Math.fact were not allowed. My compiler isn't giving me any errors, and I'm all out of ideas at this point. In addition, the scanner doesn't seem to stop accepting input after I press enter. It continues to take numbers, but doesn't do anything else. It gives an exception when I type a letter. High possibility of ID10T error. I know that the output isn't well formatted yet, but that's because I haven't had a chance to see it yet. If someone could help me figure this out, I would be very greatful. Thanks in advance!
-An aspiring code monkey
Driver (Lab4.java)
/*
This program is being created to solve Lab 4.
*/
import java.util.*;
public class Lab4
{
public static void main(String[] args)
{
String again, more = "y";
while (more.toUpperCase().charAt(0) == 'Y')
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Input X: ");
Function number = new Function();
double x = number.x();
System.out.println("x = " + x);
Function sine = new Function();
double mySin = sine.funcSine();
Function cosine = new Function();
double myCos = cosine.funcCos();
Function expo = new Function();
double myExp = expo.funcExp();
System.out.println("\t\t\t\tLibraryResult My Result");
System.out.println("\n\t\tsin(" + Function.x() + ")" + " = " + "\t\t\t" + Math.sin(Function.x()) + "\t" + mySin);
System.out.println("\n\t\tcos(" + Function.x() + ")" + " = " + "\t\t\t" + Math.cos(Function.x()) + "\t" + myCos);
System.out.println("\n\t\texp(" + Function.x() + ")" + " = " + "\t\t\t" + Math.exp(Function.x()) + "\t" + myExp);
System.out.println("\n\t\t\tDo more (Y/N) ? ");
more = keyboard.next();
String junk = keyboard.nextLine();
}
}
}
Method (Function.java)
/*
This class provides the information for the parent to use in order to solve Lab 4.
*/
import java.util.*;
public class Function
{
Scanner keyboard = new Scanner(System.in);
public static int number;
private double temp = 1;
private double last = 1;
public static double x()
{
Scanner keyboard = new Scanner(System.in);
double x = keyboard.nextDouble();
return x;
}
public static double pow(double value, double power)
{
if(power == 0)
{
return 1;
}
double result = value;
for(int i = 0; i < power -1; i++)
{
result = result * value;
}
return result;
}
public static double getFact()
{
while (number < 0)
{
number =(number * -1);
}
double factorial = 1;
if (0 == (number % 1))
{
do
{
factorial = factorial * number;
--number;
} while (number >= 1);
}
else //Stirling's Approximation
{
double e = 2.718281828459;
double part1 = Math.sqrt(2 * 3.141592653589 * number);
double part2a = (number / e);
double part2b = (pow(part2a,number));
factorial = (part1 * part2b);
}
return factorial;
}
public static double funcSine()
{
int place = 0;
double next = x()*1;
for(number = 3; number <= 30; number = number + 2)
{
next = next + ((pow((-1),place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double mySin = next * 1;
return mySin;
}
public static double funcCos()
{
int place = 0;
double next = 1;
for(number = 2; number <= 30; number = number + 2)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myCos = next * 1;
return myCos;
}
public static double funcExp()
{
int place = 0;
double next = 1 + x();
for(number = 1; number <= 30; number++)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myExp = next * 1;
return myExp;
}
}
Check the syntax of your while loop:
while (more.toUpperCase().charAt(0) == 'Y')
Think about when the program will ever not satisfy this expression.
Also you have multiple Scanners all over your code. ITs not clear why you need to keep reading inout over and over again.

How do I find the average of the doubles in the file - JAVA

I need to Skip over text or integers. It reads a .dat file that has numbers (int/doubles) and strings in it. It also Calculates and prints max, min, sum, and the count of the number of words in the file. How do I do the average? Thank you!!
import java.io.*;
import java.util.*;
public class ProcessFile {
public static void main(String [] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Enter file name: ");
String n = console.next();
File f = new File(n);
while(!f.exists()){
System.out.print("Doesn't exist. Enter a valid filename: ");
n = console.next();
f = new File(n);
}
Scanner input = new Scanner(f);
int minInt = Integer.MAX_VALUE;
int maxInt = Integer.MIN_VALUE;
int countInt;
int averageInt =
double minDouble = Double.MIN_VALUE;
double maxDouble = Double.MAX_VALUE;
double countDouble;
double averageDouble = //sum / countDouble
while(input.hasNext()){
if (input.hasNextInt()){
int next = input.nextInt();
maxInt = Math.max(next, maxInt);
minInt = Math.min(next, minInt);
countIntC++;
averageInt =
System.out.println("The results for the integers in the file :");
System.out.printf(" Max = %d\n", maxInt);
System.out.printf(" Min = %d\n", minInt);
System.out.printf(" Count = %d\n", countInt);
System.out.printf(" averageInt = %d\n", averageInt);
} else if (input.hasNextDouble()) { //can I read it as a double
double = next2 = input.nextDouble();
maxDouble = Math.max(next2, maxDouble);
minDouble = Math.min(next2, minDouble);
countDouble++;
averageDouble =
System.out.println("The results for the integers in the file:");
System.out.printf(" Max = %f\n", maxDouble);
System.out.printf(" Min = %f\n", minDouble);
System.out.printf(" Count = %f\n", countDouble);
System.out.printf(" averageInt = %f\n", averageDouble);
} else { //it is String
}
}
}
}
I see three problems
1) you need to initialize countDouble
countDouble = 0;
you're trying to do this countDouble++ before it's been ititialized
2) double = next2 = input.nextDouble();
I believe should be this
double next2 = input.nextDouble();
3) there no such variable countIntC
you're trying to countIntC++
should be countInt++
To calculate, I think you want to do this
averageInt = (maxInt + minInt) / countInt; // I THINK, depending on your logic
All in all, I have a feeling there's alot going on in your code, that can be thrown out.

Categories

Resources