java


Create string from only part of user input


The project I am working on now is an interactive one. It is focused on learning language. I want the user to be able to input data, and the console to respond with a set sentence based on what the user wrote.
I am stuck at "My name is". I have been researching the scanner.skip function all morning, but cannot seem to find the information I need on how to get it to do what I want it to do. I want the user to write "My name is [name]." I then want the console to split this answer into two separate strings, "My name is" and "[name]".
I want to be able to check that "My name is" matches exactly to "My name is", while ignoring whatever "[name]" happens to be. I want to be able to access "[name]" later on, however, so that the console is able to talk to the user using their entered name. How would I go about doing this with the scanner.skip function? Is this even the correct function to use?
I'd use substring:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
System.out.printf("line: '%s'%n", line);
if (line.startsWith("My name is ")) {
String name = line.substring("My name is ".length());
System.out.printf("name: '%s'%n", name);
} else {
// print error or something
System.out.println("Error: line has to start with 'My name is ' string.");
}
}
}
BufferedReader is used, because it's quicker and in this case it's not important for later processing...
Ideone link
public class Test {
public static void main(String[] args) {
String var = "My Name Is Uly";
String name = var.replace("My Name Is ", "");
String firsPart = var.replace(" " + name, "");
System.out.println(firsPart + " " + name);
}
}
If you are willing to provide the introductory text (" My name is :") then you can get the name like this:
cn = System.console();
name = cn.readLine("My name is ");
System.out.println("Name entered : " + name);
alternatively you can also parse the string:
cn = System.console();
name = cn.readLine();
//n= no of chars in your text :My name is
name = name.substring(n);
System.out.println("Name entered : " + name );
You don't need skip. Just read the whole strong, the using functions available as members of the String class, check that it starts with "My name is", and, if it does, take a substring starting and the end of that prefix (+1 for space), and store it in a vvariable to use as the name later.
public class test {
public static void main(String args[]) {
Scanner sc;
do {
sc = new Scanner(System.in);
String s = sc.nextLine();
if (s.equalsIgnoreCase("exit")) {
System.out.println("Bye");
break;
}else if(s.length()>11 && s.substring(0,10).equalsIgnoreCase("my name is")) {
String name = s.substring(11);
System.out.println("your name is:"+name);
} else {
System.out.println("Sorry incorrect answer ... ");
}
}while (true);
}
}
import java.util.Scanner;
public class Name{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str = input.nextLine();
if(str.indexOf("My name is ") >= 0){
String name = str.substring(str.indexOf("My name is ")+11, str.length());
System.out.println("Your name is: "+name);
}
else
System.out.println("Error: Could not find name!");
}
}
Tests if the entered String has an index of "My name is " and then breaks the String into a substring to extract the name from the input.

Related Links

set OutputStream for a process
Is there a “global” Ctrl + . (Jump to Error) shortcut in Eclipse?
How to use a variable data as a scope variable in jstl
API to check if BlackBerry device is password-protected
Enum.valueOf throws a warning for unknown type of class that extends Enum?
How to tell XStream to ignore child elements that have the 'class' attribute
Beginner Java - using substring() to make a long string into seperate lines
Java ScheduledThreadPool multithreads stops after some time
How can I unit test servlets with JUnit 4?
How to trigger alerts based upon timestamps in database?
anyway to rearrange a arraylist and remove printline
NetBeans clean and build makes disable components enabled
JTable method called when sorting by column
get an applet into the web browser
How do I generate random sample data in my Oracle database?
How to delete or show details about an Object contained in list and presented in dataTable using JSF framework?

Categories

HOME
maven
openlayers
cloud
pypi
keras
reflection
fft
q
at-command
yarn
binary-tree
echarts
slurm
communication
numeral.js
timeout
vb.net-2010
task
windows-phone-7
caml
libtiff
pugjs
normalizr
openedx
introduction
emulator
swiftlint
excel-2007
one-to-many
facet
chromebook
url-scheme
react-css-modules
brunch
wtx
libssl
quote
http-status-code-503
ioio
grails-3.1
kendo-ui-grid
wpf-controls
ios5
swisscomdev
space-complexity
greenrobot-eventbus
broadcastreceiver
unoconv
ensembles
grid.mvc
isbn
import-from-excel
s
babel-core
avconv
smartcontracts
prolog-setof
domain-model
setter
forever
slickedit
pillow
epson
linode
spring-mongodb
spring-cache
orthogonal
vtigercrm
ableton-live
infix-notation
transmitfile
xml-attribute
paypal-express
skype4py
energy
phpcas
marching-cubes
retina
pundit
responsive-images
ideamart
fluid-dynamics
nsight
lustre
website-monitoring
block-device
java-metro-framework
markers
zend-route
castle
fluentautomation
industrial
pyhdf
jplaton
buster.js
hungarian-algorithm
anonymous-methods
chuck
wse3.0
netdna-api
infobox
file-comparison
jquery-ui-droppable
ncqrs
thunderbird-lightning
firefox4
uimenucontroller
xetex
sector
port-number
private-members
paul-graham

Resources

Encrypt Message