How to solve problem with java

0

I was doing a program when there was a problem with the or || I do not really understand why it happens, although the program runs with functionality the result is not the desired First I declare the if with the conditions separated by an or but this goes to the else the code is as follows

import java.util.Scanner;

public class USSD {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
     Scanner lee=new Scanner(System.in);
     String cadena = null;

     char asterisco='*';
     String ayuda;
     int casos;
     char numeral='#';
     int stw = 0;
    ayuda=lee.nextLine();
    casos=Integer.parseInt(ayuda);


       for( int x=0;x<casos;x++) {

         cadena=lee.nextLine();
         int ling=cadena.length()-1;
        for(int a=0;a<cadena.length();a++) {
            if(cadena.charAt(a)==asterisco||cadena.charAt(a)==numeral||cadena.charAt(a)==0||cadena.charAt(a)==1||cadena.charAt(a)==2||cadena.charAt(a)==3||cadena.charAt(a)==4||cadena.charAt(a)==5||cadena.charAt(a)==6|cadena.charAt(a)==7||cadena.charAt(a)==8||cadena.charAt(a)==9) {

            }
            else {
                stw=1;
            }

        }
        if (cadena.charAt(0)==asterisco&&cadena.charAt(4)==asterisco&&cadena.charAt(ling)==numeral&&stw==0) {
         System.out.println("bien");
        }
        else {System.out.println("mal");} 



   }    




    }

}

the program when using the console write * 109 * 123 # and I get "wrong" result but I do not really find the problem because I do not get "well" I was reviewing it in the debugger but the error is given as I said in the or because it is not fulfilled and sends it to the else

I'm waiting for your help lately:)

    
asked by jason argonauta 20.06.2018 в 05:12
source

1 answer

1

Your code can be simplified using a regular expression:

System.out.println("Escriba la cadena: ");
Scanner lee=new Scanner(System.in);
String cadena = lee.nextLine();
String regex = ".*[0-9#*].*";
int stw =(cadena.matches(regex) ? 0 : 1;
int ling=cadena.length()-1;
char asterisco='*';
char numeral='#';

if (
      ling>4
      &&cadena.charAt(0)==asterisco
      &&cadena.charAt(4)==asterisco
      &&cadena.charAt(ling)==numeral
      &&stw==0
    ) 
{
     System.out.println("bien");
} else {
    System.out.println("mal");
} 
lee.close();

Test 1:

Escriba la cadena: 

*109*123#
bien

Test 2:

Escriba la cadena: 

*109*123#djdlj0w
mal
    
answered by 20.06.2018 в 06:05