"buy x share(s) at $y each"
or
"sell x share(s) at $y each"
or
"sell x share(s) at $y each"
解决方案 »
- 最近准备写一个基于javamail的电子邮件客户端,请问有什么参考的书籍没
- 请问自学java SE 应该按什么顺序呐?
- JTextPane指定换行?
- 怎样用java将一篇文章(多行,并且存在空行)读入程序中(如文本框中)
- applet画图不能显示问题
- 郁闷的一比,我路径设置对的,怎么现在运行不起来了,散分!!~~
- Java----服务器开发----学习流程
- 使用eclipse和sysdeo进行开发时,启动tomcat出错。
- 哪里有《Thinking in Java》课后习题解答的免费下载?
- tomcat是不是免费的呀?
- 求NoSuchFieldException的解决方法。
- JDK的lib问题
用户输入buy x share(s) at $y each或者sell x share(s) at $y each其中的一句话。
假如输入了buy x share(s) at $y each,就输出一个
买了x个,每个y元。
假如输入sell x share(s) at $y each,就输出一句
卖了X个,每个y元。
buy (\d+) share(?:s?) at $(\d+) each
然后用反向引用啊
等我写程序给你
public Output(){
Scanner scanner = new Scanner(System.in);
String str = null;
while(!(str = scanner.nextLine()).equals("q")){
if(str.matches("buy\\s\\d+\\s(share|shares)\\sat\\s\\$\\d+\\seach")){
System.out.print("买了"+ getTotal(str) +",每个"+ getPrice(str) +"美元。");
}
else if(str.matches("sell\\s\\d+\\s(share|shares)\\sat\\s\\$\\d+\\seach")){
System.out.print("卖了"+ getTotal(str) +",每个"+ getPrice(str) +"美元。");
}
else{
System.out.println("Wrong Format!Pleass enter again!");
} str = scanner.nextLine();
}
}
public static String getTotal(String str){
int start = str.indexOf(" ");
int end = str.indexOf(" ", start+1); return str.substring(start, end);
}
public static String getPrice(String str){
int start = str.indexOf("$");
int end = str.indexOf(" ", start+1); return str.substring(start+1, end);
}
public static void main(String args[]){
new Output();
}
}
楼主完善细节吧,基本功能是这样的。
把字符串用split处理成字符串数组,下面随便搞咯
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Test {
public static void main(String[] args) throws IOException {
String reg="buy\\s(\\d+)\\sshare(?:s?)\\sat\\s(\\d+)\\seach";
String anotherreg="sell\\s(\\d+)\\sshare(?:s?)\\sat\\s(\\d+)\\seach";
Pattern patternforbuy=Pattern.compile(reg);
Pattern patternforsell=Pattern.compile(anotherreg);
Scanner input=new Scanner(System.in);
String in;
while(true)
{
System.out.print("please enter command:");
in=input.nextLine();
Matcher m=patternforbuy.matcher(in);
Matcher mtwo=patternforsell.matcher(in);
if(m.matches())
System.out.println("买了"+m.group(1)+"个,每个"+m.group(2));
else if(mtwo.matches())
System.out.println("卖了"+mtwo.group(1)+"个,每个"+mtwo.group(2));
else
{
if(in.equalsIgnoreCase("exit"))
{
System.out.println("exit safely");
return;
}
System.out.println("no Match");
}
}
}
}