When I run this code and input the double value for the first variable i.e
miles It shows an error on the read.nextDouble() line as Exception in thread "main" java.util.InputMismatchException.
/**
* Created by Ranjan Yadav on 1.10.2016.
*/
public class GasMileage {
public static void main(String[] args){
java.util.Scanner read = new java.util.Scanner(System.in);
int counter = 0;
System.out.println("Miles Driven(press 1 to quit): ");
double miles = read.nextDouble();
double totalGalon = 0;
double totalMiles = 0;
double milesPerGalon = 0;
double totalMilesPerGalon = 0;
totalMiles += miles;
while(miles != 1){
System.out.println("Gallon used: ");
double galon = read.nextDouble();
counter++;
milesPerGalon = miles / galon;
totalMilesPerGalon += milesPerGalon;
System.out.println("Miles per gallon: " + milesPerGalon);
System.out.println("Miles Driven(press 1 to quit); ");
miles = read.nextDouble();
totalGalon += galon;
totalMiles += miles;
}
if(counter == 0 ){
System.out.println("No values were entered.\nThanks for Using!\n\n");
}else{
double avg = totalMilesPerGalon / counter;
System.out.printf("Total miles driven: %.2f" , totalMiles);
System.out.printf("Total gallons used: %.2f" , totalGalon);
System.out.printf("Miles per gallon for all trips: %.2f" , totalMilesPerGalon);
}
}
}
From the Javadoc:
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
Basically, you're inputting something that is not a number.
Related
I am a bit confused, I have a little program I wrote for a school assignment, the constraints I am required to work with is that no method can contain more than 15 lines of code, and we cannot use any for next loops.
What I cant seem to figure out is why I am able to pass an integer to my rounding method and it even returns the rounded value, but then it jumps back to my if / then statements (which it shouldnt be doing) and does not pass the variable.
It is a very rudimentary program I know...my coding skills are not very good, but any help would be appreciated.
The variables I need passed back are testscore and GPA, those need to go back to the main method so they can be stored to new variables and finally pushed off into the results method.
Im still pretty new to coding and the community and how things work...
import java.util.*;
public class Admit {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction();
double testscore = 0;
double GPA = 0;
int Student = 1;
ACTSATScores(1,0,console);
double StudentOneTestScore = testscore;
GPAInfo(0,console);
double StudentOneGPAScore = GPA;
Student = 2;
ACTSATScores(2,0,console);
double StudentTwoTestScore = testscore;
GPAInfo(0,console);
double StudentTwoGPAScore = GPA;
DisplayResults(StudentOneTestScore,StudentOneGPAScore,StudentTwoTestScore,StudentTwoGPAScore);
}
public static void Introduction() {
System.out.println("This program compares two applicants to");
System.out.println("determine which one seems like the stronger");
System.out.println("applicant. For each candidate I will need");
System.out.println("either SAT or ACT scores plus a weighted GPA.");
System.out.println();
}
public static double ACTSATScores(int Student,double testscore,Scanner console) {
System.out.println("Information for applicant #" + Student + ":");
System.out.print("do you have 1) SAT scores or 2) ACT scores? ");
int ACTSAT = console.nextInt();
if ( ACTSAT == 1) {
SAT(Student,testscore,console);
}
if ( ACTSAT == 2) {
ACT(Student,testscore,console);
}
return testscore;
}
public static double SAT(int Student,double testscore,Scanner console) {
System.out.print("SAT math? ");
int SATMath = console.nextInt();
System.out.print("SAT critical reading? ");
int SATReading = console.nextInt();
System.out.print("SAT writing? ");
int SATWriting = console.nextInt();
testscore = ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
System.out.println("exam score = " + roundNumber(testscore));
return ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
}
public static double ACT(int Student,double testscore,Scanner console) {
System.out.print("ACT English? ");
int ACTEnglish = console.nextInt();
System.out.print("ACT math? ");
int ACTMath = console.nextInt();
System.out.print("ACT reading? ");
int ACTReading = console.nextInt();
System.out.print("ACT science? ");
int ACTScience = console.nextInt();
testscore = ( ( 2 * ACTMath + ACTEnglish + ACTReading + ACTScience ) / 1.8 );
System.out.println("exam score = " + roundNumber(testscore));
return testscore;
}
public static double GPAInfo(double GPA,Scanner console) {
System.out.print("overall GPA? ");
double OverallGPA = console.nextDouble();
System.out.print("max GPA? ");
double MaxGPA = console.nextDouble();
System.out.print("Transcript Multiplier? ");
double TranscriptMultiplier = console.nextDouble();
GPA = ( OverallGPA / MaxGPA * 100 * TranscriptMultiplier );
System.out.println("GPA score = " + roundNumber(GPA));
return GPA;
}
public static double roundNumber(double number) {
return (Math.round(number * 10)) / 10.0;
}
public static double DisplayResults(double StudentOneTestScore, double StudentOneGPAScore, double StudentTwoTestScore, double StudentTwoGPAScore) {
System.out.println("First applicant overall score = " + StudentOneTestScore + StudentOneGPAScore);
System.out.println("Second applicant overall score = " + StudentTwoTestScore + StudentTwoGPAScore);
if ( StudentOneTestScore + StudentOneGPAScore > StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The first applicant seems to be better");
}
else if ( StudentOneTestScore + StudentOneGPAScore < StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The second applicant seems to be better");
}
else {
System.out.println("The two applicants seem to be equal");
}
return StudentOneTestScore;
}
}
Expected output:
This program compares two applicants to
determine which one seems like the stronger
applicant. For each candidate I will need
either SAT or ACT scores plus a weighted GPA.
Information for applicant #1:
do you have 1) SAT scores or 2) ACT scores? 1
SAT math? 450
SAT critical reading? 530
SAT writing? 490
exam score = 60.0
overall GPA? 3.4
max GPA? 4.0
Transcript Multiplier? 0.9
GPA score = 76.5
Information for applicant #2:
do you have 1) SAT scores or 2) ACT scores? 2
ACT English? 25
ACT math? 20
ACT reading? 18
ACT science? 15
exam score = 54.4
overall GPA? 3.3
max GPA? 4.0
Transcript Multiplier? 0.95
GPA score = 78.4
First applicant overall score = 136.5
Second applicant overall score = 132.8
The first applicant seems to be better
My output
This program compares two applicants to
determine which one seems like the stronger
applicant. For each candidate I will need
either SAT or ACT scores plus a weighted GPA.
Information for applicant #1:
do you have 1) SAT scores or 2) ACT scores? 1
SAT math? 450
SAT critical reading? 530
SAT writing? 490
exam score = 60.0
overall GPA? 3.4
max GPA? 4.0
Transcript Multiplier? 0.9
GPA score = 76.5
Information for applicant #2:
do you have 1) SAT scores or 2) ACT scores? 2
ACT English? 25
ACT math? 20
ACT reading? 18
ACT science? 15
exam score = 54.4
overall GPA? 3.3
max GPA? 4.0
Transcript Multiplier? 0.95
GPA score = 78.4
First applicant overall score = 0.00.0
Second applicant overall score = 0.00.0
The two applicants seem to be equal
Corrected Code for anyone that needs it
import java.util.*;
public class Admit {
public static void main(String[] Args) {
Scanner console = new Scanner(System.in);
Introduction();
int Student = 1;
double StudentOneTestScore = ACTSATScores(1,console);
double StudentOneGPAScore = GPAInfo(0,console);
Student = 2;
double StudentTwoTestScore = ACTSATScores(1,console);
double StudentTwoGPAScore = GPAInfo(0,console);
DisplayResults(StudentOneTestScore,StudentOneGPAScore,StudentTwoTestScore,StudentTwoGPAScore);
}
public static void Introduction() {
System.out.println("This program compares two applicants to");
System.out.println("determine which one seems like the stronger");
System.out.println("applicant. For each candidate I will need");
System.out.println("either SAT or ACT scores plus a weighted GPA.");
System.out.println();
}
public static double ACTSATScores(int Student,Scanner console) {
double testscore = 0;
System.out.println("Information for applicant #" + Student + ":");
System.out.print(" do you have 1) SAT scores or 2) ACT scores? ");
int ACTSAT = console.nextInt();
if ( ACTSAT == 1) {
testscore = SAT(console);
}
if ( ACTSAT == 2) {
testscore = ACT(console);
}
return testscore;
}
public static double SAT(Scanner console) {
System.out.print(" SAT math? ");
int SATMath = console.nextInt();
System.out.print(" SAT critical reading? ");
int SATReading = console.nextInt();
System.out.print(" SAT writing? ");
int SATWriting = console.nextInt();
double testscore = ( ( 2 * SATMath + SATReading + SATWriting ) / 32);
System.out.println(" exam score = " + roundNumber(testscore));
return testscore;
}
public static double ACT(Scanner console) {
System.out.print(" ACT English? ");
int ACTEnglish = console.nextInt();
System.out.print(" ACT math? ");
int ACTMath = console.nextInt();
System.out.print(" ACT reading? ");
int ACTReading = console.nextInt();
System.out.print(" ACT science? ");
int ACTScience = console.nextInt();
double testscore = ( ( 2 * ACTMath + ACTEnglish + ACTReading + ACTScience ) / 1.8 );
System.out.println(" exam score = " + roundNumber(testscore));
return testscore;
}
public static double GPAInfo(double GPA,Scanner console) {
System.out.print(" overall GPA? ");
double OverallGPA = console.nextDouble();
System.out.print(" max GPA? ");
double MaxGPA = console.nextDouble();
System.out.print(" Transcript Multiplier? ");
double TranscriptMultiplier = console.nextDouble();
GPA = ( OverallGPA / MaxGPA * 100 * TranscriptMultiplier );
System.out.println(" GPA score = " + roundNumber(GPA));
System.out.println();
return GPA;
}
public static double roundNumber(double number) {
return (Math.round(number * 10)) / 10.0;
}
public static double finalScore(double TestScore, double GPAScore) {
return TestScore + GPAScore;
}
public static double DisplayResults(double StudentOneTestScore, double StudentOneGPAScore, double StudentTwoTestScore, double StudentTwoGPAScore) {
double StudentOneScore = finalScore(StudentOneTestScore,StudentOneGPAScore);
double StudentTwoScore = finalScore(StudentTwoTestScore,StudentTwoGPAScore);
System.out.println("First applicant overall score = " + roundNumber(StudentOneScore)); //StudentOneTestScore + StudentOneGPAScore);
System.out.println("Second applicant overall score = " + roundNumber(StudentTwoScore)); //StudentTwoTestScore + StudentTwoGPAScore);
if ( StudentOneTestScore + StudentOneGPAScore > StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The first applicant seems to be better");
} else if ( StudentOneTestScore + StudentOneGPAScore < StudentTwoTestScore + StudentTwoGPAScore ) {
System.out.println("The second applicant seems to be better");
} else {
System.out.println("The two applicants seem to be equal");
}
return StudentOneTestScore;
}
}
It seems you have a problem when using methods, returning types and inmutable types.
In the main section:
double testscore = 0;
double GPA = 0;
int Student = 1;
ACTSATScores(1,0,console);
double StudentOneTestScore = testscore;
GPAInfo(0,console);
double StudentOneGPAScore = GPA;
Student = 2;
ACTSATScores(2,0,console);
double StudentTwoTestScore = testscore;
You are assigning those variables the value "testscore". But you really never change that value, and the way you wrote the methods makes me believe that you are expecting testscore to change inside the methods.
Try printing the value of testscore in the main to see that it does not change its value (it should be always 0 in that main). This might be what you are looking for:
double StudentOneTestScore = ACTSATScores(1,0,console);
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);
Im trying to write a code, that computes CD value, for every month.
Suppose you put 10,000 dollars into a CD with an annual percentage yield of 6,15%.
After one month the CD is worth:
10000 + 10000 * 6,15 / 1200 = 10051.25
After the next month :
10051.25 + 10051.25 * 6,15 / 1200 = 10102.76
Now I need to display all the results for the specific number of months entered by the user,
So
month1 =
month2 =
But whth this code I wrote, nothing is printed.
Can you see what's wrong?
Thanks in advance!
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
while (i != months) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
You do not modify neither i nor months in
while (i != months) {
....
}
so if the (i != months) condition is satisfied, the loop runs forever, and you never get to System.out.print statement.
for (int i = 1; i < months; i++) {
while (i != months) {
//you have to modify i or to modify the while condition.
}
if you don't modify i in the while you can't exit from the loop
Corrected code-
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}
Note: If you want to print values for each month then the print statement should be inside the loop. You don't need two loops for the objective that you have mentioned above.
As you have been told your code won't get out of the while loop if you don't modify it. Simply remove the while loop. Your code should be like this:
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextDouble();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}
Thanks! Solved it by using
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
instead of while loop.
It works now :) Thanks so much!
I am creating a simple commissions calculator, whereas, one can input the final sales price of an infinite amount of sales; then at the end it prints out the total amount of the commission plus a base pay rate ($200).
Here is my initial code:
import java.util.Scanner;
public class AssignmentsModule2_Program2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Intialization Phase
double sold = 0;
double soldCounter = 0;
double baseRate = 200.00;
double commissionRate = 0.09;
System.out.print("Enter total of sold item or -1 if done: ");
int value = input.nextInt();
while (sold != -1)
{
sold = sold + value;
soldCounter = soldCounter + 1;
System.out.print("Enter price of sold item or -1 if done: ");
value = input.nextInt();
}
double totalCommission = sold * commissionRate + baseRate;
System.out.printf("%nTotal pay for the week is: %d%n", sold);
}
}
Unfortunately, when I run the program an error code appears.
Here is the error code:
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 assignmentsmodule2_program2.AssignmentsModule2_Program2.main(AssignmentsModule2_Program2.java:31)
Java Result: 1
Is there anyone out there who can lend some help?
Thanks.
You program is expecting an integer as input. The exception is thrown when a float or a char is used as input. I would use double variable:
import java.util.Scanner;
public class AssignmentsModule2_Program2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Intialization Phase
double sold = 0.0;
int soldCounter = 0;
double baseRate = 200.00;
double commissionRate = 0.09;
System.out.print("Enter total of sold item or -1 if done: ");
double value = input.nextDouble();
while (value > 0)
{
sold = sold + value;
soldCounter = soldCounter + 1;
System.out.print("Enter price of sold item or -1 if done: ");
value = input.nextDouble();
}
double totalCommission = sold * commissionRate + baseRate;
System.out.printf("%nTotal pay for the week is: %f%n", sold);
}
}
I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}