gpt4 book ai didi

java - Eclipse - Java,从 double 转换为 int

转载 作者:行者123 更新时间:2023-12-01 12:36:43 26 4
gpt4 key购买 nike

我刚刚开始使用 Eclipse,对 Java 还很陌生。我有一段代码无法编译,因为我生成的随机数不会转换为整数。以下代码块第二行的错误消息为“此方法必须返回 int 类型的结果”。

public class passwordHelper {
public int rNum(String nums, String lets){


int z;


if(nums == "yes" && lets == "yes"){
z = (int)Math.random()*36;
return z;

} else if(nums == "yes"){
z = (int)Math.random()*10;
return z;

} else if(lets == "yes"){
z = (int)Math.random()*26 + 10;
return z;

} else {
System.out.println("Sorry, you need either letters or numbers in your password.");
}
}
}

正如你所看到的,我正在使用“(int)”函数将我的数字转换为整数,但它向我发送了相同的错误消息,我还尝试使用其他转换方法,例如“Math.floor( )”、“Math.round()”以及三者的组合。如果有人想知道这是为用户生成随机数字和字母字符串的代码的一部分。

//感谢您的帮助

最佳答案

你必须在所有分支中返回一个值,有3种可能性:

1) 在 else 分支中返回一个 int:

public int rNum(String nums, String lets){

int z;

if(nums == "yes" && lets == "yes"){
z = (int)Math.random()*36;
return z;

} else if(nums == "yes"){
z = (int)Math.random()*10;
return z;

} else if(lets == "yes"){
z = (int)Math.random()*26 + 10;
return z;

} else {
System.out.println("Sorry, you need either letters or numbers in your password.");
return -1;
}
}

2)抛出未经检查的异常

public int rNum(String nums, String lets){

int z;

if(nums == "yes" && lets == "yes"){
z = (int)Math.random()*36;
return z;

} else if(nums == "yes"){
z = (int)Math.random()*10;
return z;

} else if(lets == "yes"){
z = (int)Math.random()*26 + 10;
return z;

} else {
System.out.println("Sorry, you need either letters or numbers in your password.");
throw new RuntimeException("Sorry, you need either letters or numbers in your password.");
}
}

3)抛出已检查的异常

public int rNum(String nums, String lets) throws Exception {

int z;

if(nums == "yes" && lets == "yes"){
z = (int)Math.random()*36;
return z;

} else if(nums == "yes"){
z = (int)Math.random()*10;
return z;

} else if(lets == "yes"){
z = (int)Math.random()*26 + 10;
return z;

} else {
System.out.println("Sorry, you need either letters or numbers in your password.");
throw new Exception("Sorry, you need either letters or numbers in your password.");
}
}

关于java - Eclipse - Java,从 double 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25516057/

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