在java中打印出来自不同方法的变量?

时间:2013-10-02 05:37:09

标签: java methods printing return hex

我必须为此代码使用不同的方法,没有java快捷方式! 这是我的代码:

import java.io.*; 

import java.util.Scanner; 

public class pg3a { 

public static void main(String[] args) throws IOException { 

   Scanner keyboard = new Scanner(System.in); 

   String hex; 
   char choice = 'y'; 
   boolean isValid = false; 
   do { 
      switch (choice) { 
   case 'y': 
      System.out.print("Do you want to enter a hexadecimal number? "); 
      System.out.print("y or n?: "); 
      choice = keyboard.next().charAt(0); 

      System.out.print("Enter a hexadecimal number: #"); 
      hex = keyboard.next(); 
      hex = hex.toUpperCase(); 
      int hexLength = hex.length(); 
      isValid = valid(hex); 
        if (isValid) { 
            System.out.println(hex + " is valid and equal to" + convert(hex)); 
        } 
        else { 
           System.out.println(hex + " is invalid."); 
       } 
     case 'n': 
       System.out.println("quit"); 
      } 
      }while (choice != 'n'); 
} 

public static boolean valid (String validString) { 

  int a = 0; 
  if (validString.charAt(0) == '-') { 
  a = 1; 
} 
 for (int i=a; i< validString.length(); i++) { 
    if (!((validString.charAt(i) >= 'a' && validString.charAt(i) <= 'f')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) 
{ 
return false; 
} 
} 
return true; 
} 

如何在程序检查十六进制数的所有参数并以十进制形式计算它应该是什么后,它打印出十六进制数是有效的,然后十进制数是多少?

另外,我怎样才能使它成为以^ z或^ d结尾的循环来结束程序?

1 个答案:

答案 0 :(得分:0)

要将表示十六进制数字的字符串转换为整数,可以使用Integer.toString(String, int);方法:

Integer parsedValue = Integer.parseInt(hex, 16);

第一个参数是要转换的字符串,第二个参数是基数规范,因此现在这个值为16。

要完成,Integer.toString(Integer,int)与上述相反:它将Integer值转换为指定基数的字符串。

只需创建一个名为convert的方法,然后将其返回。

打印整数不是一个大问题,你可以使用+运算符将它连接到任何字符串。

System.out.println("The value: " + parsedValue);

另外,请记住,您有一点问题:

这一行使你的字符串中的所有字符大写:

hex = hex.toUpperCase(); 

但是你在这里检查小写字母:

if (!((validString.charAt(i) >= 'a' && validString.charAt(i) <= 'f')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) 

要么hex=hex.toLowerCase();,要么调整上述条件以检查“A”和“F”之间。

不得不提的是,检查String的有效性是否转换为数值是不同的:它会触发try-catch块:尝试转换数字,如果失败,则无效...

Integer value; //have to declare it here to be able to access it outside of the try block
try {
   value = Integer.parseInt(hex,16);  

} catch(NumberFormatException e) {
   //if you want to get the stack trace
   e.printStackTrace(); //if not using a proper logging framework!!! Don't just print it!
   //handle the situation: e.g. break loop, write eror message, offer retry for user, etc...
}