给定Java中的int
,我希望能够确定数字的数百位数。例如:
我已尝试过以下代码,但收到以下错误:
对于参数类型boolean,int
,运算符未定义
这是我的代码:
import java.util.Random;
class adam{
public static void main(String[]args)
{
Random rnd = new Random();
int first = rnd.nextInt(900)+100;
int second = rnd.nextInt(900)+100;
int third = rnd.nextInt(900)+100;
System.out.println(first);
System.out.println(second);
System.out.println(third);
if ((first==second&&first==third)/100);
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
int
中获取数百位数的数字?答案 0 :(得分:0)
您需要的只是数字中的倒数第三位。 所以你可以试试这个:
String temp = number + "";
System.out.println(temp.charAt(temp.length() - 3));
答案 1 :(得分:0)
如何从Java
int
中获取数百位数的数字?
你的整数除法是正确的。您还可以使用模数运算符来处理数字> = 1000。
最容易显示数学,这应该足以让你继续:
2468 (1) start with an integer, 2468
2468 / 100 = 24 (2) divide by 100 to discard 10's and 1's
24 % 10 = 4 (3) modulo 10 to discard 1000's and higher
4 (4) and your left with your 100's digit
正如你所看到的,你可以在(2)停止,如果你知道你不会看到数字> = 1000.顺便说一下,如果你不得不处理负数,你首先要取绝对值号。
为什么我的代码中出现此错误?
因为这句话是无稽之谈:
if ((first==second&&first==third)/100);
特别是条件是:
(first==second&&first==third)/100
如果你把它分成它的部分,你可以看到发生了什么:
first == second (1) == produces a boolean
first == third (2) == produces a boolean
(1) && (2) (3) && produces a boolean
100 (4) 100 is an int
(3) / (4) (5) now you have boolean / int
您无法将boolean
除以int
。
答案 2 :(得分:0)
此代码有效:
import java.util.Random;
class Adam{
public static void main(String[]args)
{
Random rnd = new Random();
int first = rnd.nextInt(900)+100;
int second = rnd.nextInt(900)+100;
int third = rnd.nextInt(900)+100;
System.out.println(first);
System.out.println(second);
System.out.println(third);
int first1=first/100;
int second1=second/100;
int third1=third/100;
System.out.println("an input of "+first +" an output of "+first1 +" first");
System.out.println("an input of "+second +" an output of "+second1+" first");
System.out.println("an input of "+third +" an output of "+third1+" first");
}
}