So I am trying to get back into Java after doing C++ for quite some time, I decided to practice by rewriting my C++ programs into Java. Now in my Min Max Program I have the following lines of code:
//C++ Code Sample
getline(cin,mystr);
stringstream(mystr) >> value;
max = value;
min = value;
stringstream stream(mystr);
while(stream >> value)
{
if(value > max)
{
max = value;
}
else if(value < min)
{
min = value;
}
}
Now, getline is equivalent to using the Scanner class, but what of the StringStream? While searching I saw people mentioning InputStream, but that seems to be related to reading from a file, ex: http://www.tutorialspoint.com/java/io/inputstream_read.htm.
Thus, I was wondering if I can get similar functionality? I could of course also ask the user to specify how many inputs they wish to type in, and then just populate an array; but that seems awkward.
Update:
I created a quick work around that works as follows:
String in = "";
while(true)
{
in = input.nextLine();
if(in.equalsIgnoreCase("DONE"))
{
break;
}
value = Integer.parseInt(in);
if(value > max)
{
max = value;
}
else if(value < min)
{
min = value;
}
}
Core Java bootcamp program with Hands on practice Create an input stream and set the string: DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream("pqrs tu v wxy z". getBytes())); The getBytes() method is used to convert a string into sequence of bytes and returns an array of bytes.
To use stringstream, we need to include sstream header file.
Absolutely! Make sure that you pass it by reference, not by value.
StringStream in C++ is similar to cin and cout streams and allows us to work with strings. Like other streams, we can perform read, write, and clear operations on a StringStream object. The standard methods used to perform these operations are defined in the StringStream class.
You can use java.util.Scanner to parse a String
using Scanner(String). You can also use java.lang.StringBuilder to construct strings in an efficient manner.
If you're trying to read a string of numbers from the input and then convert them to integers, you can use the following piece of code which does use Streams.
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array of integers");
String str = sc.nextLine();
String[] strings = str.split(" ");
List<Integer> ints = Stream.of(strings).
map(value -> Integer.valueOf(value)).
collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With