图灵机实现
Java實現圖靈機XNx2
語言環境:
eclipse java
代碼
Number
import java.util.Scanner; class Number {private int n;//用戶輸入的數private String binary;//二進制數private String binarycode;//二進制編碼public Number() {//類的構造方法System.out.print("請輸入一個十進制的數:");Scanner input=new Scanner(System.in);while(true)//判斷輸入數的正確性{n=input.nextInt();if(n<=0){System.out.println("請輸入大于0的數:");continue;}else break;}}public void binary() {binary=Integer.toBinaryString(n);//將數n轉化為二進制字符串binarycode=new String();binarycode+="0";for(int i=0;i<binary.length();i++)//將二進制字符串轉化為二進制編碼字符串{if(binary.charAt(i)!='0')binarycode+=binary.charAt(i)+"0";elsebinarycode+=binary.charAt(i);}binarycode+="110";}public void binaryPrint() {System.out.print("此數的二進制形式為:");System.out.println(binary);System.out.print("此數的二進制編碼為:");System.out.println(binarycode);}public String getBinarycode() {//用于提取二進制編碼return binarycode;} }TuringXNx2類
public class TuringXNx2 {public static void main(String[] args) {Number n=new Number();//創建對象用戶進行輸入int i=0,memory=0;n.binary();String binarycode=n.getBinarycode(),binarycodex2=new String(),binaryout=new String();//創建三個字符串,分別用來存放計算前的二進制編碼和計算后的二進制編碼以及計算后的二進制數n.binaryPrint();for(i=0;i<binarycode.length();i++) {//進行圖靈機XNx2的計算if(i+1==binarycode.length()){//實現對二進制編碼最后的動態加0binarycode+="0";}if(memory==0 && binarycode.charAt(i)=='0') {binarycodex2+='0';memory=0;System.out.println("內態為0,輸入為0,操作后改變為: " + binarycode + " 內態為:" + memory + " 輸出為:" + binarycode.charAt(i));continue;}else if(binarycode.charAt(i)=='1'&&memory==0) {binarycodex2+='0';memory=1;System.out.println("內態為0,輸入為1,操作后改變為: "+binarycode+" 內態為:"+memory+" 輸出為:"+binarycode.charAt(i));continue;}else if(memory==1&&binarycode.charAt(i)=='0') {binarycodex2+='1';memory=0;System.out.println("內態為1,輸入為0,操作后改變為: "+binarycode+" 內態為:"+memory+" 輸出為:"+binarycode.charAt(i));continue;}else if(memory==1&&binarycode.charAt(i)=='1') {memory=10;binarycodex2+='0';System.out.println("內態為1,輸入為1,操作后改變為: "+binarycode+" 內態為:"+memory+" 輸出為:"+binarycode.charAt(i));continue;}else if(memory==10&&binarycode.charAt(i)=='0') {memory=11;binarycodex2+='1';System.out.println("內態為10,輸入為0,操作后改變為:"+binarycode+" 內態為:"+memory+" 輸出為:"+binarycode.charAt(i));continue;}else if(memory==11&&binarycode.charAt(i)=='0') {memory=0;binarycodex2+="10";System.out.println("內態為11,輸入為0,操作后改變為:"+binarycode+" 內態為:"+memory+" 輸出為:"+binarycode.charAt(i));break;}} System.out.println("計算結果為:"+binarycodex2);System.out.print("計算的二進制結果為:");for(i=0;i<binarycodex2.length();) {//找到計算后的二進制編碼中的第一個1并輸出if(binarycodex2.charAt(i)!='1'){i++;}else{System.out.print("1");binaryout+="1";i++;break;}}for(;i<binarycodex2.length();) {//輸出之后的二進制數if(binarycodex2.charAt(i)=='0'&&binarycodex2.charAt(i+1)=='1') {if(binarycodex2.charAt(i+2)=='0'){System.out.print("1");binaryout+="1";i=i+2;}else{break;} }else {System.out.print("0");binaryout+="0";i=i+1;}}System.out.print("\n");System.out.println("整數結果為:"+Integer.parseInt(binaryout,2));//輸出轉化為整數的結果} }總結
- 上一篇: 三天打鱼,两天晒网。
- 下一篇: 数组元素数组中的元素通过解析字符串参数获