![](/img/trans.png)
[英]Fibonacci sequence will not print anything but the number that is inputted by the user
[英]Verify User Input is a number only on Fibonacci sequence
import java.util.Scanner;
public class Fibonacci {
public static void main(String args[]) {
int result = UserInput();
fibArray[0] = 1;
fibArray[1] = 1;
for (int i = 0; i < result; i++)
System.out.print(fibonacci(i) + " ");
}
public static long fibArray[] = new long[1000];
public static long fibonacci(long n) {
long fibValue = 0;
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else if (fibArray[(int) n] != 0) {
return fibArray[(int) n];
} else {
fibValue = fibonacci(n - 1) + fibonacci(n - 2);
fibArray[(int) n] = fibValue;
return fibValue;
}
}
public static int UserInput() {
System.out.print("Enter a Fibonacci Number ");
Scanner test = new Scanner(System.in);
int n = test.nextInt();
return n;
}
}
嗨,这不是家庭作业,也不是大学作业。 我刚刚学习 java,我想在我的 UserInput 方法中对斐波那契数列进行检查,我只想输入数字而不是特殊字符或字母。 我在这里阅读了其他类似的主题,但我仍然不确定如何执行此操作。
我将如何实现这一目标?
顺便说一句,如果代码草率,我很抱歉。 谢谢
看看这个。
您可以像这样修改您的代码。 这个想法是检查您从 Scanner 获得的字符串是否是 integer (使用Integer#parseInt方法)。 此外,java 中的一般约定是使用小驼峰式大小写作为方法名称。
public static void userInput(){
System.out.print("Enter a Fibonacci Number");
Scanner test = new Scanner(System.in);
String possibleInteger = test.next();
if(isInteger(possibleInteger)){
//Continue with your code
}
}
private static boolean isInteger(String possibleInteger){
try{
Integer.parseInt(possibleInteger);
return true;
} catch( NumberFormatException ignore ){
return false;
}
}
顺便说一句,我会通过以迭代方式而不是递归和记忆的方式构建斐波那契序列来解决这个问题(并且只需检查当前数字是否大于选中的数字),这样你就不需要额外的空间并且你可以支持大于 fib_1000,祝你好运!
检查输入的值是否是斐波那契数列的一部分
public static Set<Long> fibSet = new HashSet<>();
然后执行以下操作:
int value = UserInput(); boolean has = fibSet.contains(value); for (int i = 0; i < 1000 && has == false; i++) { if (value == fibonacci(i)) { has = true; break; } } System.out.println(value + " is" + (has? "": " not") + " a term in the standard fibonacci sequence");
}
请注意,static 集仅对同一程序中的多次运行有用,因为它检查先前添加的条目。
循环中的 1000 值是任意的,可以更改以增加或减少项的数量。
这是我拥有的解决方案,它适用于大多数数字,但如果它接收的数字大于整数的数量限制,则可能会失败。 公共 static boolean checkIfNumber() {
int pin = 21211;
Integer pinT = pin;
int total = 0;
//Make a character array with all the characters that you want to have.
char[] numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
for (int i = 0; i < number.length; i++) {
if (pinT.toString().contains(numbers[i]) {
total += 1;
}
}
return total < pintT.toString().length();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.