txt file with integers, strings and bulleted list (1.) - java

I have a txt file which has several rows like this
7. SSWAB 38 15 - 57
but I don't need all the values, just the String and the integers.
I would use nextInt for the Integers, but how can I deal with 1. and -?
Also there is the string, what is a useful nextString? Is next enough?
I have tried something like this, just using tokens, but nothing happens
scanner.next(); //7.
String s = (scanner.next()); //SAVES sswab
Integer n1 = scanner.nextInt(); //38
Integer n2 = scanner.nextInt(); //15
Integer n3 = scanner.nextInt(); //- is skipped, as next int is 57

You can use scanner.next(Pattern pattern) for matching these groups.
Try this regex
-?\d+\.?(\d+)?|\w+
Demo
It would catch all groups you mentioned plus fractional numbers and negative numbers.
Then you can use this regex in scanner
String text = "7. SSWAB 38 15 - 57 ";
Scanner scanner = new Scanner(text);
while(scanner.hasNext()) {
if(scanner.hasNext("-?\\d+\\.?(\\d+)?|\\w+")) {
System.out.println(scanner.next("-?\\d+\\.?(\\d+)?|\\w+"));
} else {
scanner.next();
}
}
This code catch all matching groups and skip others. Output
7.
SSWAB
38
15
57

Related

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

read input by user seperated by line breaks, spaces etc

im struggling with the input part of the below question.
Question: The input stream contains a set of integer numbers Ai (0 ≤ Ai ≤ 1018). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.
how do i read the input from the user which are separated by line breaks, spaces etc. how do i make sure the input stream doesnot exceed 256 KB?
and how do i make sure that a particular input will be the last value entered by the user so that the program and proceed for execution?
the input can be given in anyway, any number not exceeding 10^8,EX: first input can be given as say 1 and in the same line the second input can be given as 34 separated by 3 spaces from the first input. then 2nd line and the 3rd line are empty and again in the fourth line, there can a number say 225345 which is the 3rd input. so once all the inputs are given by the user, i have to take them, arrange them into one list or array and perform some operations on them.
example:
1427 0
876652098643267843
5276538
kindly help. thanks
This should do the trick if there is at least one space between each number
Scanner scanner = new Scanner(new File("data.txt")); // or new Scanner(System.in) for reading from command line.
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNext()) {
int number = scanner.nextInt();
if (number<0||number>1018)
break;
list.add(number);
}
scanner.close();
System.out.println(list);
Example: (data.txt)
145 358
94 2
13 1205 158 489
Output:
[145, 358, 94, 2, 13, 1205, 158, 489]
Use a java.util.Scanner to read the sequence of longs (because 10^18 > Integer.MAX_VALUE):
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong()) {
long number = scanner.nextLong();
if (number < 1 || number > 1_000_000_000_000_000_000L)
throw new RuntimeException("input out of range: " + number);
}
To validate the input stream size you can reuse the CountingInputStream from Guava or Commons IO, or code your own. Note that, due to internal buffering in Scanner, you may end up reading more than 256 KB of input.
CountingInputStream input = new CountingInputStream(System.in);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong() && input.getCount() < 256 * 1024) { ... }
Ensuring that a particular input will be the last value requires you to pick a delimiter. I'd use a number out of the acceptable input, say, -1:
CountingInputStream input = new CountingInputStream(System.in);
Scanner scanner = new Scanner(input);
while (scanner.hasNextLong() && input.getCount() < 256 * 1024) {
long number = scanner.nextLong();
if (number == -1)
break;
if (number < 1 || number > 1_000_000_000_000_000_000L)
throw new RuntimeException("input out of range: " + number);
}
Hope this helps.

Error in Java while trying to read input

This program should count amount of digits in a number.
Here is my code:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
Scanner marty = new Scanner(System.in);
float sk;
System.out.println("Enter start number: ");
sk = marty.nextFloat();
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);
marty.close();
}
}
I am getting this kind of error, while tryin to input number with 4 or more digits before comma, like 11111,456:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at Converter.main(Converter.java:11)
Any ideas about what the problem may be?
Taking the log (base10) of a number and adding 1 is not going to give you the correct answer for the number of digits of the input number anyway.
Your given example of 11111.465 has 8 digits. The log10 of this number is 4.045... adding 1 gives you the answer of 5.
Another example: 99, Log10(99) = 1.99, cast as int = 2, add 1 = 3... clearly is only 2 digits.
You could just read the input as a String then do something like the following instead
int count = 0;
String s = /* (Input Number) */
for(char c : s.toCharArray())
{
if(Character.isDigit(c))
count++;
}
You would have to also have to check it is actually a number though by checking its pattern...
When inputting a number, you aren't supposed to include commas unless you expect to split it. If you want a decimal, use a "." instead. If you want a number greater than 999, don't include a comma
Like many people have said, the comma is messing you up.
One option you may consider if your input needs comma is replacing the commas from the input string before try to count the number of digits.
System.out.println("Enter start number: ");
String input = marty.nextLine();
float sk = Float.parseFloat(input.replace(",", ".")); // use input.replace(",", "") if you want to remove commas
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);

Taking input an arbitrary number of times

I am looking to solve a coding problem, which requires me to take the input an arbitary number of times with one integer at one line. I am using an ArrayList to store those values.
The input will contain several test cases (not more than 10). Each
testcase is a single line with a number n, 0 <= n <= 1 000 000 000.
It is the number written on your coin.
For example
Input:
12
2
3
6
16
17
My attempt to take input in Java:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNext()){
list.add(inp.nextInt());
}
However, when I try to print the elements of the list to check if I have taken the inputs correctly, I don't get any output. the corresponding correct code in C goes like this:
unsigned long n;
while(scanf("%lu",&n)>0)
{
printf("%lu\n",functionName(n));
}
Please help me fix this thing with Java.
(PS: I am not able to submit solutions in Java because of this )
You can do this one thing! At the end of the input you can specify some character or string terminator.
code:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNextInt())
{
list.add(inp.nextInt());
}
System.out.println("list contains");
for(Integer i : list)
{
System.out.println(i);
}
sample input:
10
20
30
40
53
exit
output:
list contains
10
20
30
40
53
Can you do something like this:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNextInt()){
list.add(inp.nextInt());
}
If there is some another value like character, loop finishes.

Categories