java - How to detect whitespace of operator -


i have problem code.

i want detect whitespace of operator " + ", " +", "+ " or "+".

i want output

  • whitespace of operator "a"

how can modify code?

my code here.

scanner input = new scanner (new file(path file)); int plus1; int plus2; int plus3; int plus4; string splus = ""; while (in.hasnext()) {     string line = in.nextline();     in.hasnextline();     loc++;     if (line.length() > 0) {          plus1 = -1;         plus2 = -1;         plus3 = -1;         plus4 = -1;         while (true) {             plus1 = line.indexof(" + ", plus1 + 1);             plus2 = line.indexof(" +", plus2 + 1);             plus3 = line.indexof("+ ", plus3 + 1);             plus4 = line.indexof("+", plus4 + 1);              if (plus1 > 0) {                 splus = "a";             }             if (plus2 > 0) {                 splus = "b";             }             if (plus3 > 0) {                 splus = "c";             }             if(plus4 > 0){                 splus = "d";             }              if ((plus1 < 0) || (plus2 < 0) || (plus3 < 0) || (plus4 < 0)) break;         }     } } 

there 2 problems logic:

  1. you using trim() in line.indexof(" +".trim(), plus2+1), returns index of "+" not " +"
  2. any 1 occurrence of " + " counted 4 times, because line.indexof(" +") count occurrences of " + "

for 2. easier use line.indexof('+'), , check before , after index see how many whitespaces there are:

int plus = line.indexof('+'); if(plus == -1) break; if(line.charat(plus-1) == ' ') {     if(line.charat(plus+1) == ' ') //a;     else //b; }  else if(line.charat(plus+1) == ' ') {     //c }  else {     //d } 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -