gpt4 book ai didi

Java.util.Scanner 转 int

转载 作者:行者123 更新时间:2023-12-01 14:06:27 25 4
gpt4 key购买 nike

如何将“dryrun.txt”中存储的数字设置为 int url?我知道这是一个非常简单的答案,但我似乎无法理解。我看过其他关于使用 parseInt 的帖子,但是当我这样做时,我总是收到错误,我问了我的老师,他说这仅用于在其他文本中查找数字,在这个文件中它只有 1 个数字。感谢您的帮助。

import java.util.Scanner;
import java.io.*;

public class Even
{
public static void main (String[] args) throws IOException
{
int even = 0;
int url = 0;
int Counter = 2;
Scanner fileScan;

fileScan = new Scanner (new File("dryrun.txt"));
url = fileScan.nextInt();

if ( url > 2)
System.out.println ("Error");
if (url % 2 == 0)
even = (Counter + 2);

System.out.print(" "+ even +" ");
}
}

最佳答案

Okay, yeah you're right sorry I didn't realize that but anyway I still have my original problem, the value in the file is 0 now and it gives me the Error but if I set it to 2 it adds four and doesn't give me the error..

这表明你的逻辑是错误的......

根据此代码,让我们进行一些桌面检查...

if ( url > 2)
System.out.println ("Error");
if (url % 2 == 0)
even = (Counter + 2);

假设url == 4 ...

  • if (url > 2) =if (4 > 2) =true ,打印Error
  • if (url % 2 == 0) =if (4 % 2 == 0) =true , even = Counter + 2

假设url == 2 ...

  • if (url > 2) =if (2 > 2) =false ,什么都不做...
  • if (url % 2 == 0) =if (2 % 2 == 0) =true , even = Counter + 2

假设你想在数字超过1时打印错误你应该使用if (url >= 2)if (url > 1)

假设出现错误时您不想继续计算结果,则应该使用 if-else声明,大致如下...

if ( url > 2)
System.out.println ("Error");
else if (url % 2 == 0) {
even = (Counter + 2);
System.out.print(" " + even + " ");
}

关于Java.util.Scanner 转 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18862929/

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