I want to know how to read a number from 1 to trillions in My Java application without an error.
This is the part of my code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter your money value : ");
long value = sc.nextInt();
System.out.print("Your money in String : "+value);
If I enter a value from about 1 to 2.111.111.999 it works fine but
every time I run it and enter greater than that, there's this error message :
Exception in thread "main" java.util.InputMismatchException: For input string: "1000000000000"
at java.util.Scanner.nextInt(Scanner.java:2097)
at java.util.Scanner.nextInt(Scanner.java:2050)
at konversiangka.Konversiangka.main(Konversiangka.java:28)
Java Result: 1
I guess this is a "data type" mistake.
I know if you want to store a trillion in a long data type you have to add "L" in the end
of the value, like this, "1000000000000L". But I don't want User to add that when they enter a value on the program,
So can you help Me how to do that?
I Appreciate any suggestion and correction, thanks.
Use
long value = sc.nextLong();
instead.
The reason for the error is that the maximum value that can be put into an int is 2,147,483,647, and even though you declared the variable as a long, Scanner.nextInt() always tries to convert the number into an int.
You can use a long as Tharwen mentioned or you can use java.math.BigDecimal. BigDecimal is a class made for holding a decimal number as big (or small) as you want. You can see all the primitive data types and their max/min size here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Scanner sc = new Scanner(System.in);
System.out.print("Enter your money value : ");
BigDecimal value = sc.nextBigDecimal();
System.out.print("Your money in String : "+value);
Output:
Enter your money value : 271075217301782039710237102710521231.23
Your money in String : 271075217301782039710237102710521231.23
Related
I'm running this in VS code and compiling and running through terminal with the proper JDK installed but nothing seems to run it just goes blank and then I type "clear" and a mismatch exception is thrown. Can someone explain why? Thank you :)
import java.util.Scanner;
class realTime {
public static void Time(int seconds) {
int min = 0, hours = 0;
min = (int)seconds / 60;
hours = (int)seconds / 3600;
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + min);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int seconds = scan.nextInt();
Time(seconds);
}
}
I know that it will not calculate the min and hours correctly I'm just putting code down to test whether it runs.
Because the terminal is waiting for some value, in this lines:
Scanner scan = new Scanner(System.in);
int seconds = scan.nextInt();
Basically you're creating a Scanner object, and declaring an int variable waiting for a value, in this case a next integer, to do something.
Just type some integer number in your terminal and it should be working fine.
In the terminal the scanner is waiting for the user input which is of type int, you need to enter the seconds in the terminal.
The error is showing because you are entering String type value but the scanner is expecting int type.
Hope this resolve the issue.
The solution is already present in other answers, but why the InputMismatchException is what this answer is about.
From the docs,
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
For nextInt()
public int nextInt()
Scans the next token of the input as an int.
Throws: InputMismatchException - if the next token does not match the
Integer regular expression, or is out of range
Here "clear" does not match the regular expression of Integer.
Since you are not passing any radix to nextInt() method, it expects the input to have only 0-9 (Decimal Number System- Base 10 is the default). Had it been nextInt(16), It would accept any HexaDecimal (0-F, Base 16) Number and so on.
It is worth noting the another case where you can get the same Exception, This happens if the input > Integer.MAX_VALUE.
You need to have a prompt for the user to enter in there time in seconds so your scanner can actually get something to put in for your seconds int. Do something like this:
System.out.println("Enter seconds to convert");
int seconds = scan.nextInt();
I pretty new to java programming so i was wondering if there is a way to use the condition of a while loop to stop an invalid value being used.
I am writing a program that prompts the user to enter an identification number as an integer then uses a scanner to store that value.
Just wanted to know if this is possible to put something in the condition of the for loop that prints an error message if the enter something like a string, double or char so i dont get the Input Mismatch Exception.
like this:
identification = userId(in); //scanner
while (identification (is not an integer)){
System.out.println("Invalid Value, Please enter an integer");
identification = userId(in);
Even better, you can write:
while ((identification = userId(in)) < 0) {
System.out.println("blah ...");
}
The assumption is that the userIn method returns some negative value if the input is not an integer. You can make the invalid return value whatever you want as long as it is not something that is a valid input.
Some people don't like this style because it has gone out of fashion and they are not used to it; however, it used to be common in C programming and there is nothing about it that is implicitly unclear or bad.
This should do what you are asking. It is basically a while loop that waits until the next input is an integer before continuing the code. The important part is making sure to use in.next() inside the while loop instead of in.nextInt() because the values could be anything.
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (!(in.hasNextInt()))
{
System.out.print("Integer not entered, please enter an integer: ");
in.next();
}
int value = in.nextInt();
System.out.println("The int was " + value);
in.close();
I have a problem I sort of half fixed? It's more of a logic error, I think. My program overall is running smoothly, but I need to fix the flow of how my program interprets user input.
This program should report user error if they input a non numerical value or a negative number. And if the user enters 0, then is should accept it as a correct answer ( I have yet to figure out how to do that since my condition is whether or not it's a double).
I'm trying to differentiate between whether the user inputs a negative number or a character in the feedback. So far, I've made a loop to continuously prompt the user to enter a number if they don't input a double. Though I'm not sure how to go about accepting a 0 as an answer and filtering out negative numbers. I went back to my flow diagram and figured I may need to use an if-else statement to do this. But how can I do that while keeping the loop going? I'm not totally sure how I'm suppose to format that kind of thing.
Help is appreciated for this newbie! Thank you!
while(looping){
// Prompt user to enter how many grades they want averaged
System.out.println("How many grades would you like to average? ");
// Check if the input variables are positive numerical variables
// Or else report to user to input a number
while(!input.hasNextDouble()) //cannot be negative
{
input.next();
System.out.println("Please enter a number: ");
}
gradeNumber = input.nextInt();
// Prompt user to enter the grades
System.out.println("Please enter " + gradeNumber + " grades: ");
// Use a for-loop to control how many loops - reference to gradeNumber
for(gradesCount = 0; gradesCount < gradeNumber; gradesCount++){
// Check if the input variables are numerical variables
while (!input.hasNextDouble())
{
input.next();
System.out.println("Please enter a number: ");
}
gradesInput = input.nextDouble();
finalGrades = finalGrades + gradesInput;
} // end loop
I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
I want to make a program which keeps prompting the user to input integers(from CUI) until it receives a 'X' or 'x' from the user.
The program then prints out the maximum number, minimum number and average value of the input numbers.
I did manage to get the user to input numbers until someone types 'X', but I can't seem to get it to stop if someone types 'x' and the second bit.
This is the code that I have managed to work out:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!in.hasNext("X") && !in.hasNext("x"))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Any hints on how I proceed further?
You will need to do something like this:
Scanner in = new Scanner(System.in);
System.out.println("Enter a number")
while(!(in.hasNext("X") || in.hasNext("x")))
s = in.next().charAt(0);
System.out.println("This is the end of the numbers");
Whenever you use while loop you have to use the {} in case the arguments in the while block are more than 1 line, but if they are just of a line then you can just go on without using the {}.
But the problem, you had I suppose is the use of && instead of ||. What the && (AND) operator does is execute if both the statements are true but a || (OR) Operator works if any of the conditions are true.
If you say while(!in.hasNext("X") && !in.hasNext("x")) it makes no sense as the user input is not both at the same time, but instead if you usewhile(!in.hasNext("X") || !in.hasNext("x"))` it makes sense. Understood?
And about sorry, im really new at this. but ive added the code No problem, you need not say sorry but there are a few things to keep in mind before asking a question. You must read this https://stackoverflow.com/help/how-to-ask and yeah one more thing, you should use proper English Grammar while framing your question.
Last of all, about how to calculate the average..., for that what you need to do is store all the input variables into an array and then take out the mean of that or alternatively you could think about it and code something up yourself. Like to take out mean, you could make a variable sum and then keep adding the integers the user enters and also keep a variable count which will keep the count of the number of integers entered and then at last you could divide both of them to have your answer
Update: For checking the minimum and the maximum, what you can do is make 2 new variables like int min=0, max=0; and when the user enters a new variable you can check
//Note you have to change the "userinput" to the actual user input
if(min>userinput){
min=userinput;
}
and
if(max<userinput){
max=userinput;
}
Note: At stackoverflow we are there to help you out with the problems you are facing BUT you cannot exploit this. You cannot just post your homework here. But if you are trying to code something up and are stuck at it and cannot find a answer at google/stackoverflow then you can ask a new question and in that you need to tell what all you have already tried. Welcome to SO! :D Hope you have a nice time here
This would fit your needs:
public void readNumbers() {
// The list of numbers that we read
List<Integer> numbers = new ArrayList<>();
// The scanner for the systems standard input stream
Scanner scanner = new Scanner(System.in);
// As long as there a tokens...
while (scanner.hasNext()) {
if (scanner.hasNextInt()) { // ...check if the next token is an integer
// Get the token converted to an integer and store it in the list
numbers.add(scanner.nextInt());
} else if (scanner.hasNext("X") || scanner.hasNext("x")) { // ...check if 'X' or 'x' has been entered
break; // Leave the loop
}
}
// Close the scanner to avoid resource leaks
scanner.close();
// If the list has no elements we can return
if (numbers.isEmpty()) {
System.out.println("No numbers were entered.");
return;
}
// The following is only executed if the list is not empty/
// Sort the list ascending
Collections.sort(numbers);
// Calculate the average
double average = 0;
for (int num : numbers) {
average += num;
}
average /= numbers.size();
// Print the first number
System.out.println("Minimum number: " + numbers.get(0));
// Print the last number
System.out.println("Maximum number: " + numbers.get(numbers.size() - 1));
// Print the average
System.out.println("Average: " + average);
}