File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Problem with accepting a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with accepting a String" Watch "Problem with accepting a String" New topic
Author

Problem with accepting a String

S Thanigaivel
Ranch Hand

Joined: Oct 06, 2005
Posts: 60
Following is capable of accepting a single word
it the input is Hello World
it discards the ' World'
how to accept a small sentence using the same Scanner Class

import java.util.*;

public class getInput
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String name = scan.next();
System.out.println(name);
}
}
Seb Mathe
Ranch Hand

Joined: Sep 28, 2005
Posts: 225
while(scan.hasNext())
System.out.print(scan.next());

Have a look to the method useDelimiter in class Scanner too.


Regards,<br />Seb<br /> <br />SCJP 1.4
S Thanigaivel
Ranch Hand

Joined: Oct 06, 2005
Posts: 60
I'm getting the desired out with the following two codes but i don't know wats actually happening inside can anyone help me by explaining these programs

Method 1:

import java.util.*;
import java.util.Scanner.*;

public class getInput
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\r\n|[\n\r\u2028\u2029\u0085]");

String name = "";

while(scan.hasNext())
{
if (!(name = scan.next()).equals(scan.useDelimiter("\r|\n|[\n\r\u2028\u2029\u0085]")))
break;
}
System.out.println(name);
}
}

Method2:

import java.util.*;
import java.util.Scanner.*;

public class getInput
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\r\n|[\n\r\u2028\u2029\u0085]");

String name = "";
String chk = null;

while(scan.hasNext())
{
chk = scan.next();
name = chk;
if (!chk.equals(null))
break;
chk = null;
}
System.out.println(name);
}
}

Also plz suggest me the best method using Scanner class
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with accepting a String
 
Similar Threads
Newbie is missing something... (javax.swing)
about if-else
Regex: Keep Single dashes Negative Lookahead
err get and set methods and scanner class / JOptionPane