gpt4 book ai didi

java - 如何添加输入总数以及如何在 for 循环中执行 if-else 语句?

转载 作者:太空宇宙 更新时间:2023-11-04 12:00:55 24 4
gpt4 key购买 nike

1.如何在用户输入数字时添加分数。我不明白。它继续打印 4,而不是更高的分数。另外,我需要返回一个 boolean 答案,当 4 个分数超过 32 时,就会打印 else if 语句。

import java.util.Scanner;

class forloops
{
public static void main (String[] param)
{
runnerscore();
System.exit(0);

} //END main

public static void runnerscore()
{
int score = 1; // initialising the score that is kept throughout the program
int input = 0;

for (int i = 0; i<=3; i++) // for loop for the questions
{

input(score, input); // 2nd method
score = score + 1;
}

if (score<=32) // boolean expression and have used if-else statement
{
System.out.println("The team has " + score + " points so is legal"); // prints out what the score is and if it is legal
}
else if (score >32)
{
System.out.println("The team has " + score + " points so is NOT legal"); // prints out if the score is not legal
}
}

public static int input(int score, int input)
{
Scanner scanner = new Scanner(System.in); //enables scanner that lets the user input
System.out.println("What is the disability class of runner " + score + "?");
input = Integer.parseInt(scanner.nextLine());
return input;
}
}//END DisabilityRate

最佳答案

您实际上从未存储输入总和,而且分数将在 4 处最大化,因为 for 循环将运行 4 次。最后看一下您可能需要的代码:

import java.util.Scanner;

class Example {

// Keep scanner reference here
Scanner scanner = new Scanner(System.in);

/**
* Constructor
*/
public Example() {
runnerScore();
}

/**
* Main method
*
* @param param
*/
public static void main(String[] param) {
new Example();
}

/**
* A method
*/
public void runnerScore() {

int score = 1;
int sumOfInputs = 0;

// for loop for the questions
for (int i = 0; i <= 3; i++) {

int input = input(score); // You need to save somewhere the input
// you get from the user....
System.out.println("The (" + i + ") time , input from user was " + input);

sumOfInputs += input; // sum every input you get

++score; // which is like using score = score + 1 or score+=1
}

// boolean expression and have used if-else statement
if (sumOfInputs <= 32) {

// prints out what the score is and if it is legal
System.out.println("\nThe team has " + sumOfInputs + " points so is legal");

} else if (sumOfInputs > 32) {

// prints out if the score is not legal
System.out.println("\nThe team has " + sumOfInputs + " points so is NOT legal");

}
}

/**
* Return the input from the user
*
* @param score
* @return
*/
public int input(int score) {
int scannerInput = 0;

System.out.println("\nWhat is the disability class of runner " + score + "?");

// String -> integer
scannerInput = Integer.parseInt(scanner.nextLine());

// Return it
return scannerInput;

}
}

关于java - 如何添加输入总数以及如何在 for 循环中执行 if-else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40919912/

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