gpt4 book ai didi

java - 用于计算 java 运行次数的计数器

转载 作者:行者123 更新时间:2023-11-30 06:58:30 26 4
gpt4 key购买 nike

这是我的代码,它接受一个输入值并将其与一个随机值进行比较我有 15 次运行代码来估计并获得等于代码决定的随机值的输入值......我想做一个计数器来计算我运行代码的次数......我试着把 count++;在代码的不同地方,但我没有得到正确的答案......你认为在哪里算++;应该放在输出中以获得运行次数......谢谢

这是我的代码

package person;

import java.util.Random;
import java.util.Scanner;

public class Cat {

public static void main(String[] args) {

int max = 100;
int min = 0;
int diff = max-min;
Random rn = new Random();
int i = rn.nextInt(diff+1);
i+=min;
for (int k=0; k<15; k++){
int count=0;
Scanner sb = new Scanner(System.in);
System.out.println("Enter your number");
int x = sb.nextInt();
if(x>i){
System.out.println(x+"is bigger than i");
} else if(x<i){
System.out.println(x+"is smaller than i");
} else if (x==i){
System.out.println(x+"is equals to i "+" "+" no. of try"+count);
break;
}
}
}
}

最佳答案

您的方法的问题在于您的计数处于循环中,因此它总是会被重置。您可以将其移出循环或仅打印计数器循环变量。

package person;

import java.util.Random;
import java.util.Scanner;

public class Cat {

public static void main(String[] args) {

int max = 100;
int min = 0;
int diff = max-min;
Random rn = new Random();
int i = rn.nextInt(diff+1);
i+=min;
int k;
for (k=0; k<15; k++) {
Scanner sb = new Scanner(System.in);
System.out.println("Enter your number");
int x = sb.nextInt();
if(x>i) {
System.out.println(x+"is bigger than i");
} else if(x<i) {
System.out.println(x+"is smaller than i");
} else if (x==i) {
System.out.println(x+"is equals to i "+" "+" no. of try"+k+1);
break;
}
}
if(sb !=null) {
sb.close();
}
}
}

关于java - 用于计算 java 运行次数的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593236/

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