Java Scanner get number from string [closed] - java

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
The string is, for example "r1" and I need the 1 in an int form
Scanner sc = new Scanner("r1");
int result = sc.nextInt(); // should be 1
compiles correctly but has a runtime error, should I be using the delimiter? Im unsure what the delimiter does.

Well, there's a few options. Since you literally want to skip the "r" then read the number, you could use Scanner#skip. For example, to skip all non-digits then read the number:
Scanner sc = new Scanner("r1");
sc.skip("[^0-9]*");
int n = sc.nextInt();
That will also work if there are no leading non-digits.
Another option is to use non-digits as delimiters, as you mentioned. For example:
Scanner sc = new Scanner("x1 r2kk3 4 x56y 7g");
sc.useDelimiter("[^0-9]+"); // note we use + not *
while (sc.hasNextInt())
System.out.println(sc.nextInt());
Outputs the six numbers: 1, 2, 3, 4, 56, 7.
And yet another option, depending on the nature of your input, is to pre-process the string by replacing all non-digits with whitespace ahead of time, then using a scanner in its default configuration, e.g.:
String input = "r1";
input = input.replaceAll("[^0-9]+", " ");
And, of course, you could always just pre-process the string to remove the first character if you know it's in that form, then use the scanner (or just Integer#parseInt):
String input = "r1";
input = input.substring(1);
What you do depends on what's most appropriate for your input. Replace "non-digit" with whatever it is exactly that you want to skip.
By the way I believe a light scolding is in order for this:
Im unsure what the delimiter does.
The documentation for Scanner explains this quite clearly in the intro text, and even shows an example.
Additionally, the definition of the word "delimiter" itself is readily available.

There are some fundamental mistakes here.
First, you say:
One = sc.nextInt("r1");
compiles correctly ...
No it doesn't. If sc is really a java.util.Scanner, then there is no Scanner.nextInt(String) method, so that cannot compile.
The second problem is that the hasNextXXX and nextXXX methods do not parse their arguments. They parse the characters in the scanner's input source.
The third problem is that Scanner doesn't provide a single method that does what you are (apparently) trying to do.
If you have a String s that contains the value "r1", then you don't need a Scanner at all. What you need to do us something like this:
String s = ...
int i = Integer.parseInt(s.substring(1));
or maybe something this:
Matcher m = Pattern.compile("r(\\d+)").matcher(s);
if (m.matches()) {
int i = Integer.parseInt(m.group(1));
}
... which checks that the field is in the expected format before extracting the number.
On the other hand if you are really trying to read the string from a scanner them, you could do something like this:
String s = sc.next();
and then extract the number as above.

If the formatting is the same for all your input where the last char is the value you could use this:
String s = sc.nextLine()
Int i = Integer.parseInt(s.charAt(s.length() -1));
Else you could for instance make the string a char Array, iterate trough it and check whether each char is a number.

Related

Is there a way to accept a single character as an input?

New to programming, so my apologies if this is dumb question.
When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = input.nextLine();
}
}
The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.
But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.
You can use System.in.read() instead of Scanner
char input = (char) System.in.read();
You can also use Scanner, doing something like:
Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);
For using Stringinstead of char, you can also to convert to String:
Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));
This is less fancy than other ways, but for a newbie, it'll be easier to understand. On the other hand, I think the problem proposed doesn't need amazing performance.
Set the delimiter so every character is a token:
Scanner input = new Scanner(System.in).useDelimiter("(?<=.)");
String c = input.next(); // one char
The regex (?<=.) is a look behind, which has zero width, that matches after every character.

Java How to Read Data From a String (stringstream equivalent) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Let's say I have a String (call it s) with the following format:
[String] [String] [double] [int]
for example,
"YES james 3.5 2"
I would like to read this data into separate variables (a String, a String, a double, and an int)
Note that I come from a C++ background. In C++, I would do something like the following:
std::istringstream iss{s}; // create a stream to the string
std::string first, second;
double third = 0.0;
int fourth = 0;
iss >> first >> second >> third >> fourth; // read data
In Java, I came up with the following code:
String[] sa = s.split(" ");
String first = sa[0], second = sa[1];
double third = Double.parseDouble(sa[2]);
int fourth = Integer.parseInt(sa[3]);
However, I will have to do this to many different inputs, so I would like to use the most efficient and fastest way of doing this.
Questions:
Is there any more efficient/faster way of doing this? Perhaps a cleaner way?
Try it like this. Scanner's constructor can take a string as a data source.
Scanner scan = new Scanner("12 34 55 88");
while (scan.hasNext()) {
System.out.println(scan.nextInt());
}
prints
12
34
55
88
As it has been mentioned in the comments, if this is coming from keyboard (or really from an input stream) you could use Scanner class to do so. However, from input sources other than keyboard, I will not use Scanner but some other method to parse strings. For example, if reading lines from a file, you may want to use a Reader instead. For this answer, I will assume the input source is the keyboard.
Using Scanner to get the input
Scanner scanner = new Scanner(System.in);
System.out.print("Provide your input: ");
String input = scanner.nextLine();
input.close();
Break the String into tokens
Here you have a few options. One is to break down the string into substring by splitting the input using white space as a delimeter:
String[] words = input.split("\\s");
If the order of these substrings is guaranteed, you can assign them directly to the variables (not the most elegant solution - but readable)
String first = words[0];
String second = words[1];
double third = words[2];
int fourth = words[3];
Alternatively, you can extract the substrings directly by using String#substring(int) and/or String#substring(int, int) methods and test whether or not the obtained substring is a number (double or int), or just simply a string.

How to convert scanner to String or List

I have a scanner with many lines of text(representing number) and I want to convert all the text in the scanner to a List.
Example:
Scanner myScanner = new Scanner(new File("input.txt"));
input.txt:
000110100110
010101110111
111100101011
101101001101
011011111110
011100011001
110010011100
000001011100
101110100110
010001011100
011111001010
100111100101
111111000010
My first thought was to convert it to a String by changing the delimiter to something I know is not in the file:
myScanner.useDelimiter("impossible String");
String content = myScanner.next();
and then use
List<String> fullInput = Arrays.asList(content.split("\n"));
However, it gives me problems later on with parsing the numbers on the scanner. I've tried debugging it but I can't seem to understand the problem. For example, I made it print the String to the console before parsing it. It would print a proper number(asString) and then give me NumberFormatException when it is supposed to parse.
Here's the runnable code:
public static void main(String[] args) throws FileNotFoundException {
Scanner myScanner = new Scanner(new File("input.txt"));
myScanner.useDelimiter("impossible String");
String content = myScanner.next();
List<String> fullInput = Arrays.asList(content.split("\n"));
System.out.println(fullInput.get(1));
System.out.println(Long.parseLong(fullInput.get(1)));
}
This is what I ended up using after the first didn't work:
Scanner myScanner = new Scanner(new File("input.txt"));
List<String> fullInput = new ArrayList<>();
while (sc.hasNextLine())
fullInput.add(myScanner.nextLine());
Do you know what's wrong with the first method or is there a better way to do this?
Because you are parsing a string that represents a number that's beyond the size of an integer.
int values can be between -2,147,483,648 to 2,147,483,647.
fullInput.get(1) gives you 010101110111 which is greater than 2,147,483,647.
You can use long.
long val = Long.parseLong(fullInput.get(1));
If the string represents binary numbers and you want to convert them to int, then you need to provide the base when parsing the string.
int val = Integer.parseInt(fullInput.get(1), 2);
For what you are trying to do here, Scanner is the wrong solution.
If your goal is to simply read the all lines of the file as String[] you can use the Files.readAllLines(Path, Charset) method (javadoc) to do this. You could then wrap that as a List using Arrays.asList(...).
What you are actually doing could work under some circumstances. But one possible problem is that String.split("\n") only works on systems where the line terminator is a single NL character. On Windows, the line terminator is a CR NL sequence. And in that case, String.split("\n") will leave a CR at the end of all but the last string / line. That would be sufficient to cause Long.parseLong(...) to throw a NumberFormatException. (The parseXxx methods do not tolerate extraneous characters such as whitespace in the argument.)
A possible solution to the extraneous whitespace problem is to trim the string; e.g.
System.out.println(Long.parseLong(fullInput.get(1).trim()));
The trim() method (javadoc) returns a string with any leading and/or trailing whitespace removed.
But there is another way to deal with this. If you don't care whether each number in the input file is on a separate line, you could do something like this:
Scanner myScanner = new Scanner(new File("input.txt"));
List<Long> numbers = new ArrayList<>();
while (myScanner.hasNextLong()) {
numbers.append(myScanner.nextLong());
}
Finally, #ChengThao makes a valid point. It looks like these are binary numbers. If they are in fact binary, then it makes more sense to parse them using Long.parseLong(string, radix) with a radix value of 2. However if you parse them as decimal using parseLong (as you are currently doing) the values in your question will fit into a long type.

Accepting a known number of integers on a single line in java

I know there is a similar question already asked, so let me apologize in advance. I am new to Java and before this, my only programming experience is QBasic.
So here is my dilemma: I need to accept 2 integer values and I would like to be able to enter both values on the same line, separated by a space (IE: Enter "45 60" and have x=45 and y=60).
From what I have seen, people are suggesting arrays, but I am weeks away from learning those... is there a simpler way to do it? We have gone over "for", "if/else", and "while" loops if that helps. I don't have any example code because I don't know where to start with this one.
I have the program working with 2 separate calls to the scanner... just trying to shorten/ clean up the code. Any ideas??
Thanks!
//UPDATE:
Here is the sample so far. As I post this, I am also reading the scanner doc.
And I don't expect you guys to do my homework for me. I'd never learn that way.
The println at the end it my way of checking that the values were stored properly.
public static void homework(){
Scanner hwScan = new Scanner(System.in);
System.out.println("Homework and Exam 1 weights? ");
int hwWeight = hwScan.nextInt();
int ex1Weight=hwScan.nextInt();
System.out.println(hwWeight+" "+ex1Weight);
}
Even simple scanner.nextInt() would work for you like below:
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println("x = " + x + " y = " + y);
Output:
1 2
x = 1 y = 2
If you only have to accept two integer numbers you could do something like this:
String input = System.console().readLine(); //"10 20"
//String input = "10 20";
String[] intsAsString = input.split(" ");
int a = Integer.parseInt(intsAsString[0];
int b = Integer.parseInt(intsAsString[1]);
intsAsString is an array, in simple terms, that means it stores n-strings in one variable. (Thats very simplistic, but since you look at arrays more closely later you will see what i mean).
Be sure to roughly understand each line, not necessarily what exactly the lines do but conceptually: Read data form Console, parse the line so you have the two Strings which represent the two ints, then parse each string to an int. Otherwise you will have a hard time in later on.

How do I ignore characters entered by the user via Scanner?

Im working right now on a program that can divide, add, ect, but, im also making it for others, so, the problems usually have letters as well. What code could I implement so that my program ignores characters, and just focuses on numbers?
import static java.lang.System.out;
import java.util.Scanner;
public class Trinomial {
public static void main(final String args[]) {
final Scanner first = new Scanner(System.in);
out.print("Enter the first number: ");
final int First = first.nextInt();
final Scanner second = new Scanner(System.in);
out.print("Enter the second number: ");
final int Second = second.nextInt();
final Scanner third = new Scanner(System.in);
out.print("Enter the third number: ");
final int Third = third.nextInt();
numFactors(First);
}
}
You can have your program check whether each character it looks at is a digit using Character.isDigit()
http://www.tutorialspoint.com/java/character_isdigit.htm
You probably also want to allow your math operators through, e.g.
if (Character.isDigit(input) || input == '+' ||
input == '-' || input == '/' || input == '*')
{
// Do something with input
}
If that's not what you're looking for, please improve your question to be more specific.
Firstly, you will have to use next() method from the scanner, as nextInt() will return an exception if the next token contains non-digit characters. This will read the token as a String. Then you can get rid of non-digit characters by, for example, creating an empty String (for performance reasons StringBuilder can be better, but that makes it more complex), looping through the original string and using the already mentioned isDigit() method to determine whether the character is a digit. If it is, add it to your new string. Once you have a string containing only digits, use Integer.parseInt(string) method to get the integer value.
I am not quite sure, why you initialise a new Scanner every time, I think you should be able to use the first one throughout your program.

Categories

Resources