猿问

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

所以我想做的是要求用户输入他们的体重和考试 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 );

     }

}


慕桂英546537
浏览 133回答 1
1回答

繁华开满天机

您必须在 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 来定义它们,你必须自己寻找你想要在那里使用的
随时随地看视频慕课网APP

相关分类

Java
我要回答