• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

Problem with accepting a String

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
}
}
 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic