How to Get Multiline Input from the User

How to get multiline input from the user

In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n

To get multi-line input from the user you can go like:

no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"

print(lines)

Or

lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)

Multiple lines of input in input type= text /

You need to use a textarea to get multiline handling.

<textarea name="Text1" cols="40" rows="5"></textarea>

How to take multi-line input in Java

You could use the empty line as a loop-breaker:

while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}

How to read multiple lines of raw input?

sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
pass # do things here

To get every line as a string you can do:

'\n'.join(iter(input, sentinel))

Python 2:

'\n'.join(iter(raw_input, sentinel))

How to get a multiple-line input from a user in Java and then store the input in an array of type string where every line is an element of the array

With the help of Scanner class you can take input from cmd and store each line into Array of String or In ArrayList collection.

public static void main(String[] args) {

    ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);

while (s.hasNextLine()) {
String line = s.nextLine();
in.add(line);

if (line != null && line.equalsIgnoreCase("END")) {
System.out.println("Output list : " + in);
break;
}

}

}


Related Topics



Leave a reply



Submit