gpt4 book ai didi

java - 尝试学习如何错误检查我的代码

转载 作者:行者123 更新时间:2023-12-02 10:46:28 25 4
gpt4 key购买 nike

我试图向用户询问两个两位数,然后对这两个数字执行长度检查和类型检查,然后我想输出数字的总和。这是我到目前为止所拥有的:

package codething;

import java.util.Scanner;
public class Practice {

public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();

if(number.hasNextInt()) {
} else {
System.out.println("Error");
}

int m;



int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}

Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();

if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}

int sum = n + m;
System.out.println(sum);
}
}

目前我的程序甚至不会要求我提供第二个输入。不知道该怎么办:/

最佳答案

有几件事:

- 不要构造多个 Scanner 对象来从 System.in 读取。它只会导致问题。

- 您正在使用 String.valueOf() 将 int 转换为 String。最好简单地检查一下,确保它在 10 到 99 之间。

-您检查以确保 Scanner 在您调用 nextInt 之后有一个下一个 int,但这没有帮助。您需要确保有下一个 int。

-许多 if 语句都有一个空的 if block ,然后您在 else 中执行某些操作。您可以在 if 中执行相反的操作并省略 else (而不是 if(length ==2) {} 您可以执行 if(长度!= 2) {//代码}

Scanner number = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}

int m = 0;


if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}


System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}

if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);

关于java - 尝试学习如何错误检查我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52524018/

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