![](/img/trans.png)
[英]Java - IF 'input' = 'this' {store string from array into variable}
[英]get input from user and store it in String Array in Java
我编写了一个程序,该程序从用户那里获得“输入学生人数:”的输入,然后将学生姓名添加到其中并在控制台中打印出来。 我写了一个运行良好的代码,但问题是循环已经漫游了一段时间,代码无法正常工作我也想知道如何使用不带扫描仪的命令行参数获取输入并将其存储在字符串数组中
这是我的代码,请帮助,我正在学习Java短语
import java.util.Scanner;
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
next():查找并返回此扫描仪的下一个完整令牌。
nextLine():将此扫描程序前进到当前行之外,并返回被跳过的输入。
尝试放置一个
scanner.nextLine();
如果要忽略该行的其余部分,则在每个nextInt()
之后。
public class StringScanner
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
in.nextLine();// just to ignore the line
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.println("Enter Student Names: "+i);
studentname[i] = in.nextLine();
}
for(String names:studentname)
{
System.out.println(names);
}
}
}
您可以使用数组args[]
不必在此传递学生人数。
因此,您在java <className>
之后在命令提示符处传递的任何名称都将存储在此数组中,并且可以对其进行迭代。
使用ArrayList而不是String Array
声明头文件
import java.util.ArrayList;
更改您的代码
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.println("Enter The number of students:");
int totalstudents = in.nextInt();
//store into arraylist
ArrayList<String> al = new ArrayList<String>();
for(int i = 0; i < totalstudents;i++)
{
System.out.println(i);
System.out.println("Enter Student Names: ");
al.add(in.next());
}
for(int i=0; i< al.size(); i++)
{
System.out.println(al.get(i));
}
添加in.nextLine();
在分配此int totalstudents = in.nextInt();
试试这个代码:
Scanner in = new Scanner(System.in);
//get the input for number of students:
System.out.print("Enter The number of students:");
int totalstudents = in.nextInt();
//store into String array
String studentname[] = new String[totalstudents];
for(int i = 0; i < studentname.length;i++)
{
System.out.print("Enter Student " + i + " Name:");
studentname[i] = in.nextLine();
}
for(int i = 0; i < studentname.length;i++)
{
System.out.println(studentname[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.