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

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.

Related

separate Lines and picking up Each One in new String Variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
String is Like This:
String Text="Bank name Some Thing \n Reminder is Some Thing \n Date Some";
I want it to be Like this:
String T1="Bank Name Some Thing";
String T2="Reminder is Some Thing";
String T3="Date Some";
I'm Working with java
I will be thankful to Your Help.
You can use split() function to split the sentences based on delimiter \n and store them in an array. Then by iterating the array, you can access each string:
public static void main(String[] args) {
String Text="Bank name Some Thing \n Reminder is Some Thing \n Date Some";
String[] sentences = Text.split("\n");
for (String s : sentences){
System.out.println(s.trim());
}
}
Related method's doc page is here.
Since there are additional spaces around delimiter, you can use trim method to remove them.
If you want to assign the values to different variables as mentioned in your question, you can do it as follows:
String T1 = sentences[0].trim();
String T2 = sentences[1].trim();
String T3 = sentences[3].trim();
You should also follow Java naming conventions e.g. the name of the variables should be t1, t2, and t3 instead of T1, T2, and T3.
Another option is to use the Scanner
String text =
"Bank name Some Thing \n Reminder is Some Thing \n Date Some";
Scanner scan = new Scanner(text);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine().trim());
}
Prints
Bank name Some Thing
Reminder is Some Thing
Date Some
If you know how many lines you have you can just assign them directly as follows:
String T1=scan.nextLine().trim();
String T2=scan.nextLine().trim();
String T3=scan.nextLine().trim();

Addition Using Stacks? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I want to add a pair of numbers that are separated by a space. So a user inputs multiple numbers of any length separated by a space. I'm using BigInteger for this. Using two stacks, each pair of numbers must be added together and the results need to be printed out. For example, the output would be like this:
10
+ 10
= 20
99
+ 1
= 100
1000000000000000000000000000000
+ 1000000000000000000000000000000
= 2000000000000000000000000000000
I need to use stacks to do this. This is what I have so far but I'm not sure where to go after this.
public static void main (String[] args)
{
Stack<BigInteger> stack = new Stack<BigInteger>();
System.out.println("Please write some pairs of numbers to add separated by a space: ");
Scanner input = new Scanner(System.in);
for (BigInteger number : input.nextLine().split(" "))
{
for (int i = 0; i < number.length(); i++)
{
stack.push(number);
}
while (!stack.isEmpty()) {
reverseInput += stack.pop();
}
}
}
You don't need inner for loop. If you are trying to add two numbers using stack, you can push them into Stack, pop and add to the result, e.g.:
Stack<BigInteger> stack = new Stack<BigInteger>();
System.out.println("Please write some pairs of numbers to add by a space: ");
Scanner input = new Scanner(System.in);
for (BigInteger number : input.nextLine().split(" "))
{
BigInteger result = new BigInteger("0");
while (!stack.isEmpty()) {
result.add(stack.pop());
}
System.put.println("Result : " + result);
First of all,
for (BigInteger number : input.nextLine().split(" "))
Isn't going to work, because that .split() returns an object of type String[], and you can't directly treat String asBigInteger.
Also, you're doubling up on your for loops. That line I copied above, if it worked the way you wanted, would loop through all of the numbers in your input. So there's no need for that inner for loop. In fact, it won't even compile, since BigInteger doesn't have a .length() method.
But you're on the right track. What you can do is tokenize the input like you're already doing, and push each element into a the stack as-is. Because there's no need to push them into the stack as BigInteger. You can have a Stack<String>, and then convert them into BigInteger when you pop them back off to do the addition. Or alternatively, convert them to BigInteger as you push each one onto the stack.
input.nextLine().split(" ");
returns a String[], you cannot automatically cast it to BigInteger[], as that will throw a ClassCastException.
Do you allow decimal values? If so, you'd be better off converting each String element to a primitive double representation, as you won't need the additional precision offered by BigDecimal.
As decimal values won't be allowed, you'd want to convert the String to its integer representation.
for (final String s : input.nextLine().split(" ")) {
final int value = Integer.parseInt(s);
stack.push(value);
}
The stack generic type will be Integer. So Stack<Integer>
Have you considered the case of bad user input? In that case you need to handle a NumberFormatException

Java Scanner get number from string [closed]

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.

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.

Issues with input from user [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an input from user of the following form:
1234 abc def gfh
..
8789327 kjwd jwdn
stop
now if i use Scanner and in turn use
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
int i=sc.nextInt();
int str=sc.nextLine();
t=sc.nextLine();
}
Is there some way by which i may get
i=1234
str="abc def gfh"
...
and so on...and stop when the user enters a stop
I want to accept the numerical values and strings separately...without using regex.
Also I want to stop taking input with keyword "stop".
First of all, you are doing nothing with the accepted input, just ignoring it to take next input.
Second, scanner.nextLine() returns you the next line read which is String. To get the tokens separately, you would need to split the string read to get them.
Third, you should check in your while, whether you have next input or not using scanner#hasNextLine, if its equal to true, then only you should read your input in your while loop.
If you want to read each token separately, you should better use Scanner#next method, which returns the next token read.
Also, you want to read integers and strings, so you also need to test, whether you are having an integer. You would need to use Scanner#hasNextInt method for that.
Ok, since you want to read integer and string separately on each line.
Here's what you can try: -
while (scanner.hasNextLine()) { // Check whether you have nextLine to read
String str = scanner.nextLine(); // Read the nextLine
if (str.equals("stop")) { // If line is "stop" break
break;
}
String[] tokens = str.split(" ", 1); // Split your string with limit 1
// This will give you 2 length array
int firstValue = Integer.parseInt(tokens[0]); // Get 1st integer value
String secondString = tokens[1]; // Get next string after integer value
}
You never change the value of t so the while condition will be always true unless the first line of your file is stop.
your code:
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
while(!t.equals("stop"))
{
int i=sc.nextInt();
int str=sc.nextLine();
t=sc.nextLine();
}
First of all int str=sc.nextLine(); is wrong as nextLine() returns string. According to me, what you can do is:
Scanner sc=new Scanner(System.in);
String t=sc.nextLine();
int i;
String str="";
while(!t.equals("stop"))
{
int index=t.indexOf(" ");
if(index==-1)
System.out.println("error");
else{
i=Integer.parseInt(t.substring(0,index));
str=t.substring(index+1);
}
t=sc.nextLine();
}
I hope it helps.

Categories

Resources