Java “我怎么能?”;划界;给定字符串中的整数?
我正在做一个练习,我必须从键盘输入一个字符串。字符串将是简单的算术,例如“2+4+6-8+3-7”。是的,格式必须是这样。中间只有一个空格 这样做的目的是获取这个字符串并最终打印出它的答案。到目前为止,这是我的代码:Java “我怎么能?”;划界;给定字符串中的整数?,java,regex,loops,pattern-matching,delimiter,Java,Regex,Loops,Pattern Matching,Delimiter,我正在做一个练习,我必须从键盘输入一个字符串。字符串将是简单的算术,例如“2+4+6-8+3-7”。是的,格式必须是这样。中间只有一个空格 这样做的目的是获取这个字符串并最终打印出它的答案。到目前为止,这是我的代码: public class AddemUp { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.print("Enter someth
public class AddemUp {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 + 137: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
sc.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*");
int sum = 0;
int theInt;
Scanner sc1 = new Scanner(s);
sc1.useDelimiter("\\s*\\s*");
String plusOrMinus = sc1.next();
int count = 0;
if(s.startsWith("-"))
{
sum -= sc.nextInt();
}
while(sc.hasNextInt())
{
theInt = sc.nextInt();
if(count == 0)
{
sum += theInt;
}
else if(plusOrMinus.equals("+"))
{
sum += theInt;
}
else
{
sum -= theInt;
}
sc1.next();
count++;
}
System.out.println("Sum is: " + sum);
}
}
}
在第25行,“sc1.delimiter”所在的位置,我不知道如何让代码跳过所有整数(连同空格)并仅隔离“+”或“-”。一旦实现了这一点,我就可以简单地将其实现到while循环中。尝试使用split()
()方法。这要容易得多
"8 + 33 + 1345 + 137".split("\\+|\\-")
应返回带有数字的数组。请尝试以下操作:
String str = ...
int total = 0;
int operand;
for(int i = 0; i < str.length(); i++){
if(Character.isWhiteSpace(str.charAt(i)))
; // empty
else if(Character.isDigit(str.charAt(i))){
StringBuilder number = new StringBuilder();
while(Character.isDigit(str.charAt(i))){
number.append(str.charAt(i));
i++;
}
operand = Integer.parseInt(number.toString);
}
else if(str.charAt(i)) == '+')
total += operand;
else if(str.charAt(i)) == '-)
total -= operand;
else
throw new IllegalArgumentException();
}
String str=。。。
int-total=0;
整数操作数;
对于(int i=0;i
当然,你应该做一个更好的检查,为非法入境。我刚刚给了你一个主意。如果你想消除数字,留下一个操作数数组,在加号或减号以外的字符上拆分:
String[] ops = str.split("[^+-]+");
仅供参考,当减号是字符类中的第一个或最后一个时,它是一个文字减号(否则它是一个范围)下面的代码可以计算运算符“+”和“-”的序列 我希望它有帮助
public class test1 {
public static void main(String[] args) {
String s= "9-15";
s=s+"/"; /* add / to execute the last operation */
String split[]= new String[s.length()];
for (int i=0;i<split.length;i++){ /* split the string to array */
split[i]=s.substring(i,i+1);
}
String val1="",op="+"; /* val1 : container of the value before the operator to calculate it with total
op : the operator between val1 and val2 at the begin is + */
int som=0;
for (int i=0;i<split.length;i++){
try{
val1=val1+Integer.parseInt(split[i]); /* saving the number after the operation in a string to calculate it,
a number format exception is throwing when the case don't contain integer*/
}catch(NumberFormatException e){
if(op.equals("+")) {
som=som+Integer.parseInt(val1); /*calculate the total */
val1=""; /*initialize val1 to save the second number */
op=split[i]; /* save the operator of the next operation */
}else{
if(op.equals("-")) {
som=som-Integer.parseInt(val1);
val1="";
op=split[i];
}
}
}
}
System.out.println(som);
}
}
公共类test1{
公共静态void main(字符串[]args){
字符串s=“9-15”;
s=s+“/”;/*添加/以执行最后一个操作*/
字符串拆分[]=新字符串[s.length()];
对于(int i=0;i
希望这可能对你有帮助…给你,希望这对你有帮助
您将要看到的代码可以解所有基本方程,这意味着它可以解方程中仅包含
、+
、-
、*
、和/或//code>符号的方程。此方程还可以加、减、乘和/或除小数。此不能包含x^y
,(x)
,[x]
等的olve方程
public static boolean isNum(String e) {
String[] num=new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
boolean ret=false;
for (String n : num) {
if (e.contains(n)) {
ret=true;
break;
}
}
return ret;
}
public static boolean ifMax(String[] e, int i) {
boolean ret=false;
if (i == (e.length - 1)) {
ret=true;
}
return ret;
}
public static String getResult(String equation) {
String[] e=equation.split(" ");
String[] sign=new String[] {"+", "-", "*", "/"};
double answer=Double.parseDouble(e[0]);
for (int i=1; i<e.length; i++) {
if (isNum(e[i]) != true) {
if (e[i].equals(sign[0])) {
double cc=0;
if (ifMax(e, i) == false) {
cc=Double.parseDouble(e[i+1]);
}
answer=answer+(cc);
} else if (e[i].equals(sign[1])) {
double cc=0;
if (ifMax(e, i) == false) {
cc=Double.parseDouble(e[i+1]);
}
answer=answer-(cc);
} else if (e[i].equals(sign[2])) {
if (ifMax(e, i) == false) {
answer=answer*(Double.parseDouble(e[i+1]));
}
} else if (e[i].equals(sign[3])) {
if (ifMax(e, i) == false) {
answer=answer/(Double.parseDouble(e[i+1]));
}
}
}
}
return equation+" = "+answer;
}
输出:
System.out.println(getResult("1 + 2 + 3 + 4 / 2 - 3 * 6"));
1 + 2 + 3 + 4 / 2 - 3 * 6 = 12
您可以使用下面的代码
"8 + 33 + 1345 + 137".split("(\\s\\d*\\s)|(\\s\\d*)|(\\d*\\s)")
这里,正则表达式检查字符串中的数字及其前后的空格
此拆分返回数组[,+,+,+,+]
除非字符串以+/-开头,否则第一位将始终为空,您可以从[1]位置访问数组我不会为此使用Scanner,我会使用模式匹配。相反,Scanner希望在您想要的字符之间使用分隔符,而模式匹配则标识您想要的字符
为了找到操作员,你可以用这个
Pattern p = Pattern.compile("[+-]");
Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7");
while (m.find()) {
String token = m.group(0);
System.out.println(token);
}
当数字和运算符一起在循环中时,逻辑可以直接处理。这就是为什么我要包括这个
Pattern p = Pattern.compile("([^\\s]+)(?:\\s+|$)");
Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7");
while (m.find()) {
String token = m.group(1);
System.out.println(token);
}
是测试正则表达式的好地方。我知道split()方法,但我不想分离方程中的数字。事实上,我已经使用扫描仪“sc”的分隔符完成了这项工作。我需要分离的是运算符符号“+”和“-”。我需要删除数字。使用此问题可能会有所帮助,因为它试图从字符串中删除所有数字,我认为您会发现这与使用数字作为分隔符非常相似。在您的程序中有许多CTE,例如操作数
可能未初始化,在数字中缺少括号。toString
,s
should small inisWhiteSpace
和finnaly output将IndexOutOfBoundException
似乎这将回答6+2/2为4,而不是7个只说“这是您问题的解决方案”的答案不是很好,因为他们在帮助OP学习和提高方面做得不好。此外,OP可能不希望有人给他们一个解决方案,而只是希望朝着正确的方向推进,这样他们就可以自己实施解决方案。答案只是说“这是你问题的解决方案”不是很好,因为他们在帮助OP学习和提高方面做得不好。此外,OP可能不希望有人给他们一个解决方案,而只是希望朝着正确的方向推进,这样他们就可以自己实施解决方案。答案只是说“这是你问题的解决方案”不是很好,因为他们在帮助OP学习和提高方面做得不好。此外,OP可能不希望有人给他们一个解决方案,而只是希望朝着正确的方向推进,这样他们就可以自己实施解决方案。
Pattern p = Pattern.compile("([^\\s]+)(?:\\s+|$)");
Matcher m = p.matcher("2 + 4 + 6 - 8 + 3 - 7");
while (m.find()) {
String token = m.group(1);
System.out.println(token);
}