Write program that applies concept of varags method to create function, display() which takes 3 parameters: (1) one parameter named object of String type, (2) one array called atoms, of String type, and (3)variable-length list of parameters named n. Import Scanner class to source file. In the main() function, use tools provided by the Scanner class to take three string literals as inputs one by one. • The first input is the name of a subject (ex: glucose).• The 2nd input is list of atomic symbols (ex: C Cl Na O) • The 3rd input is list of integers (ex: 18 12 5 2).Then, call display() function and pass the 3 inputs as values of parameters of display() function. Upon receiving the values, the display() function must be able to split string literals properly into arrays of String type, except the one passed to object parameter.
Ex
Enter the name of a subject: Sodium carbonate
Enter a list of atomic symbols: Na C O
Enter a list of integers: 2 1 3
The empirical formula of Sodium carbonate is Na2CO3
import java.util.Scanner;
public class Main {
public static void display(String object, String[] atoms, String... n) {
System.out.print("The empirical formula of " + object + " is ");
for (int i = 0; i < atoms.length; i++) {
System.out.print(atoms[i] + (!n[i].equals("1") ? n[i] : ""));
}
System.out.println();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the name of a subject: ");
String object = in.nextLine();
System.out.print("Enter a list of atomic symbols: ");
String atoms = in.nextLine();
System.out.print("Enter a list of integers: ");
String n = in.nextLine();
display(object, atoms.split(" "), n.split(" "));
}
}
Comments
Leave a comment