gpt4 book ai didi

Java 十六进制数和条件

转载 作者:行者123 更新时间:2023-11-30 10:11:39 26 4
gpt4 key购买 nike

我是 Java 的新手,所以我对条件中的十六进制数及其大小有疑问。 Scanner 类也存在一些问题。我在 java 文档中搜索了原始数据类型。

该计划是关于;拿一个数字,看看它可以写入哪种数据类型,然后打印适当的数据类型。

import java.util.*;
import java.io.*;
import java.lang.Integer;


public class Solution{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
long t=sc.nextInt();

for(int i=0;i<t;i++)
{

try
{
long x=sc.nextLong();
System.out.println(x+" can be fitted in:");
if(x>=0x81 || x<=0x7f)System.out.println("* byte");
if(x<=0x7fff || x>=0x8001)System.out.println("* short");
if(x<=0x7fffffff || x>=0x80000001)System.out.println("* int");

//if(x<= (0x7fffffffffffffff)|| x>=
//(0x8000000000000001))System.out.println("*long");
System.out.printf("\n\n%x\n\n",x);
System.out.println();
}
catch(Exception e)
{
System.out.println(sc.next()+" can't be fitted anywhere.");
}

}
}
}

问题:

  1. 我收到评论“if()”条件“太大 int :0x7ffffffffffffffff”的错误消息,为什么会这样?

  2. 我通过注释一些“if()”来运行程序,并给它“10”来搜索可能的数据类型,但这次它只打印“int”数据类型。

  3. 如果我给它“0x7b”作为输入,它会执行到“catch()”部分。为什么?

你能解释一下吗?谢谢。

最佳答案

I get an error message for commented "if()" conditional "too large int :0x7fffffffffffffff " why is that so?

因为 0x7fffffffffffffff 是一个 int 字面量。 7ffffffffffffffff 无法放入 int。不过,它可以放入 long 中。要使其成为 long 文字,您必须在末尾添加 lL:

if(x<= (0x7fffffffffffffffL)|| x>=
(0x8000000000000001L))System.out.println("*long");

但是这个if语句是多余的,因为x已经是long类型了,所以根据定义,它的值必须适合

实际上,使用每种类型的 MAX_VALUEMIN_VALUE 常量比数字文字更不容易出错:

System.out.println(x+" can be fitted in:");
if(x>=Byte.MIN_VALUE || x<=Byte.MAX_VALUE)System.out.println("* byte");
if(x>=Short.MIN_VALUE || x<=Short.MAX_VALUE)System.out.println("* short");
if(x>= Integer.MIN_VALUE || x<=Integer.MAX_VALUE)System.out.println("* int");
System.out.println("*long");

I run the program by commenting some "if()" and give it "10" to search possible data types but this time it prints just only "int" datatype.

我无法复制这个。您注释掉了哪些 if 语句?

If I give it "0x7b" as input it carries out to "catch()" section. Why?

不幸的是,

Scanner.nextLong 无法识别十六进制数。您可以将数字作为字符串读取,检查其前缀,如果它是 0x,则剥离前两个字符,并将其解析为十六进制数字。

关于Java 十六进制数和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com