我想问一下如何让我的代码只是获取输入而不是声明它?这是我的计划。我想输入不同的原子序数而不仅仅是" 37"喜欢我的代码中的内容。别担心我的评论,用我的母语。谢谢!
public class ElectConfi {
public static void main(String s[]) {
int atomicNumber = 37;
String electronConfiguration = getElectronConfiguration(atomicNumber);
System.out.println(electronConfiguration);
}
public static String getElectronConfiguration(int atomicNumber) {
int[] config = new int[20]; //dito nag store ng number of elec. in each of the 20
orbitals.
String[] orbitals = {"1s^", "2s^", "2p^", "3s^", "3p^", "4s^", "3d^", "4p^", "5s^",
"4d^", "5p^", "6s^", "4f^", "5d^", "6p^", "7s^", "5f^", "6d^", "7p^", "8s^"};
//Names of the orbitals
String result="";
for(int i=0;i<20;i++) //dito ung i represents the orbital and tapos ung j
represents ng electrons
{
for(int j=0;(getMax(i)>j)&&(atomicNumber>0);j++,atomicNumber--) //if atomic
number > 0 and ung orbital ay kaya pa magsupport ng more electrons, add
electron to orbital ie increment configuration by 1
{
config[i]+=1;
}
if(config[i]!=0) //d2 nagche-check to prevent it printing empty
orbitals
result+=orbitals[i]+config[i]+" "; //orbital name and configuration
correspond to each other
}
return result;
}
public static int getMax(int x) //returns the number of max. supported electrons by each
orbital. for eg. x=0 ie 1s supports 2 electrons
{
if(x==0||x==1||x==3||x==5||x==8||x==11||x==15||x==19)
return 2;
else if(x==2||x==4||x==7||x==10||x==14||x==18)
return 6;
else if(x==6||x==9||x==13||x==17)
return 10;
else
return 14;
}
}
答案 0 :(得分:2)
您可以使用Scanner
或BufferedReader
并获取用户输入
使用Scanner
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
使用BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int atomicNumber = Integer.parseInt(reader.readLine());
答案 1 :(得分:0)
public static String getElectronConfiguration(int atomicNumber) {}
此方法接受任何int
值并返回String
结果。所以你只需要提供不同的数字作为输入。此方法无需更改。
如何提供不同的输入?
您可以使用Scanner来执行此操作。
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
现在调用你的方法
String electronConfiguration = getElectronConfiguration(atomicNumber);
还有其他方法吗?
您可以在代码中为atomicNumber
定义一组值,然后您可以在循环中运行这些值
答案 2 :(得分:0)
您可以从命令行参数获取用户输入:
public static void main(String s[]) {
if (s.length == 0) {
// Print usage instructions
} else {
int atomicNumber = Integer.parseInt(s[0]);
// rest of program
}
}
答案 3 :(得分:0)
您可以通过以下方式从命令行参数获取输入:
Scanner scanner = new Scanner(System.in);
String inputLine = scanner.nextLine(); //get entire line
//or
int inputInt= scanner.nextInt();//get an integer
检查java.util.Scaner api以获取更多信息 - http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
希望这有帮助!