I am trying to get the regular expression for floats to work. I keep getting an error
Cannot invoke matches(String) on the primitive type float.
Any help? I'm kinda lost.
System.out.print("Enter $ amount of loan:");
payment = scanner.nextFloat();
while (!Regulations.paymentmatch(payment)) {
System.out.println("Information Not Correctly Entered");
System.out.printf("Please try again: ");
payment = scanner.nextFloat();
}
public static boolean paymentmatch(float a) {
return a.matches("\\d+.?\\d{2}");
}
If you want to allow the user to type a non-float value and then read it and tell them it's not a valid float value, you can't use nextFloat to read it, because...if it's not a valid float value, it won't work.
Either use hasNextFloat, which will tell you whether the scanner can read a float (but won't let you tell the user they typed something that wasn't a float), or use nextLine to read whatever they typed (as a String) and then validate that (via matches).
Related
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 want to create a Java program where
a user will input something and the output will show what type of data the input is..?
For example:
Input: 25
Output: integer
Input: ABC
Output: string
Input: 12.7
Output: float/double.
Please help as I am clueless on how to work this out
This should work for your purpose:
import java.util.Scanner;
public class DataType
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
if(in.hasNextByte(2))
System.out.println("Byte");
else if(in.hasNextInt())
System.out.println("Integer");
else if(in.hasNextFloat())
System.out.println("Float");
else if(in.hasNextBoolean())
System.out.println("Boolean");
else if(in.hasNext())
System.out.println("String");
}
}
Note that the order of if...else statements is very important here because of the following set relations with respect to patterns:
All byte patterns can be integers
All integer patterns can be floats
All float patterns can be Strings
All booleans can be Strings
There are quite a lot of hasNext..() methods in the Scanner class, such as BigInteger, short, and so on. You may refer the Scanner class documentation for further details.
A simple approach could go like this; starting with some input string X.
If X can be parsed as Integer --> it is an int/Integer
Then you try Long
Then Float
Then Double
If nothing worked, you probably have a string there
( with "parsing" I mean using methods such as Integer.parseInt() ... you pass in X; and when that method doesn't throw an exception on you, you know that X is an Integer/int )
But: such a detection very much depends on your definition of valid inputs; and potential mappings. As there zillions of ways of interpreting a string. It might not be a number; but given a correct format string ... it could be timestamp.
So the very first step: clarify your requirements! Understand the potential input formats you have to support; then think about their "mapping"; and a potential check to identify that type.
You can get a string and try to parse it as other types:
Scanner s = new Scanner(System.in);//allows user input
input = s.nextLine();//reads user input
try{//java will try to execute the code but will go to the catch block if there's an exception.
int inputInt = Integer.parseInt(input);//try to convert input to int
catch(Exception e){
e.printStackTrace();//this tell you exactly what went wrong. If you get here, then the input isn't an integer.
}
//same with double
This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 7 years ago.
I'm writing a program in which I need to take input from the keyboard. I need to take a number in, yet I'm not sure if it's an int or a double. Here's the code that I have (for that specific part):
import java.io.*;
import java.util.*;
//...
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
I know I can get a String and do parseInt() or parseDouble(), but I don't know which one it'll be.
Well, ints are also doubles so if you assume that everything is a double you will be OK with your logic. Like this:
import java.io.*;
import java.util.*;
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
It only get complex if you needed the input to be an integer for whatever reason. And then, parseInt() to test for int would be just fine.
Just use a double no matter what it is. There is no noticeable loss on using a double for integral values.
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
Then, if you need to know whether you've gotten a double or not, you can check it using Math.floor:
if (choice == Math.floor(choice)) {
int choiceInt = (int) choice);
// treat it as an int
}
Don't mess with catching NumberFormatException, don't search the string for a period (which might not even be correct, for example if the input is 1e-3 it's a double (0.001) but doesn't have a period. Just parse it as a double and move on.
Also, don't forget that both nextInt() and nextDouble() do not capture the newline, so you need to capture it with a nextLine() after using them.
What I would do is get String input, and parse it as either a double or an integer.
String str = input.next();
int i = 0;
double d = 0d;
boolean isInt = false, isDouble = false;
try {
// If the below method call doesn't throw an exception, we know that it's a valid integer
i = Integer.parseInt(str);
isInt = true
}catch(NumberFormatException e){
try {
// It wasn't in the right format for an integer, so let's try parsing it as a double
d = Double.parseDouble(str);
isDouble = true;
}catch(NumberFormatException e){
// An error was thrown when parsing it as a double, so it's neither an int or double
System.out.println(str + " is neither an int or a double");
}
}
// isInt and isDouble now store whether or not the input was an int or a double
// Both will be false if it wasn't a valid int or double
This way, you can ensure that you don't lose integer precision by just parsing a double (doubles have a different range of possible values than integers), and you can handle the cases where neither a valid integer or double was entered.
If an exception is thrown by the code inside the try block, the code in the catch block is executed. In our case, if an exception is thrown by the parseInt() method, we execute the code in the catch block, where the second try-block is. If an exception os thrown by the parseDouble() method, then we execute the code inside the second catch-block, which prints an error message.
You could try using the floor function to check if it is a double. In case you don't know, the floor function basically cuts off any decimal numbers. So you can compare the number with and without the decimal. If they are the same, then the number can be treated as an integer, otherwise a double (assuming you don't need to worry about large numbers like longs).
String choice = input.nextLine();
if (Double.parseDouble(choice) == Math.floor(Double.parseDouble(choice)) {
//choice is an int
} else {
//choice is a double
}
After programming in C++ for a few months, and getting to an intermediate level, I decided to start learning Java. I'm having some trouble wrapping my head around how the scanner variable works. In C++, "cin>>" was very straightforward in the fact that it would store whatever the input was, into a previously declared variable. However, in Java a variable itself is a scanner? How does that work? Also, what is the purpose of having ".nextDouble" after telling the scanner where to store the variable? I learned it from a tutorial, and here's my code below.
import java.util.Scanner;
class calculator {
public static void main(String args[]) {
Scanner var = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Enter first number: ");
fnum = var.nextDouble();
System.out.println("Enter second number: ");
snum = var.nextDouble();
answer = fnum+snum;
System.out.println(answer);
}
}
Scanner var = new Scanner(System.in);
At this point values won't be read. Assume like this opens a stream (or) pipe between console and your program.
fnum = var.nextDouble();
Tells JVM that, now go and get the next available double value from the stream named as var (java terminology, reference) and store that value to fnum.
var is a reference to a Scanner object that helps abstract the reading of tokenized input from a source (in this case the default input stream, System.in).
The call to .nextDouble() waits for a value to be inputted (e.g. from a prompt, or piped into stdin). Once input, the value will be stored in the assigned property (i.e. fnum or snum).
If the value's not parseable as a double, an InputMismatchException will be thrown.
Here's a briefly annotated version of your source that explains what's happening:
// Create a new Scanner object that will read input from System.in (stdin).
Scanner var = new Scanner(System.in);
// Declare some variables. The scanner hasn't done anything significant yet.
double fnum, snum, answer;
// Print a line to stdout.
System.out.println("Enter first number: ");
// Block until the scanner (i.e. stdin) receives a token. By default, the
// Scanner will use whitespace to tokenize anything that comes in on
// System.in. nextDouble() will try to parse the first available token
// into a double. If the parsing succeeds, assign the parsed value to fnum.
fnum = var.nextDouble();
// Same thing as above, but for snum.
System.out.println("Enter second number: ");
snum = var.nextDouble();
...
It may not hurt to read through the class documentation for Scanner to help provide some context about what a Scanner is and how it works.
Calling var.nextDouble() causes the next double value to be read from the input and its value returned. You then need to store the value somewhere (or not, if you just want to throw it away). There's no place where you are "telling the scanner where to store the variable".
Something that a person who knows C++ at an "intermediate level" should know: cin is a global variable, >> is a method call masquerading as an operator, and the "variable" is a reference parameter of that method call.
In Java there are no unqualified global variables, method calls follow the object.method(params) format, and there's no pass-by-reference.
nextDouble() is a method of the class Scanner that returns the next scanned double. Basically the class Scanner is doing the cin type stuff for you but you don't see the inner workings of it. It's as if you wrote a class in C++ to handle the cin for you and now you are just using that class.
Here as a beginner it is okay that you got confused. First thing is why we use scanner?. We use scanner class when the program wants to get an user input. just like program asks you "what is your name?" you type Peter. Then program can respond you as "Hello Peter!". There you enter your name which is a string value,
When you use scanner you get user inputs and you need variables to store those inputs. you can say "name" is the variable. so what ever name you enter will get stored in name variable. Now how system take your that particular answer? for that there are some methods we use. for a
string we will use var.next() ,
double --> var.nextDouble(),
int ----> nextInt(),
where var is in Scanner var = new Scanner(System.in); the scanner reference variable name.
in your example you are expecting double values as user inputs so that's why you are saying JVM to get the next double value.
Doing some homework here (second assignment, still extremely green...). The object is to read in number x and y and provide the number in the hundreds position.
For this, I need to use int's I'd assume, as a requirement is to utilize value-returning methods.
I'm just starting to code this, however I'm hitting compile errors already:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Illegal modifier for parameter anum; only final is permitted
Illegal modifier for parameter bnum; only final is permitted
Type mismatch: cannot convert from String to int at Hundreds.main(Hundreds.java:6)
Where am I going wrong?
Here is the code so far:
import java.util.Scanner;
public class Hundreds {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
private int anum,bnum;
System.out.println("Hello, for this assignment we are going to require the user to enter two distinct numbers of their choosing");
System.out.println("Please ensure the numbers are between 100 and 9999");
System.out.println("\n");
System.out.println("Please enter your first Number: ");
anum = input.nextLine();
Since those variables are local, you can't set visibility scopes to them like private, public, protected.
Move them out of the main function if you intend their scope to be larger.
anum = Integer.valueOf(input.nextLine());
You can also test to see if the next element is an int, and then give feedback to the user if it's not:
if(input.hasNextInt()) {
anum = input.nextInt();
}
Make anum string instead of int. nextLine return a string. don't use private either while defining your string within main.
Try this instead:
anum = input.nextInt();
This will still error out if you input a non-integer (try it to see the fun stack trace), but will get you past where you're at currently.
(i) Remove invalid modifiers.
(ii)Convert string to integer. So make use of anum=input.nextInt() instead of anum=input.nextLine()