Using scanner to get integers and a string from a file - java

I have a file with contents
v1 0 2 v2 0 3 v3 1 2 v4 1 2 v5 1 3
I need to be able to get the information and store this in three different variables (a String and 2 ints). I am having trouble getting my head around the pattern I would use with the useDelimiter function.
Also is there a way that I don't have to first split it into separate strings, then parseInt from that string? So I have a class called Task which has a String and two Ints. I need to be able to go through the file and create multiple tasks e.g. Task(v1,0,2), Task(v2,0,3).
Thanks.

I think you're over-thinking things -- you don't need to use useDelimiter since Java's Scanner object automatically will split via whitespace.
Scanner scan = new Scanner(new File("myFile"));
ArrayList<Task> output = new ArrayList<Task>();
while (scan.hasNext()) {
String s = scan.next();
int num1 = scan.nextInt();
int num2 = scan.nextInt();
output.add(new Task(s, num1, num2));
}
Note that the above code will fail if the input does not exactly match the pattern of string-int-int -- the nextInt method in a Scanner will fail if the next token cannot be interpreted as an int, and the code will throw an exception if the number of tokens in the input is not a multiple of three.

Default delimiter is ok
while(sc.hasNext()) {
String s = sc.next();
int i1 = sc.nextInt();
int i2 = sc.nextInt();
...
}

Related

I want to read those inputs in a single line separated by space in java without using String?

System.out.println("Number of pages + Number of lost pages + Number of Readers");
int n = s.nextInt();
int m = s.nextInt();
int q = s.nextInt();
I want to read input values all the values are going to be integer but I want to read it in a same line with changing it form Integer.
Assuming s is an instance of Scanner: Your code, as written, does exactly what you want.
scanners are created by default with a delimiter configured to be 'any whitespace'. nextInt() reads the next token (which are the things in between the delimiter, i.e. the whitespace), and returns it to you by parsing it into an integer.
Thus, your code as pasted works fine.
If it doesn't, stop setting up a delimiter, or reset it back to 'any whitespace' with e.g. scanner.reset(); or scanner.useDelimiter("\\s+");.
class Example {
public static void main(String[] args) {
var in = new Scanner(System.in);
System.out.println("Enter something:");
System.out.println(in.nextInt());
System.out.println(in.nextInt());
System.out.println(in.nextInt());
}
}
works fine here.

Why do I get wrong mathematical results when using scanner class and delimiters for getting a double in Java?

I am writing a program where I have to get a user input, saved as a double. The user must be able to put it using both ',' and '.' as a delimiter - however they want. I tried using useDelimiter which works only partially - it does indeed accept both values (e.g 4.5 and 4,5) but when I later use the entered value in a mathematical equation, I get wrong results - it seems to round the user input down to the closest integer and as an effect no matter whether I enter, 4 or 4.5 or 4,5 or 4.8 etc., I get the same result, which is actually only true to 4.
Does anyone happen to know why it doesn't work?
double protectiveResistor=0; //must be a double, required by my teacher
double voltage= 5;
System.out.println("Please provide the resistance.");
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
protectiveResistor=sc.nextDouble();
}
catch(InputMismatchException exception)
{
System.out.println("Wrong input!");
System.exit(1);
}
if (protectiveResistor<0){
System.err.println("Wrong input!");
System.exit(1);
}
double current = (double)voltage/protectiveResistor;
double power = (double)current*current*protectiveResistor;
Thank you!
The useDelimiter method is for telling the Scanner what character will separate the numbers from each other. It's not for specifying what character will be the decimal point. So with your code, if the user enters either 4.5 or 4,5, the Scanner will see that as two separate inputs, 4 and 5.
Unfortunately, the Scanner doesn't have the facility to let you specify two different characters as decimal separators. The only thing you can really do is scan the two numbers separately, then join them together into a decimal number afterwards. You will want to scan them as String values, so that you don't lose any zeroes after the decimal point.
What useDelimiter() does is split the input on the specified delimiter.
As an example, if you have the input of 4,5, the following code will print "4".
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
If you also want to print the second part, after the ',', you need to add another line to get the next value, which would in this example print
"4
5":
Scanner sc= new Scanner(System.in);
sc.useDelimiter(",");
System.out.println(sc.next())
System.out.println(sc.next())
In your code you can do it like this:
Scanner sc= new Scanner(System.in);
sc.useDelimiter("(\\p{javaWhitespace}|\\.|,)");
try
{
String firstPart = "0";
String secondPart = "0";
if (sc.hasNext()) {
firstPart = sc.next();
}
if (sc.hasNext()) {
secondPart = sc.next();
}
protectiveResistor = Double.parseDouble(firstPart + "." + secondPart)
}
// Rest of your code here
What this code does is split the input on whitespace, '.' and ','. For a floating point value you expect one part before the decimal point and one after it. Therefore, you expect the scanner to have split the input in two parts. These two parts are assigned to two variables, firstPart and secondPart. In the last step, the two parts are brought together with the '.' as decimal point, as expected by Java and parsed back into a variable of type Double.

How to check if the next 3 input is an int by using Scanner.hasNextInt() and loop only in java

How can I check if the next three input user is giving is an int value,
like let's say there is three variables,
var1
var2
var3
And I am taking input as,
Scanner sc = new Scanner (System.in);
var1 = sc.nextInt();
var2 = sc.nextInt();
var3 = sc.nextInt();
Now if I want to use while(sc.hasNextInt()) to determine if the next input is an int or not then it will only check if the next input for var1 is int or not and won't check for the other to variables, var2, var3. One thing can be done by using while loop with if (condition). For example,
Scanner sc = new Scanner (System.in);
while (sc.hasNextInt()) {
var1 = sc.nextInt();
if (sc.hasNextInt()) {
var2 = sc.nextInt();
if (sc.hasNextInt()) {
var3 = sc.nextInt();
}
}
}
But this looks lengthy and needs a lot to write. For similar issue I have seen for Language C there is a method for scanf() which can do the trick. For example,
while(scanf("%d %d %d", &var1, &var2 & var3) == 3) {
// Statements here
}
So my question is there any such features available in java's Scanner.hasNextInt or Scanner.hasNext("regex").
I have also tried sc.hasNext("[0-9]* [0-9]* [0-9]*") but didn't worked actually.
Thank you in advance.
hasNext(regex) tests only single token. Problem is that default delimiter is one-or-more-whitespaces so number number number can't be single token (delimiter - space - can't be part of it). So sc.hasNext("[0-9]* [0-9]* [0-9]*") each time will end up testing only single number. BTW in your pattern * should probably be + since each number should have at least one digit.
To let spaces be part of token we need to remove them from delimiter pattern. In other words we need to replace delimiter pattern with one which represents only line separators like \R (more info). This way if user will write data in one line (will use enter only after third number) that line would be seen as single token and can be tested by regex.
Later you will need to set delimiter back to one-or-more-whitespaces (\s+) because nextInt also works based on single token, so without it we would end up with trying to parse string like "1 2 3".
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\R");
System.out.print("Write 3 numbers (sepate them with space): ");
while(!sc.hasNext("\\d+ \\d+ \\d+")){
String line = sc.nextLine();//IMPORTANT! Consume incorrect values
System.out.println("This are not 3 numbers: "+line);
System.out.print("Try again: ");
}
//here we are sure that there are 3 numbers
sc.useDelimiter("\\s+");//nextInt can't properly parse "num num num", we need to set whitespaces as delimiter
int var1 = sc.nextInt();
int var2 = sc.nextInt();
int var3 = sc.nextInt();
System.out.println("var1=" + var1);
System.out.println("var2=" + var2);
System.out.println("var3=" + var3);
Possible problem with this solution is fact that \d+ will let user provide number of any length, which may be out of int range. If you want to accept only int take a look at Regex for a valid 32-bit signed integer. You can also use nextLong instead, since long has larger range, but still it has max value. To accept any integer, regardless of its length you can use nextBigInteger().
I tried with nextLine method and usage of Pattern. Regex is matching with 3 numbers which is separeted with space. So it can be like this i think ;
Scanner scanner = new Scanner(System.in);
Pattern p = Pattern.compile("[0-9]+\\s[0-9]+\\s[0-9]+$");
while(!p.matcher(scanner.nextLine()).find()){
System.out.println("Please write a 3 numbers which is separete with space");
}
System.out.println("Yes i got 3 numbers!");
I hope this helps you.

Is there a function in Java that allows you to transform a string to an Int considering the string has chars you want to ignore?

I'm doing a project for a Uni course where I need to read an input of an int followed by a '+' in the form of (for example) "2+".
However when using nextInt() it throws an InputMismatchException
What are the workarounds for this as I only want to store the int, but the "user", inputs an int followed by the char '+'?
I've already tried a lot of stuff including parseInt and valueOf but none seemed to work.
Should I just do it manually and analyze char by char?
Thanks in advance for your help.
Edit: just to clear it up. All the user will input is and Int followed by a + after. The theme of the project is to do something in the theme of a Netflix program. This parameter will be used as the age rating for a movie. However, I don't want to store the entire string in the movie as it would make things harder to check if a user is eligible or not to watch a certain movie.
UPDATE: Managed to make the substring into parseInt to work
String x = in.nextLine();
x = x.substring(0, x.length()-1);
int i = Integer.parseInt(x);
Thanks for your help :)
Try out Scanner#useDelimiter():
try(Scanner sc=new Scanner(System.in)){
sc.useDelimiter("\\D"); /* use non-digit as separator */
while(sc.hasNextInt()){
System.out.println(sc.nextInt());
}
}
Input: 2+33-599
Output:
2
33
599
OR with your current code x = x.substring(0, x.length()-1); to make it more precise try instead: x = x.replaceAll("\\D","");
Yes you should manually do it. The methods that are there will throw a parse exception. Also do you want to remove all non digit characters or just plus signs? For example if someone inputs "2 plus 5 equals 7" do you want to get 257 or throw an error? You should define strict rules.
You can do something like: Integer.parseInt(stringValue.replaceAll("[^\d]","")); to remove all characters that are no digits.
Hard way is the only way!
from my Git repo line 290.
Also useful Javadoc RegEx
It takes in an input String and extracts all numbers from it then you tokenize the string with .replaceAll() and read the tokens.
int inputLimit = 1;
Scanner scan = new Scanner(System.in);
try{
userInput = scan.nextLine();
tokens = userInput.replaceAll("[^0-9]", "");
//get integers from String input
if(!tokens.equals("")){
for(int i = 0; i < tokens.length() && i < inputLimit; ++i){
String token = "" + tokens.charAt(i);
int index = Integer.parseInt(token);
if(0 == index){
return;
}
cardIndexes.add(index);
}
}else{
System.out.println("Please enter integers 0 to 9.");
System.out.print(">");
}
Possible solutions already have been given, Here is one more.
Scanner sc = new Scanner(System.in);
String numberWithPlusSign = sc.next();
String onlyNumber = numberWithPlusSign.substring(0, numberWithPlusSign.indexOf('+'));
int number = Integer.parseInt(onlyNumber);

How do i declare and read values into integer values?

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();

Categories