方法一:Pattern和Matcher對正則表達式的運用、arraylist的元素添加以及和數組間的轉換:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str = input.next(); List<String> List = new ArrayList<String>(); //多項式的校驗,詳情看上篇 if (str.matches( "^(([-+]([1-9][0-9]*)(\\*x(\\^[+-]?([1-9][0-9]*))?))|(([1-9][0-9]*)\\*(x(\\^[+-]?([1-9][0-9]*))?))|([-+](x(\\^[+-]?([1-9][0-9]*))?))|([-+]([1-9][0-9]*))|(([1-9][0-9]*))|((x(\\^[+-]?([1-9][0-9]*))?)))+$")) { //多項式的匹配 Pattern pattern = Pattern.compile( "([-+]([1-9][0-9]*)(\\*x(\\^[+-]?([1-9][0-9]*))?))|(([1-9][0-9]*)\\*(x(\\^[+-]?([1-9][0-9]*))?))|([-+](x(\\^[+-]?([1-9][0-9]*))?))|([-+]([1-9][0-9]*))|(([1-9][0-9]*))|((x(\\^[+-]?([1-9][0-9]*))?))"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { List.add(matcher.group()); //將單項式一個一個加到list中 } String[] strs= new String[List.size()];// 聲明數組存放單項式,數組大小是list的長度 int i = 0; for (String s: List) { // 將list中的單項式轉存到數組中,String s: List語句是☞將list里面的元素對象轉換成String類型的字符串 strs[i] = s; System.out.println(strs[i]); i++; } } else System.out.println("Wrong Format"); } }
方法二:算法思路——字符串的替代
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String str = input.next(); //多項式的校驗 if (str.matches( "^(([-+]([1-9][0-9]*)(\\*x(\\^[+-]?([1-9][0-9]*))?))|(([1-9][0-9]*)\\*(x(\\^[+-]?([1-9][0-9]*))?))|([-+](x(\\^[+-]?([1-9][0-9]*))?))|([-+]([1-9][0-9]*))|(([1-9][0-9]*))|((x(\\^[+-]?([1-9][0-9]*))?)))+$")) { str=str.replaceAll(" {1,}","").replaceAll("\\^-","\\^b").replaceAll("-","c-").replaceAll("\\+","d\\+");//先將所有的指數中的負號^-轉換成^b,用以區別運算符中的減號,再將所有的運算符-替換成c-,最后將所有的運算符+換成d+ if(str.charAt(0)=='c')//特列:如果首字符串是c,即轉換前是負號 str=str.replaceFirst("c-","-");//為了使分割后的單項式首相不為空,便將c-換成- String[] s=str.split("[dc]");//以運算符為標志將多項式分割開來存放在數組s中 for(int i=0;i<s.length;i++) { s[i]=s[i].replaceAll("b", "-");//將所有指數中的負號替換回來 System.out.println(s[i]); } } else System.out.println("Wrong Format"); } }
方法二要注意首項為負號的情況:
if(str.charAt(0)=='c')//如果首字符串是c,轉換前是負號 str=str.replaceFirst("c-","-");//替換回來