I am trying to make this file loop, but I keep getting an error on at the last if statement (Marked by an arrow).
The program is supposed to read in a file with the first line being the name of the customer.
On the second line, the first number is the number of trees to be removed(150 per tree), the second number is tree trimming to be done(50 an hour).
The third line are all the stumps to be removed and their diameter(one number is one stump and also it's diameter).
This is the file that is supposed to be read in (http://pastebin.com/gXkujcaM).
public class Prog_5 {
public static void main(String[] args) throws FileNotFoundException {
String name = "Joe";
double trees = 0;
double treeTrimming = 0;
double stumpInches = 0;
double stumpTotal = 0;
double total = 0;
double totalRev = 0;
Scanner in = new Scanner(System.in);
System.out.print("Input file: ");
String inputFile = in.nextLine();
System.out.print("Output file: ");
String outputFile = in.nextLine();
in.close();
File input = new File(inputFile);
in = new Scanner(input);
PrintWriter output = new PrintWriter(outputFile);
while(in.hasNext()){
name = in.nextLine();
output.println("Customer: " + name);
System.out.println("Customer: " + name);
trees = in.nextDouble();
trees *= 150;
output.println("Tree Removal: $" + trees);
System.out.println("Tree Removal: $" + trees);
treeTrimming = in.nextDouble();
treeTrimming *= 50;
output.println("Tree Trimming: $" + treeTrimming);
System.out.println("Tree Trimming: $" + treeTrimming);
while (in.hasNextDouble()) {
stumpInches = in.nextDouble();
if (stumpInches != -1) {
stumpTotal = stumpTotal + 30;
if (stumpInches > 12) {
stumpInches -= 12;
stumpInches *= 2;
}
stumpTotal += stumpInches;
}
}
output.println("Stump Removal: $" + stumpTotal);
System.out.println("Stump Removal: $" + stumpTotal);
total = (trees + treeTrimming + stumpTotal);
output.println("Total: $" + total);
System.out.println("Total: $" + total);
totalRev += total;
stumpTotal = 0;
trees = 0;
treeTrimming = 0;
if(in.hasNext());
in.next();
}
output.close();
}
}
it is your if loop is problem . you should write it like below . but you terminated it with ;
if(in.hasNext()){
in.next();
}
so it will keep throwing nosuchelement exception every time if it reaches EOF
There is no need of outer while loop, if condition at the end. Inner while loops takes care of what your program is intended to do. PFB corrected code:
import java.io.*;
import java.util.Scanner;
public class Prog_5 {
public static void main(String[] args) throws FileNotFoundException {
String name = "Joe";
double trees = 0;
double treeTrimming = 0;
double stumpInches = 0;
double stumpTotal = 0;
double total = 0;
double totalRev = 0;
Scanner in = new Scanner(System.in);
System.out.print("Input file: ");
String inputFile = in.nextLine();
System.out.print("Output file: ");
String outputFile = in.nextLine();
in.close();
File input = new File(inputFile);
in = new Scanner(input);
PrintWriter output = new PrintWriter(outputFile);
// while (in.hasNext()) {
name = in.nextLine();
output.println("Customer: " + name);
System.out.println("Customer: " + name);
trees = in.nextDouble();
trees *= 150;
output.println("Tree Removal: $" + trees);
System.out.println("Tree Removal: $" + trees);
treeTrimming = in.nextDouble();
treeTrimming *= 50;
output.println("Tree Trimming: $" + treeTrimming);
System.out.println("Tree Trimming: $" + treeTrimming);
while (in.hasNextDouble()) {
stumpInches = in.nextDouble();
if (stumpInches != -1) {
stumpTotal = stumpTotal + 30;
if (stumpInches > 12) {
stumpInches -= 12;
stumpInches *= 2;
}
stumpTotal += stumpInches;
}
}
output.println("Stump Removal: $" + stumpTotal);
System.out.println("Stump Removal: $" + stumpTotal);
total = (trees + treeTrimming + stumpTotal);
output.println("Total: $" + total);
System.out.println("Total: $" + total);
totalRev += total;
stumpTotal = 0;
trees = 0;
treeTrimming = 0;
// if (in.hasNext())
// ;
// in.next();
// }
in.close();
output.close();
}
}
Related
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
String[] array2 = new String [10]; // New array that saves up to 10 elements(treatments)
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
int n = array.length;
for (int i=0; i<n; i++) {
for (int j=0; i<n ; j++) {
System.out.println();
treatment = input.nextInt();
if (treatment==1) {
cost += Integer.parseInt(array[i][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==2) {
cost += Integer.parseInt(array[i+1][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==3) {
cost += Integer.parseInt(array[i+2][1]);
System.out.print("Total cost so far: " + cost);
}
}
}
How do I move on from here? I figured that I have to store the input in the new array and exit the loop after 10 treatments or add an option to the user to print out the receipt when they're done.
The receipt needs to print all the chosen treatments along with the cost for each individual treatment. I will also need to add a variable to add a total amount for all the chosen treatments.
Here it is what you are trying to do, As the treatments are fixed so you can just index them as 0, 1, 2. One thing you can do is to make a hashmap in which you can store the treatment name and its cost (String,int) every time the user wants to enter.
Look at the code below
import java.util.*;
import java.util.HashMap;
public class treatment {
public static void main(String []args) {
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
// New array that saves up to 10 elements(treatments)
HashMap<String, Integer> treat = new HashMap<String, Integer>();
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
int n = array.length;
int i =0;
char c = '\0';
do {
System.out.println("\n\nControl" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
System.out.println("Exit: " + "-1");
System.out.println();
System.out.print("Enter treatment value (1, 2, 3): ");
treatment = input.nextInt();
if (treatment==1){
i = 0;
cost += Integer.parseInt(array[0][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==2) {
i = 1;
cost += Integer.parseInt(array[1][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==3) {
i = 2;
cost += Integer.parseInt(array[2][1]);
System.out.println("\nTotal cost so far: " + cost);
}
treat.put(array[i][0], cost);
} while (treatment != -1);
System.out.println("Total COst is : " + cost);
System.out.println("The treatements you opt for are:\n");
System.out.println(treat);
System.out.println("\n");
}
}
import java.util.Scanner;
public class TipCalculator{
static double Steak;
static double Ribs;
static double Salad;
static double Burger;
static double SoftDrink;
static double PintofBeer;
static double Wine;
static double Champagne;
static int i;
static double [] Choice = new double [15];
static double Subtotal;
static double Tax;
static double Tip;
static double Total;
public static void main (String args []){
Scanner scan = new Scanner (System.in);
Ribs = 25;
Steak = 35;
Salad = 5;
Burger = 15;
SoftDrink = 2;
PintofBeer = 5;
Wine = 6;
Champagne = 9;
Tax = 1.13;
do {
System.out.println("Please enter one of the following options, or enter 9 to go to your bill");
System.out.println("1. 12 oz Striploin Steak ");
System.out.println("2. 16 oz Baby Back Ribs ");
System.out.println("3. Ceaser Salad ");
System.out.println("4. House Burger ");
System.out.println("5. Soft Drink ");
System.out.println("6. Wine ");
System.out.println("7. Champagne ");
Choice [i] = scan.nextInt();
}
while (Choice [i] < 9);
if (Choice [i] == 9){
Subtotal = Choice[1] + Choice[2] + Choice[3] + Choice[4] + Choice[5] + Choice[6] + Choice[7] + Choice[8] + Choice[9] + Choice[10] + Choice[11] + Choice[12] + Choice[13] + Choice[14] + Choice[15];
System.out.println("Your subtotal is " + Subtotal);
}
System.out.println("Enter your tip percent");
Tip = scan.nextInt();
Total = ((Subtotal * Tax) * (Tip/10));
System.out.println("Your total is " + Total);
}
}
You are trying to access array index 15 (so the 16th element in array) which is technically not there as index start from 0. So the last index you can access is 14. Total elements are 15 as initialized by your code.
Change your line :
Subtotal = Choice[1] + Choice[2] + Choice[3] + Choice[4] + Choice[5] + Choice[6] + Choice[7] + Choice[8] + Choice[9] + Choice[10] + Choice[11] + Choice[12] + Choice[13] + Choice[14] + Choice[15];
To:
Subtotal = Choice[0] + Choice[1] + Choice[2] + Choice[3] + Choice[4] + Choice[5] + Choice[6] + Choice[7] + Choice[8] + Choice[9] + Choice[10] + Choice[11] + Choice[12] + Choice[13] + Choice[14];
This will get the flow rolling. (Although I will confess, the code is not doing what it is meant to be doing by just reading your code. But that is a different matter.)
I've been working on a small bit of code that helps me calculate performance of a movie's Box-Office weekend. I want it to require the
Name of the movie
How much it'll cost to use
How much it's predicted to make that weekend
Then I want it to output all the above information, with the addition of each movie's performance. Well, I'm having issues with it saving multiple String[] values as well as int[] values. I can remove the String lines, and all the int[]'s (both the price and the prediction) work fine, or I can remove the int[]'s and the String[] works fine. Can anyone help me find my errors?
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[15];
int[] moviePrice = new int[15];
int[] moviePrediction = new int[15];
int[] moviePreformance = new int[15];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = console.nextInt();
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = console.nextInt();
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
When you used nextInt() and entered a number you also enterd a new line character, so the next time you called nextLine() this new line character was your next input waiting.
You could fix this by always using nextLine, or by adding a call for nextLine.
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[2];
int[] moviePrice = new int[2];
int[] moviePrediction = new int[2];
int[] moviePreformance = new int[2];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = Integer.parseInt(console.nextLine());
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = Integer.parseInt(console.nextLine());
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
This should fix the issue:
moviePrice[i] = console.nextInt();
console.nextLine();
moviePrediction[i] = console.nextInt();
console.nextLine();
console.nextInt() only reads the number, not the rest of the line, like carriage return.
Thank you some member help me to correct the code, but I have more questions to ask :
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import javax.swing.*;
public class Average2 {
public static void main(String args[]) {
int total;
int gradeCounter;
int grade = 0;
int result;
int passed = 0;
int failed = 0;
int absent = 0;
double average;
String gradeString;
String s1;
total = 0;
gradeCounter = 1;
gradeString = JOptionPane.showInputDialog("Enter Exam Marks first or -1 to Quit:");
grade = Integer.parseInt(gradeString);
String output = "Name of the Student\tExam Marks\n";
String ns = "No. of student passed: \t No. of students failed: \t No. of student Absent: \n";
if (grade != -1) {
s1 = JOptionPane.showInputDialog("Enter the Name of Student - ");
output += gradeCounter + "\t" + s1 + "\t" + gradeString + "\n";
ns = "no. of students passed:" + passed + "\n no. of students failed:" + failed + "\n no. of students absent:" + absent;
while (grade != -1) {
if(grade >= 40){
passed = passed + 1;
}
else if(grade > 0 && grade < 40){
failed = failed + 1;
}
else if(grade > 0 && grade <1){ //why grade can't check = 0??
absent = absent + 1; //
}
total = total + grade;
gradeCounter = gradeCounter + 1;
gradeString = JOptionPane.showInputDialog("Enter Exam Marks or -1 to Quit:" + gradeCounter);
grade = Integer.parseInt(gradeString);
if (grade == -1) {
break;
}
s1 = JOptionPane.showInputDialog("Enter the Name of Student - " + gradeString);
output += gradeCounter + "\t" + s1 + "\t" + gradeString + "\n";
ns = "no. of students passed:" + passed + "\n no. of students failed:" + failed + "\n no. of students absent:" + absent;
}
}
DecimalFormat twoDigits = new DecimalFormat("0.00");
if (gradeCounter != 0) {
average = (double) total / (gradeCounter-1);
JTextArea outputArea = new JTextArea();
outputArea.setText(output);
JOptionPane.showMessageDialog(null, outputArea,
"Analysis of Exam Marks", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, ns,
"Analysis of Exam Marks", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Class average is " + twoDigits.format(average), "Class Average",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "No grades were entered", "Class Average",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
http://i.stack.imgur.com/sn8VJ.png
http://i.stack.imgur.com/4yG6g.png
why if(grade = 0) will be error and the the result absent can't increase??
In this case, how to use the Math.squr to calculate standard deviation??
This is because you are reading the two inputs outside your while loop the first time and then replacing their values inside the while loop again.
gradeString = JOptionPane.showInputDialog("Enter Integer Grade or -1 to Quit:" );
s1 = JOptionPane.showInputDialog( "Enter the Name of Student - " );
grade = Integer.parseInt( gradeString );
You are appending these inputs to your output String only in the while loop and not outside.
You can do one of the following:
Append it to the output outside your while loop by doing:
String output = "Name of the Student\tExam Marks\n";
output += gradeCounter + "\t" + s1 + "\t" + gradeString + "\n";
Simple remove these statements as you are anyways calling them inside your while loop
Made the changes in the following version of the code. It should work as you wanted.
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
import javax.swing.*;
public class Average {
public static void main(String args[]) {
int total;
int gradeCounter;
int grade;
double average;
String gradeString;
String s1;
total = 0;
gradeCounter = 1;
gradeString = JOptionPane.showInputDialog("Enter Integer Grade or -1 to Quit:");
grade = Integer.parseInt(gradeString);
String output = "Name of the Student\tExam Marks\n";
if (grade != -1) {
s1 = JOptionPane.showInputDialog("Enter the Name of Student - ");
output = gradeCounter + "\t" + s1 + "\t" + gradeString + "\n";
while (grade != -1) {
total = total + grade;
gradeCounter = gradeCounter + 1;
gradeString = JOptionPane.showInputDialog("Enter Integer Grade or -1 to Quit:" + s1);
grade = Integer.parseInt(gradeString);
if (grade == -1) {
break;
}
s1 = JOptionPane.showInputDialog("Enter the Name of Student - " + gradeCounter);
output += gradeCounter + "\t" + s1 + "\t" + gradeString + "\n";
}
}
DecimalFormat twoDigits = new DecimalFormat("0.00");
if (gradeCounter != 0) {
average = (double) total / gradeCounter;
JTextArea outputArea = new JTextArea();
outputArea.setText(output);
JOptionPane.showMessageDialog(null, outputArea, "Analysis of Exam Marks", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Class average is " + twoDigits.format(average), "Class Average",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "No grades were entered", "Class Average",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
java.util.*;
import java.io.*;
public class Sites
{
String country2, city2;
int days2, count = 0, time = 10;
double rate2, scost = 0;
public Sites(String province, String city, int days, double rate)
{
country2 = province;
city2 = city;
days2 = days;
rate2 = rate;
}
public void Sites()
{
{
Scanner scan = new Scanner(System.in);
try
{
while(count == 0)
{
BufferedReader file2 = new BufferedReader(new FileReader ("Sites.txt"));
while(file2.ready())
{
String cityS = file2.readLine();
String site1 = file2.readLine();
String cost1 = file2.readLine();
double cost1a = Double.parseDouble(cost1);
double tcost1 = cost1a * rate2;
String site2 = file2.readLine();
String cost2 = file2.readLine();
double cost2a = Double.parseDouble(cost2);
double tcost2 = cost2a * rate2;
String site3 = file2.readLine();
String cost3 = file2.readLine();
double cost3a = Double.parseDouble(cost3);
double tcost3 = cost3a * rate2;
String wiggle = file2.readLine();
if (cityS.equalsIgnoreCase(city2))
{
System.out.println("Province/Territory: " + country2 + "Number of Days Left: " + days2);
System.out.println("City: " + city2 + "Time: " + time + ":00");
System.out.println("");
System.out.println("Where would you like to go?");
System.out.println("1)" + site1);
System.out.println("Cost) " +cost1 );
System.out.println("");
System.out.println("2)" + site2);
System.out.println("Cost) " +cost2 );
System.out.println("");
System.out.println("3)" + site3);
System.out.println("Cost) " +cost3 );
System.out.println("");
System.out.println("4)Eat");
System.out.println("Cost) 25 ");
System.out.println("");
System.out.println("5)Rest");
System.out.println("Cost) 0 ");
System.out.println("");
int answer = scan.nextInt();
ArrayList<String> array = new ArrayList<String>();
Eat food = new Eat(answer,city2,rate2,array);
Descriptions sum = new Descriptions(site1,site2,site3,answer);
switch(answer)
{
case 1: time = time + 2;
scost = scost + tcost1;
sum.Description();
array.add(site1);
System.out.println("");
break;
case 2: time = time + 2;
scost = scost + tcost2;
sum.Description();
array.add(site2);
System.out.println("");
break;
case 3: time = time + 2;
scost = scost + tcost3;
sum.Description();
array.add(site3);
System.out.println("");
break;
case 4: time = time + 2;
scost = scost + (rate2*25);
food.Eat();
break;
case 5: time = time + 2;
System.out.println("You rested for a couple of hours.");
break;
}
if(time == 22)
{
days2 = days2 - 1;
time = 10;
}
if(days2 == 0)
{
count++;
for (int i = 0; i < array.size(); i++)
{
System.out.println("Thank you for using the tourist simulator. You spent " + scost + " and visited " +array.get(i));
}
}
}
}
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
You are re-declaring your ArrayList every iteration of your loop.
Try declaring your ArrayList above your declaration of the Scanner.
e.g.
Move
ArrayList<String> array = new ArrayList<String>();
To just above
Scanner scan = new Scanner(System.in);