Respuesta :
Answer:
// import the Scanner class to allow for standard input
import java.util.Scanner;
// Declare the class for the program
public class ChemistryHomework {
// Write the main method header
public static void main(String[] args) {
// Create an object of the Scanner class
// to read from the standard input
Scanner input = new Scanner(System.in);
// Prompt the user to enter an element
System.out.println("Please enter the element");
// Receive and store the user input
String element = input.nextLine();
// Check if the user input is "hydrogen", "helium" or "lithium"
// By ignoring case, if it is "hydrogen", return a text containing the
// atomic weight of hydrogen which is 1.008
if (element.equalsIgnoreCase("hydrogen")){
System.out.println("The weight of " + element + " is " + 1.008);
}
// Else, if by ignoring case it is "helium", return a text containing the
// atomic weight of helium which is 4.0026
else if(element.equalsIgnoreCase("helium")){
System.out.println("The weight of " + element + " is " + 4.0026);
}
// Else, if by ignoring case it is "lithium", return a text containing the
// atomic weight of lithium which is 6.94
else if(element.equalsIgnoreCase("lithium")){
System.out.println("The weight of " + element + " is " + 6.94);
}
// Otherwise, return an error text
else {
System.out.println("Sorry, I don't recognize that element!");
}
} // End of main method
} // End of class declaration
Sample Output 1:
-------------------------------------------------------------
>> Please enter the element
helium
>> The weight of helium is 4.0026
-------------------------------------------------------------
Sample Output 2:
--------------------------------------------------------------
>> Please enter the element
another
>> Sorry, I don't recognize that element!
--------------------------------------------------------------
Explanation:
Comments;
i. The above code has been written in Java.
ii. The code contains comments explaining every line of the code. Kindly go through the comments carefully.
iii. To ignore case of a string, the string method equalsIgnoreCase() is used as shown in the if...else statements of the code.
iv. The code without comments has been re-written as follows;
import java.util.Scanner;
public class ChemistryHomework {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the element");
String element = input.nextLine();
if (element.equalsIgnoreCase("hydrogen")){
System.out.println("The weight of " + element + " is " + 1.008);
}
else if(element.equalsIgnoreCase("helium")){
System.out.println("The weight of " + element + " is " + 4.0026);
}
else if(element.equalsIgnoreCase("lithium")){
System.out.println("The weight of " + element + " is " + 6.94);
}
else {
System.out.println("Sorry, I don't recognize that element!");
}
}
}