# Finite State Machine: Check Whether Number is Divisible by 3 or not

```import java.io.*;
class andivision {
public static void main(String args[]) throws IOException {
System.out.println("Enter a number");

int o = 0;
int q = 0;

System.out.print("\nq0");
for (int i = 0; i < n.length(); i++)

{

switch (n.charAt(i)) {
case '0':
case '3':
case '6':
case '9':
{
switch (q) {
case 0:
{
o = 1;
q = 0;
break;
}
case 1:
{
o = 0;
q = 1;
break;
}
case 2:
{
o = 0;
q = 2;
break;
}
}
System.out.print(" ->q" + q);
break;
}
case '1':
case '4':
case '7':
{
switch (q) {
case 0:
{
o = 0;
q = 1;
break;
}
case 1:
{
o = 0;
q = 2;
break;
}
case 2:
{
o = 1;
q = 0;
break;
}
}
System.out.print(" ->q" + q);
break;
}
case '2':
case '5':
case '8':
{
switch (q) {
case 0:
{
o = 0;
q = 2;
break;
}
case 1:
{
o = 1;
q = 0;
break;
}
case 2:
{
o = 0;
q = 1;
break;
}
}
System.out.print(" ->q" + q);
break;
}
}
}

/***/

System.out.println("\nOutput");
System.out.println("Is " + n + " Is Divisible By 3:");
if (o == 0) {
System.out.println("No");
} else {
System.out.println("Yes");
}
}
}

/* OUTPUT

Enter a number
462

q0 ->q1 ->q1 ->q0
OutputIs 462 Is Divisible By 3:Yes

Enter a number535

q0 ->q2 ->q2 ->q1
OutputIs 535 Is Divisible By 3:No

*/
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.