Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert String into array of characters in java

Tags:

java

arrays

import java.util.*;

public class prac9 
{
    public static void main(String[] args){
    Scanner scn=new Scanner(System.in);

    int count=0;
    String x,str=" ";

    System.out.println("Regular Expression is (a+b)(ab+ba)*");
    System.out.println("Enter a Word: ");
    x=scn.nextLine();  //here simple x string type of varible

    if(x[0]=="a"|| x[0]=="b")  //here x array of string type of varible
    {                          //prac9.java:15: error: array 
                             // required,but String found


         for(int i=1; i<x.length(); i++)
         {
             str+=x[i];  
             if((i%2==0)==true)
             {
                 if(str=="ab" || str=="ba")
                 {
                     count=count+2;
                     str=" ";
                 }
             }

         }
         if((count+1)==(x.length())){
             System.out.println("Acceptable"); 
         }
         else{
             System.out.println("Not Acceptable");
         }

    }
    else{ 
        System.out.println("Not Acceptable..");
    }
}

Please help me as simply as possible. It gives me an error as I mentioned in above comment. I know what it is saying, but I can't figure out how to convert a String into an array so I can check every single character given by a user. Actually, this code was written in C++. I just converted it into Java language.

like image 320
muneeb_ahmed Avatar asked Dec 21 '25 03:12

muneeb_ahmed


1 Answers

if(x[0]=="a"|| x[0]=="b")

can be changed to:

if(x.startsWith("a") || x.startsWith("b"))

and

str+=x[i];

can be changed to:

str+=x.charAt(i);

and lastly:

 if(str=="ab" || str=="ba")

should be changed to

 if(str.equals("ab") || str.equals("ba"))
like image 85
pleft Avatar answered Dec 22 '25 18:12

pleft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!