英文:
reading of string array
问题
我正在尝试在Java中读取一组字符串值,但我只能读取到第n-1个值,例如,如果字符串数组大小为4,我只能提供3个输入。
以下是我的代码。
package my_project;
import java.util.Scanner;
public class ArrayString
{
public static void main(String[] args)
{
int n;
String key;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of courses:");
n = sc.nextInt();
if (n <= 0)
{
System.out.println("Invalid range");
System.exit(0);
}
System.out.println("The available courses are:");
String[] courses = new String[n];
for (int i = 0; i < n; i++)
{
courses[i] = sc.nextLine();
}
for (int i = 0; i < n; i++)
{
if (courses[i].equals("java"))
{
System.out.println("course is available ");
System.exit(0);
}
}
}
}
英文:
I am trying to read set of string values in java but i am able to read only upto n-1 value i.e for eg if string array size is 4 i am bale to give only 3 inputs.
here is my code.
package my_project;
import java.util.Scanner;
public class ArrayString
{
public static void main(String[] args)
{
int n;
String key;
Scanner sc=new Scanner (System.in);
System.out.println("Enter the no of courses:");
n=sc.nextInt();
if(n<=0)
{
System.out.println("Invalid range");
System.exit(0);
}
System.out.println("The available courses are:");
String [] courses=new String[n];
for(int i=0;i<n;i++)
{
courses[i]=sc.nextLine();
}
for(int i=0;i<n;i++)
{
if(courses[i].equals("java"))
{
System.out.println("course is available ");
System.exit(0);
}
}
}
}
答案1
得分: 0
public static void main(String... args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.print("输入课程数量:");
int n = sc.nextInt();
sc.nextLine(); // 在读取整数后加入此行以读取后续的字符串
if (n <= 0)
System.out.println("无效的范围");
else {
System.out.println("可用课程有:");
String[] courses = new String[n];
for (int i = 0; i < n; i++) {
System.out.format("#%d: ", i + 1);
courses[i] = sc.nextLine();
}
for (int i = 0; i < n; i++) {
if ("java".equalsIgnoreCase(courses[i])) {
System.out.println("课程可用");
return;
}
}
}
}
}
英文:
public static void main(String... args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.print("Enter the no of courses: ");
int n = sc.nextInt();
sc.nextLine(); // add this to read String after int
if (n <= 0)
System.out.println("Invalid range");
else {
System.out.println("The available courses are:");
String[] courses = new String[n];
for (int i = 0; i < n; i++) {
System.out.format("#%d: ", i + 1);
courses[i] = sc.nextLine();
}
for (int i = 0; i < n; i++) {
if ("java".equalsIgnoreCase(courses[i])) {
System.out.println("course is available");
return;
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论