File I/O with methods - java

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);
}

Related

?: in Java: How to combine res and resString more rationally?

I want output(mix of double res and String resString) is assigned a single variable.
import java.util.Scanner;
public class Lab3Task02_08 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("х = ");
int x = in.nextInt();
System.out.print("y = ");
int y = in.nextInt();
double arithm = (x+y)/2;
double geom = Math.sqrt(Math.abs(x*y));
//////////////////////////////////////////////////////////////
double res = x>y? arithm:geom;
String resString = x>y? "Arithm.average = ":"Geom.average = ";
//////////////////////////////////////////////////////////////
System.out.print(resString + res);
in.close();
}
}
You could do something like this:
String format = "%s.average = %d";
String res = x > y
? String.format(format, "Arithm", arithm)
: String.format(format, "Geom", geom);
— But, really, I question the logic of having two different averages conflated in this way in the first place.
As I understand you want to output two different values depending on the same condition. One of the option, it could be done with String.format(), Double.compare() and x ? y : x.
public static void main(String... args) throws ParseException {
Scanner scan = new Scanner(System.in);
System.out.print("х = ");
int x = scan.nextInt();
System.out.print("y = ");
int y = scan.nextInt();
double arithmetic = (x + y) / 2.;
double geometric = Math.sqrt(Math.abs(x * y));
int res = Double.compare(arithmetic, geometric);
System.out.format(Locale.ENGLISH, "%s average = %.2f\n",
res > 0 ? "Arithmetic" : "Geometric",
res > 0 ? arithmetic : geometric);
}
Output:
х = 3
y = 5
Arithmetic average = 4.00
х = -4
y = 3
Geometric average = 3.46
If i understand the question , is this what you want ?
import java.util.Scanner;
public class Lab3Task02_08 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("х = ");
int x = in.nextInt();
System.out.print("y = ");
int y = in.nextInt();
double arithm = (x+y)/2;
double geom = Math.sqrt(Math.abs(x*y));
//////////////////////////////////////////////////////////////
double res = x>y? arithm:geom;
String resString = x>y? "Arithm.average = ":"Geom.average = ";
//////////////////////////////////////////////////////////////
String combinedRes = resString + res;
System.out.print(combinedRes);
in.close();
}
}

Java: Functions for doing a project

I'm here doing an assignment and I'm getting a problem
A red mark is coming up next to "TotalCharge = ptr.calculateCharge(NightsStay, perNight);" and the error is double cannot be converted to Integer.
I tried researching to solve the problem but nothing is working.
Thank you very much.
HiibiscusHotelSpa9674 ptr = new HiibiscusHotelSpa9674();
Scanner keyboard = new Scanner(System.in);
Integer compare = 0;
String response = null;
String number = null;
Double Price = 0.00;
Integer TotalCharge = 0;
Integer ItemNo = 0;
String surName;
Integer perNight = 0;
Integer roomNumber = 0;
Double amountPaid = 0.0;
String temp = null;
String Name = null;
Double cashPaid = 0.0;
Double Change = 0.0;
Integer NightsStay = 0;
temp = JOptionPane.showInputDialog("Enter The amount of Items :");
int Size = Integer.parseInt(temp);
String[] ItemName = new String[Size];
Integer[] ItemId = new Integer[Size];
double[] ItemPrice = new double[Size];
Integer index = 0;
while (index < Size) {
ItemName[index] = JOptionPane.showInputDialog("Enter The Item Name:");
temp = JOptionPane.showInputDialog("Enter Item ID for " + ItemName[index] + " :");
ItemId[index] = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Enter The Price for " + ItemName[index] + " :");
ItemPrice[index] = Double.parseDouble(temp);
index++;
ptr.displayMenu(ItemName, ItemId, ItemPrice);
Name = ptr.getDataSetA();
cashPaid = ptr.getDataSetB(ItemId);
Change = ptr.performCalc(cashPaid, ItemPrice);
ptr.displayResults(Change, cashPaid);
response = JOptionPane.showInputDialog("Sale Complete? Enter Y or N: ");
switch (response) {
case "N":
perNight = ptr.GetGuestInfo();
NightsStay = ptr.GetDate();
TotalCharge = ptr.calculateCharge(NightsStay, perNight);
ptr.displayGuestBill(NightsStay, TotalCharge);
break;
case "n":
perNight = ptr.GetGuestInfo();
NightsStay = ptr.GetDate();
TotalCharge = ptr.calculateCharge(NightsStay, perNight);
ptr.displayGuestBill(NightsStay, TotalCharge);
break;
default:
JOptionPane.showMessageDialog(null, "Thank you very much and haave a wonderful day!");
}
public void displayMenu(String Name[], Integer ItemId[], double Price[]) {
System.out.printf("Item Name Item ID ItemPrice\n");
for (int i = 0; i < Name.length; i++) {
System.out.printf("%s\t %d\t %.2f\t\n", Name[i], ItemId[i], Price[i]);
}
}
public String getDataSetA() {
Scanner keyboard = new Scanner(System.in);
String[] personalInformation = new String[2];
String NameRoomNumber = null;
System.out.printf("Please Enter Room Number\n");
personalInformation[1] = keyboard.next();
System.out.printf("Enter your Surname\n");
personalInformation[0] = keyboard.next();
String NameNumber = Arrays.toString(personalInformation);
return NameRoomNumber;
}
private Double getDataSetB(Integer[] ItemId) {
Scanner keyboard = new Scanner(System.in);
String temp = null;
for (int i = 0; i < ItemId.length; i++) {
double cashPaid = 0.0;
Integer[] Items = new Integer[ItemId.length];
System.out.println("Please Enter the Item ID for the item");
ItemId[i] = keyboard.nextInt();
}
System.out.printf("Please Enter Cash Paid\n");
double cashPaid = keyboard.nextDouble();
return cashPaid;
}
private double performCalc(double cashPaid, double[] Price) {
Scanner keyboard = new Scanner(System.in);
double Cost = 0.0;
double change = 0.0;
double moneyOwe = 0.0;
for (int i = 0; i < Price.length; i++) {
Cost = Cost + Price[i];
}
if (cashPaid < Cost) {
moneyOwe = Cost - cashPaid;
JOptionPane.showMessageDialog(null, "You are $" + moneyOwe + " short");
} else {
change = cashPaid - Cost;
}
return change;
}
private void displayResults(Double Change, Double cashPaid) {
JOptionPane.showMessageDialog(null, "Cash Paid:$ " + cashPaid + "Change:$ " + Change + ".");
}
private Integer GetGuestInfo() {
String temp = null;
String Guestname = null;
Integer FloorNum = 0;
Integer NoofPer = 0;
Guestname = JOptionPane.showInputDialog("Please Enter Guest Name");
temp = JOptionPane.showInputDialog("Enter Floor Required");
FloorNum = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please Enter The Number of Persons Staying with you");
NoofPer = Integer.parseInt(temp);
return NoofPer;
}
private Integer GetDate() {
String temp = null;
Integer day = 0;
Integer month = 0;
Integer year = 0;
Integer Nights = 0;
temp = JOptionPane.showInputDialog("Please enter the Day: ");
day = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the Month: ");
month = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the Year: ");
year = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog("Please enter the number of Nights staying:");
Nights = Integer.parseInt(temp);
return Nights;
}
private Double calculateCharge(Integer amtofNights, Integer perNight) {
Integer floor = 0;
double totalCharge = 0.0;
if (floor > 4) {
// int perNight = 0;
int Numofnights = 0;
totalCharge = 150 * perNight * amtofNights;
} else {
totalCharge = 100 * perNight * amtofNights;
}
return totalCharge;
}
private void displayGuestBill(Integer NightsStayed, Integer totalCharge) {
System.out.printf("The total number of nights:%d\n", NightsStayed);
System.out.printf("The total Charge:%d", totalCharge);
}
}
Double is a wrapper class on top of the primitive double. It can be cast to double, but it cannot be cast to int directly.
If you use double instead of Double, it will compile:
double d = 10.9;
int i = (int)(d);
You can not convert a double to an integer implictely, because you are loosing precision. Imagine converting 3.7 to an integer, you would get 3 but a significant amount of information got lost.
If you are fine with this, you can do an explicit cast with (int)some_double for example.
Your code example does not contain any types, which makes it hard to say at which place your conversion happens.
Edit: Since your code example now contains types, it looks likely that your calculateCharge returns a double, but you are storing it into an integer.
You should force the explicit cast by doing
TotalCharge = (int)ptr.calculateCharge(NightsStay, perNight);

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);

How I should read such information in thist task? InputMismatchException

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();
}

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