InputMismatchException Error Data Types - java

I'm playing around with Java for the first time and an error is appearing. I don't understand why.
The error is:
java.util.InputMismatchException
It says that the problem is in line 20 ("price = in.nextDouble();"), but I can't understand the problem.
It looks like that the problem happens after I insert the number of days, the cost per day and I used decimal, I put for example 34.98. Isn't the point of using double to be able to use decimal numbers?
Here is the code:
int days;
double price;
System.out.println("How many days you will be here?");
Scanner in = new Scanner(System.in);
days = in.nextInt();
System.out.println("How much you can afoord per day?");
price = in.nextDouble();
double total = price * days;
System.out.println("Youll be paying "+ total);

This code works fine for me
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
int days;
double price;
System.out.println("How many days you will be here?");
Scanner in = new Scanner(System.in);
days = in.nextInt();
System.out.println("How much you can afoord per day?");
price = in.nextDouble();
double total = price * days;
System.out.println("Youll be paying "+ total);
}
}
Output
Executing Build Command: javac /root/HelloWorld.java
How many days you will be here?
3
How much you can afoord per day?
34.98
Youll be paying 104.94
Process exited successfully

So i found the problem, i had to add after Scanner... "in.useLocale(Locale.US);"
That is why it got this error.

Related

Program getting stuck in while loop?

I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.

New to Java Programming, having math coding issues

Please be gentle as this is my first programming class and my first time ever doing something like this.
I'm tasked with creating a java program (only my second week of this class) with creating a cell phone plan based off of the mins a user puts in.
Basic Talk is 400 mins, $30 and 0.35 per min over.
Standard Talk is 600 min, for $40 and 0.30 per min over.
Unlimited is anything over 600 mins for $60 per min.
The issue I'm having is the math portion of this. No matter what I put in for the number of mins, it always returns the same dollar amount to pay, which is $140.
I have tried all various types of suggestions on the web, with the same result.
My code might be messy and I do apologize, as I said, I've been trying a variety of different things and said I would go back and clean it up some when I got this working correctly.
I need to show the amount of min entered by the user, then show them the best plan based off the mins they entred and how much they can expect to pay.
Any help would be greatly appreciated. I've been racking my brains for 3 days now and it's due by midnight Monday.
import java.util.Scanner;
import java.util.Formatter;
public class Java_Lab_2 {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
// Different Talk Plans
final double basicTalk = 30.00;
final double standardTalk = 40.00;
final double unlimtedTalk = 60.00;
final double basicextramin = 0.35;
final double standardextramin = 0.30;
// Minutes per plan
int basicMinutes;
basicMinutes = 400;
int standardMinutes;
standardMinutes = 600;
String unlimitedMinutes = "unlimited";
// Extra Charge per min per plan
String unlimited = "included";
//Number of minutes Basic
int numberOfMins = 0;
int extraMins = (basicMinutes-numberOfMins);
double extraMinCharge = (extraMins * basicextramin);
// Get number of minutes spent
System.out.println("How many talk minutes do you use per month?");
numberOfMins = scan.nextInt();
// Best Plan
if (numberOfMins <= 400) {
System.out.println("The best plan (s) for you is Basic Talk ");
System.out.println("Expect to pay $" + basicTalk);}
if ((numberOfMins > 401) &&(numberOfMins <428)) {
System.out.println("The best plan (s) for you is Basic Talk");
System.out.format("Expect to pay $%-5.2f", + extraMinCharge);
There is an order issue in your code: you do
int numberOfMins = 0;
int extraMins = (basicMinutes-numberOfMins);
double extraMinCharge = (extraMins * basicextramin);
You need to reorder this so that you have something like
System.out.println("How many talk minutes do you use per month?");
int numberOfMins = scan.nextInt();
int extraMins = (basicMinutes-numberOfMins);
double extraMinCharge = (extraMins * basicextramin);
So that you are not calculating with number of minutes set first, otherwise you are calculating with number of minutes set to 0.

how to Calculate speed and distance traveled in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
how do you write a program that prompts for and reads integer values for speed and distance traveled, then prints the time required for the trip as a floating point result in java using eclipse
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Lab3 {
public static void main(String[] args) {
int time = 0;
int distance = 0;
int speed = distance/time;
float fval = speed * time;
double dval = distance/speed;
String message;
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter Your Avaerage Speed: ");
message = scan.nextLine();
System.out.println("You Entered: \"" + message + "\"");
System.out.println("Your Total Speed is: ");
Here are some hints:
You haven't finished your code.
You need a closing } for each {.
Include the value you want to output here:
System.out.println("Your Total Speed is: ");
Hint: the string concatenation operator is .... ?
Hint: you can't calculate the speed before you know what the distance and time values are. speed = distance/time; is an assignment statement, not an equation.
it's crashing. My console isn't able to take data or input
The code you showed us doesn't compile. You can't run it ... so it can't be crashing. Hint: show us the real code. All of it.
If it is crashing, then there must be a stacktrace. The stacktrace contains important information that will help us (and you) identify the cause of the problem. Put all important information into the Question. Use the Edit button.
My guess is that an ArithmeticException is being thrown here
int speed = distance/time;
because you are dividing by zero. You are dividing by zero, because on the line before you set time to zero. Explicitly.
Please read what I wrote above ("4. Hint: ...") about not doing calculations before you have the inputs.
package stackoverflow;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please Enter speed: ");
int speed = in.nextInt();
System.out.print("Please Enter distance: ");
int distance = in.nextInt();
float time = (float)distance / speed;
System.out.println("Your time is: " + time);
}
}

How to get a remainder in java

The Student Union is organising a student trip and they are determining how many cars are required.
Prompt the user to enter the total number of students going on the trip.
Then determine how many cars are required (5 to a car) and how many students are left without transport.
import java.util.Scanner;
class P2Trip
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
int students;
int space = 5;
int sum;
System.out.println("How many students are going today?: ");
students = input.nextInt();
sum =(students / space);
System.out.println("Ammount of cars needed: " + sum);
}
}//code works fine, but im not sure how to get a remainder of students without a lift.
From your comment, it looks like you just need help with who will be left without a car. You need to use modular division (some people call it remainder) with the percent sign (%). Here is the line of code you are missing:
System.out.println("Amount of people without a car: "+students%sum);
The full code for the program is:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) [
Scanner s=new Scanner(System.in);
int carCapacity=5;
System.out.println("How many students?");
int students=s.nextInt();
int cars=students/carCapacity;
int leftOver=students%carCapacity;
System.out.println("Cars needed: "+cars);
System.out.println("Students left over: "+leftOver);
}
}
Have a look at the remainder/modulo operator here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
In my view, there are two corrections you can do in your program:
sum = (student/space);
int leftstudent;`
leftstudent=(students%space);
System.out.println("left students without transport are " +leftstudent);
You might want to check the modular division operator in Java.
Division / Divisor = coefficient
Division % Divisor = remainder
To find the remainder of number students for example you will have to use "%".

Can't understand this scanner or addition command

I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));

Categories