为什么我的代码会给我一个错误?如果用户输入了错误的号码,代码是否应该输入新的有效号码?好像它并没有让我把喜爱改成新的价值。我怎么能解决这个问题?
# The `with` statement is the proper way to open a file.
# It opens the file, and closes it accordingly when you leave it.
with open('foo.txt', 'r') as file:
# You can directly iterate your lines through the file.
for line in file:
# You want a new sum number for each line.
sum_2 = 0
# Creating your list of numbers from your string.
lineNumbers = line.split(' ')
for number in lineNumbers:
# Casting EACH number that is still a string to an integer...
sum_2 += int(number) ** 2
print 'For this line, the sum of the squares is {}.'.format(sum_2)
控制台输出:
package RobB;
import java.util.Scanner;
public class FavoriteNum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] num = new int[10];
int favorite = 0;
System.out.print("Enter your favorite number: ");
try {
favorite = scan.nextInt();
}
catch (Exception e) {
System.out.println("Enter an integer!");
System.out.print("Enter your favorite number: ");
favorite = scan.nextInt();
}
for (int i = 0; i < 10; i++) {
System.out.print("Enter a random number (" + Math.abs(((i + 1) - 10)) + " to go): ");
num[i] = scan.nextInt();
}
}
}
答案 0 :(得分:1)
这是一个带有while循环的替代方法:
boolean validInput = false;
while (!validInput) {
try {
System.out.print("Enter your favourite number: ");
favorite = scan.nextInt();
validInput = true;
}
catch (Exception e) {
System.out.println("Enter an integer!");
}
}
答案 1 :(得分:0)
在catch
条款中扫描输入似乎不是最好的主意。我建议使用do-while
循环,允许离开此循环的条件可以是boolean
标志,当您确认最终输入有效Integer
时,该状态将被更改。您可能还需要考虑使用Scanner
的{{1}}方法来检查是否提供了正确的输入,如果在您的情况下不是真的需要,则不会抛出任何异常。
以下是 ronhash的答案的一些变体,但使用了hasNextInt()
循环:
do-while
编辑:我编辑了代码,因为前一个代码不合适而且错误。