为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Java 中 if 语句中存在的用户输入?

如何使用 Java 中 if 语句中存在的用户输入?

慕桂英546537 2023-07-28 15:50:14
所以我想做的是要求用户输入他们的体重和考试 1 和 2 的分数,如果他们输入分数,则使用这些变量来计算当前分数。但是,由于分数是由用户通过 if 语句内部的扫描器声明的,因此它不允许我从 if 语句外部使用这些变量。当我想计算 csEx1 和 csEx2 时,如何使用变量“examOneScore”和“examTwoScore”。当我尝试使用它们时,它显示“局部变量 examOneScore 可能尚未初始化。”import java.util.Scanner;public class CurrentScore{    public static void main(String[] args)     {       Scanner keyboard = new Scanner(System.in);       System.out.printf("Weight of Exam 1: ");       double weightExamOne = keyboard.nextDouble();       System.out.printf("Weight of Exam 2: ");       double weightExamTwo = keyboard.nextDouble();       System.out.printf("Do you know your score of first exam? ");          String examOne = keyboard.nextLine();       if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))         {           System.out.printf("Your score? ");           double examOneScore = keyboard.nextDouble();       }       System.out.printf("Do you know your score of secondexam? ");        String examTwo = keyboard.nextLine();       if(answerTwo.equalsIgnoreCase("yes") || answerTwo.equalsIgnoreCase("y"))         {           System.out.printf("Your score? ");           double examTwoScore = keyboard.nextDouble();       }       double csEx1 = (weightExamOne * examOneScore);       double csEx2 = (weightExamTwo * examTwoScore );     }}
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

您必须在 if 语句之外定义稍后要使用的变量:


public static void main(String[] args)

{

    Scanner keyboard = new Scanner(System.in);


    System.out.printf("Weight of Exam 1: ");

    double weightExamOne = keyboard.nextDouble();


    System.out.printf("Weight of Exam 2: ");

    double weightExamTwo = keyboard.nextDouble();


    System.out.printf("Do you know your score of first exam? ");

    String examOne = keyboard.nextLine();


    double examOneScore = 1;

    if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))

    {

        System.out.printf("Your score? ");

        examOneScore = keyboard.nextDouble();

    }


    System.out.printf("Do you know your score of second exam? ");

    String examTwo = keyboard.nextLine();


    double examTwoScore = 1;

    if(examTwo.equalsIgnoreCase("yes") || examTwo.equalsIgnoreCase("y"))

    {

        System.out.printf("Your score? ");

        examTwoScore = keyboard.nextDouble();

    }


    double csEx1 = (weightExamOne * examOneScore);

    double csEx2 = (weightExamTwo * examTwoScore );

}

我使用值 1 来定义它们,你必须自己寻找你想要在那里使用的


查看完整回答
反对 回复 2023-07-28
  • 1 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信