Reputation: 7
can you help me to solve this one problem in Java. All I want is terminating the program by simply typing "end" when I prompt user to input anything in any number of Lines. I search through google but I can't do anything to solved this by my own. I'm just a beginner in programming especially writing Java program.
int nom;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number max. is 10:");
nom = input.nextInt();
if ( nom > 10){
System.out.println("Sorry you exceed the limit of number of lines!");
System.exit(0); //
}
String[] Nput = new String[nom];
for(int counter = 0; counter < nom; counter ++ ) {
System.out.println("Input anything here in line:" +(counter+1));
Nput[counter] = input.next();
}
input.close();
System.out.println("Number of lines is:" + nom + "\r\nYou typed:");
for(int counter = 0; counter < nom; counter ++ ) {
System.out.println(Nput[counter]);
Upvotes: 1
Views: 169
Reputation: 621
Update the for loop as follows, where you input the strings and check whether the given string is equal to the "end" or whatever your breaking condition is. Then use the transfer keyword break to jump from the for loop.
for(int counter = 0; counter < nom; counter ++ ) {
System.out.print("Input anything here in line " +(counter+1)+" : ");
Nput[counter] = input.next();
if(Nput[counter].equals("end")){
break;
}
}
Upvotes: 1