亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Java 中 if 語句中存在的用戶輸入?

如何使用 Java 中 if 語句中存在的用戶輸入?

慕桂英546537 2023-07-28 15:50:14
所以我想做的是要求用戶輸入他們的體重和考試 1 和 2 的分數,如果他們輸入分數,則使用這些變量來計算當前分數。但是,由于分數是由用戶通過 if 語句內部的掃描器聲明的,因此它不允許我從 if 語句外部使用這些變量。當我想計算 csEx1 和 csEx2 時,如何使用變量“examOneScore”和“examTwoScore”。當我嘗試使用它們時,它顯示“局部變量 examOneScore 可能尚未初始化?!眎mport 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 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號