Mallige.BS :
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);
}
}
}
}
oleg.cherednik :
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;
}
}
}
}
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=400435&siteId=1