• java基础:1.1 基础知识速学,程序练习进制转换


    今天开始学习java,之前有C语言的基础,因此很快的浏览了一遍java的基本知识 例如键盘输入、屏幕显示等,主要了解了一下和C语言的区别。十六进制转十进制、十进制转十六进制

    用一个例子总结了一下今天学到的知识:

    十六进制转十进制

    package basic_practice_001;
    
    import java.util.Scanner;
    
    public class NO_01_begin {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		//  0x -->  De
    		Scanner input = new Scanner(System.in);
    		while(1>0)
    		{
    		System.out.print("input a hex String(Enter Q EXIT the System): ");
    		String hexString = input.nextLine();
    		if(hexString.length() < 1) {
    			System.out.println("you least input one string" );
    			System.exit(1);
    		}
    		hexString = hexString.toUpperCase();
    		int hex2decimal = 0;
    		if (hexString.charAt(0)=='Q') System.exit(1);
    		for(int i=hexString.length(),j=1;i>0;i--) {
    			int value = hexString.charAt(i-1);
    			if(value <='9' && value>='0') {
    				hex2decimal += (value-'0')*j;
    				j *=16;
    			}
    			else if(value <='F' && value>='A')  {
    					hex2decimal += (value-'A'+10)*j;
    					j *=16;
    				  }
    			else { System.out.println("you input illegal number");
    					System.exit(1);
    			}
    		}
    		System.out.println("hex to decimal = " + hex2decimal);
    	}
       }
    }

    结果如下:

    十进制转十六进制:

    package basic_practice_001;
    
    import java.util.Scanner;
    
    public class NO_01_begin {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner input = new Scanner(System.in);
    		System.out.println("enter a number:");
    		int decimal = input.nextInt();
    		String hex = "Ox";
    		int yu=0;
    		while (decimal!=0) {
    			yu = decimal%16;
    			char hexDigit = (yu>=0 && yu<=9) ? (char)(yu+'0') : (char)(yu-10+'A');
    			hex = hex + hexDigit;
    			decimal = decimal/16;
    		}
    		System.out.println("covert hex is :" + hex);
       }
    }
  • 相关阅读:
    git和github入门指南(3.1)
    git和github入门指南(2.2)
    git和github入门指南(2.1)
    git和github入门指南(1)
    webpack入门进阶(3)
    webpack入门进阶(2)
    webpack入门进阶(1)
    vue全家桶(4.3)
    vue全家桶(4.2)
    vue全家桶(4.1)
  • 原文地址:https://www.cnblogs.com/l20902/p/10610956.html
Copyright © 2020-2023  润新知