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:
- you using 
trim()inline.indexof(" +".trim(), plus2+1), returns index of"+"not" +" - any 1 occurrence of 
" + "counted 4 times, becauseline.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
Post a Comment