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: glucose
Enter list of atomic symbols: C H O
Enter list of integers: 6 12 6
The molecular formula of glucose is C6H12O6
import java.util.Scanner;
public class Q179493 {
/**
* Main method
* @param args
*/
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
String namedObject;
String[] atoms;
int n;
//The first input is the name of a subject (ex: glucose).
System.out.print("Enter the name of a subject: ");
namedObject=input.nextLine();
//The 2nd input is list of atomic symbols (ex: C Cl Na O)
System.out.print("Enter list of atomic symbols: ");
atoms=input.nextLine().split(" ");
n=atoms.length;
//The 3rd input is list of integers (ex: 18 12 5 2).
System.out.print("Enter list of integers: ");
//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.
String []listIntegers=input.nextLine().split(" ");
//Then, call display() function and pass the 3 inputs as values of parameters of display() function.
String[] atomsTemp=new String[n*2];
if(n==listIntegers.length){
for(int i=0;i<n;i++){
atomsTemp[i]=atoms[i];
}
int c=0;
for(int i=n;i<n*2;i++){
atomsTemp[i]=listIntegers[c];
c++;
}
display(namedObject, atomsTemp, n);
}else{
System.out.println("The list of integers is incorrect.");
}
input.close();
}
/***
* display() method 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.
* @param namedObject
* @param atoms
* @param n
*/
private static void display(String namedObject,String[] atoms,int n){
String molecularFormula="";
for(int i=0;i<n;i++){
molecularFormula+=atoms[i]+atoms[i+n];
}
System.out.println("The molecular formula of "+namedObject+" is "+molecularFormula);
}
}
Comments
Leave a comment