how to give a string from user having space between it? - java

I want to give a sentence from standard input and my sentence might have a space between it. I want to split the string. How to take input from standard input device?
I can do it with hard coded string.
String speech = "Four score and seven years ago";
String[] result = speech.split(" ");

You can take input from user with nextLine() method of Scanner class
import java.util.Scanner;
public class SplitString
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in/*Taking input from standard input*/);
System.out.print("Enter any string=");
String userInput = scan.nextLine();//Taking input from user
String splittedString[] = userInput.split(" ");//Splitting string with space
}
}

Store the input in a StringBuilder, line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String line;
line = reader.readLine();
Then you can split your result.
String[] result = line.split("\\s");

Related

Loop through String array to fill it with input from user

just a another noob to Java with a dumb question.
I am trying to create a function that receives a String array and fills it with text input from the user using Bufferedreader (which I currently want to use).
I sort of have the idea in my head but it gives the error cannot find symbol when using the readline() property. How can I achieve this?
public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void fill_array (String parray []){
for(int i = 0; i < parray.length; i++){
parray[i] = in.readline(); //Here it gives me the error
}
}
readLine() and not readline how embarrasing
Hii Scanner is much more simpler than BufferedReader to read input, Let me give you an example :
import java.util.*;
public class Main
{
public static void main(String arp[])
{
Scanner scanner = new Scanner(System.in);
String address = scanner.nextLine(); // read string with spaces
System.out.println("addres : "+ address);
String name = scanner.next(); // read string without spaces
System.out.println("name : "+ name);
Integer age = scanner.nextInt(); // read Integer input
System.out.println("age : "+ age);
}
}
Scanner java api link : https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

How to convert a body of text to a single line string in Java?

I would like to convert a body of text which is in a form similar to this:
text here
text there
text everywhere
into a single string which would look like the following:
textheretexttheretexteverywhere
EDIT: The text on multiple lines is to be copied from one file and pasted into the input of the program, however it isn't necessarily a .txt file.
Here's what I have so far:
public static void converter(String inputString){
String refinedString = inputString.replaceAll("\\s+","").replaceAll("\\\\n+", "");
System.out.println();
System.out.println("Refined string: " + refinedString);
}
Here is my main function where I am calling my converter method:
public static void main(String [] args){
System.out.println("Enter string: ");
Scanner input = new Scanner(System.in);
String originalString = input.nextLine();
System.out.println("Original string: " + originalString);
converter(originalString);
}
Many thanks in advance!
(I'm new to programming so sorry if I'm missing something really obvious, I've tried everything I could find on Stack overflow)
Try this:
String line = "";
File f = new File("Path to your file");
FileReader reader = new FileReader(f)
BufferedReader br = new BufferedReader(reader);
String str = "";
while((line = br.readlLine())!=null)
{
str += line;
}
System.out.println(str);
for spaces:
str = StringUtils.replace(str," ","");
You pretty much got it! The only thing you are "missing" is that you added the extra .replaceAll when you didn't need to.
Also, it sounds like you may have different types of input, but here is a solution based on your code:
EDIT: Here is the solution below:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String [] args){
System.out.println("Enter string: ");
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<> ();
String line = null;
while (!(line = input.nextLine()).isEmpty()) {
lines.add(line);
}
StringBuilder myOriginalString = new StringBuilder();
for (String s : lines) {
myOriginalString.append(s);
myOriginalString.append(" ");
myOriginalString.append("\n");
}
String originalString = myOriginalString.toString();
System.out.println("Original string: \n" + originalString);
converter(originalString);
}
public static void converter(String inputString){
String refinedString = inputString.replaceAll("\\s+","");
System.out.println();
System.out.println("Refined string: " + refinedString);
}
}
Output:
Enter string:
text here
text there
text everywhere
Original string:
text here
text there
text everywhere
Refined string: textheretexttheretexteverywhere
Process finished with exit code 0
I did my best to model it around the type of input you would be giving. Based on your question, I assume you would be copying and pasting text to the prompt when you run your program. If you are looking to read from a file, then Mahbubur Rahman's answer is correct (and I won't replicate it in this answer as he deserves the credit.)
This should work.
String list = "text here\n";
list += "text there\n";
list += "text everywhere\n";
System.out.println("Original :\n"+list);
list= list.replace("\n", "").replace(" ", "");
System.out.println("New :\n"+list);

Using scan.nextLine() for Cyrillic

I don't know how to read Cyrillic or any other language except English from the console. I tried to do this:
Scanner scan = new Scanner(System.in, "UTF_16");
String input = scan.nextLine();
But it keeps waiting for me to enter even though I already entered the text.
You need to replace the UTF_16 by UTF-8...
public static void main(String args[]) {
Scanner scan = new Scanner(System.in, "UTF-8");
String input = scan.nextLine();
String myString = "some cyrillic text";
byte[] russianBytes = input.getBytes("ISO-8859-1");
String valueConverted = new String(russianBytes, "UTF-8");
System.out.println(valueConverted);
}
this print takes Илия Камбуров and print it properly

Java Scanner delimiter doesn't split the last section

/* txt file
Rolling Stone#Jann Wenner#Bi-Weekly#Boston#9000
Rolling Stone#Jann Wenner#Bi-Weekly#Philadelphia#8000
Rolling Stone#Jann Wenner#Bi-Weekly#London#10000
The Economist#John Micklethwait#Weekly#New York#42000
The Economist#John Micklethwait#Weekly#Washington#29000
Nature#Philip Campbell#Weekly#Pittsburg#4000
Nature#Philip Campbell#Weekly#Berlin#6000
*/
public class Zines {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("txt.file"));
input.useDelimiter("#|\n|\r|\r\n");
while(input.hasNext()) {
String title = input.next();
String author = input.next();
String publisher = input.next();
String city = input.next();
String line = input.nextLine();
//int dist = Integer.valueOf(line);
System.out.println(line);
}
}
}
Output is:
"#9000
"#8000
"#10000
"#42000
"#29000
"#4000
"#6000
Output 2:
9000
Rolling Stone
("Exception in thread "main") Jann Wenner
Weekly
Washington
4000
Nature
The question here is why does the #'s still appear after using the delimiter?
Because you are using Scanner#nextLine() to read the last part. It wouldn't consider the delimiter. It will read the complete remaining text after the previously read token, and not the next token.
So, if the previous token read is Boston, the remaining text - #9000, will be read by nextLine().
You should use scanner#next() instead.
String line = input.next();

Getting input from user in Console without using Scanner

I would like to know about other ways of getting input from users using other classes like BufferedReader,etc rather than using Scanner class. So, was there any other way of getting input from the user? If so, was it efficient than Scanner class?
if you are using the Java SE6 or higher then you can make use of Console clas
Console console = System.console();
if (console==null){
System.out.print("console not available ");
}else {
String line = console.readLine("Enter name :");
System.out.print("your name :"+line);
}
You can do it simply by the following steps:
Use the BufferedReader Class and wrap it with the InputStreamReader Class.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
//string str = br.readLine(); //for string input
int i = Integer.parseInt(br.readLine()); // for Integer Input
Now since the readLine method throws an IOException you need to catch it. The whole code will look like this:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
//string str = br.readLine(); //for string input
int i = Integer.parseInt(br.readLine()); // for Integer Input
} catch(IOException ioe) {
ioe.PrintStackTrace();
}
You can use System.in directly, like this:
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
Although this may be a little faster than using the Scanner, it's not an apples-to-apples comparison: Scanner provides more methods for tokenizing the input, while BufferedReader can split your input into lines, without tokenizing it.
Use this:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
to create a reader for System.in, and you can use stdin.readLine() or something to get what you want.
Using a BufferedReader is MUCH more efficient than using a Scanner.
Here for example...
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
int num , num2;
String str[]=new String[2];
System.out.print("Please Enter Your First Number:");
str[0] = stdin.readLine();
System.out.print("Please Enter Your Second Number:");
str[1] = stdin.readLine();
num = Integer.parseInt(str[0]);
num2 = Integer.parseInt(str[1]);
A user can input data at the time of execution of the program without using a scanner class, and this can be done by using the following program.
class Demo
{
public static void main(String ar[])
{
int ab = Integer.parseInt(ar[0]);
int ba = Integer.parseInt(ar[1]);
int res = ab+ba;
System.out.print(res);
}
}
This is a basic program where a user can input data at the time of execution and get the desired result. You can add, subtract, Multiply, divide and concatenate strings, in CMD and a user can input data after compiling the java program i.e at the time of calling the class file. You just need to call the class file and then enter the data after a space.
C:\Users\Lenovo\Desktop>java Demo 5 2
Here ab= 5 and ba= 2. A user can have any number or string if he wants.

Categories

Resources