Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with accepting a String

 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while(scan.hasNext())
System.out.print(scan.next());

Have a look to the method useDelimiter in class Scanner too.
 
S Thanigaivel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic