Getting confused about taking multiple strings in a for loop - java

I was writing a code for taking multple strings as input and storing them in an Array like below:
int NumberOfTC=scanner.nextInt();
String[] words=new String[NumberOfTC];
for(int i=0;i<NumberOfTC;i++){
words[i]=sc.nextLine();
System.out.println(words[i]);
}
But this allows a single input string
After much inspection i see that the below code works:
System.out.print("No of Strings to Enter: ");
int num = scanner.nextInt();
scanner.nextLine();
String[] words = new String[num];
for (int i = 0; i < num; i++) {
System.out.print("Enter a String: ");
words[i] = scanner.nextLine();
}
I am not able to decode what is the use of scanner.nextLine() after the scanner.nextInt() line. I mean why my earlier code is not working and prints only a single string whereas the second code works properly

Related

Can't enter all of the strings I want into the string array [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed last year.
So, I know this is probably a really stupid question, I am a beginner trying to learn Java basics and I have a problem with string array that I can't quite figure out. When I try to enter words into string array and the number of words is set by user (for example 5) I always can enter one less word (for example 4 instead of 5). My code is down below.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of words");
int n = scan.nextInt();
String arr[] = new String[n];
System.out.println("Please enter the words");
for (int i = 0; i < arr.length; i++) {
arr[i] = scan.nextLine();
}
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}
}
It is because when you use nextInt(), it is not reading the newline character. You can avoid this using 2 approaches.
Use nextLine i.e. use Integer.parseInt(scanner.nextLine()) instead of nextInt().
int n = Integer.parseInt(scan.nextLine());
String arr[] = new String[n];
Call nextLine before for loop so that the redundant newline is consumed before your for loop.
int n = scan.nextInt();
String arr[] = new String[n];
scan.nextLine();
System.out.println("Please enter the words");

How can I get input validation with Java using Scanner with regex.Pattern and arrays

I want to apply some input validation to a simple Java application using java.util.regex.Pattern. Before adding the pattern matching I was able to get user input into my arrays as expected, but I can't figure out how to do this with the pattern matching included.
This lines seems to be problematic: in.nextLine(); Is it in the wrong place now that I have added the while statement with the pattern matching?
Here is the relevant chunk of code from my little app.
//These variables used during input validation
String tempName;
int tempGrade;
//These regex patterns are for input validation
//Names can be 1-15 letters and grades are 2 digits
Pattern namePattern = Pattern.compile("[A-Za-z]{1,15}");
Pattern gradePattern = Pattern.compile("[0-9]{2,2}");
//Parallel arrays to hold last names and grades
String[] names = new String[5];
int[] grades = new int[5];
Scanner in = new Scanner(System.in);
try {
for(int i = 0; i<5; i++) {
System.out.println("Enter a name:");
tempName = in.nextLine();
System.out.println("Enter a grade:");
tempGrade = in.nextInt();
in.nextLine();
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
}
names[i] = tempName;
grades[i] = tempGrade;
}
No. in.nextLine() is correct (and consumes the trailing newline from calling nextInt()). The problem is your loop.
while(!namePattern.matcher(tempName).matches()) {
System.out.println("Bad input. Try again");
tempName = in.nextLine(); //<-- add this.
}
Without updating tempName, if you enter the loop body you never leave because the condition is always true after printing your message.

How to read array of integers from the standard input in Java?

in one line from the standard input I have 3 types of integers: the first integer is id, the second integer is N - some number, and after that follows N integers, separeted by a single space which I want to store in array or ArrayList. How can I do this using BufferedReader? I have the following code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int ID = Integer.parseInt(line[0]);
int N = Integer.parseInt(line[1]);
My question is is there any elegant way to read the rest of the line and to store it into array?
Use Scanner and method hasNextInt()
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
arr[i]=scanner.nextInt();
i++;
}
}
How can I do this using BufferedReader?
You've already read/split the line, so you can just loop over the rest of the inputted integers and add them to an array:
int[] array = new int[N]; // rest of the input
assert line.length + 2 == N; // or some other equivalent check
for (int i = 0; i < N; i++)
array[i] = Integer.parseInt(line[i + 2]);
This will also let you handle errors within the loop (I'll leave that part to you, should you find it necessary).

Sorting names entered by the user in alphabetical order according to the last name

I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}

alphabetizing a list from a single string

I'm trying to create a program that takes in a single string and sorts the words by alphabetical order, this is what i have at the moment but nothing is printing out:
System.out.println("Enter words, sepaated by commas and spaces");
String input= scanner.next();
String[] words= input.split(" ");
Arrays.sort(words);
StringBuilder zoop= new StringBuilder();
for(int i=1; i<words.length; i++){
zoop.append(" ");
zoop.append(words[i]);
}
String sorted= zoop.toString();
System.out.println(sorted);
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
and
for(int i=0; i<words.length; i++){
scanner.next() only returns the next complete token. In your case, it returns just the first word. Since the for loop started with 1 instead of 0, the program printed nothing.
You have two errors that cooperate to produce no output. First, look at the difference between Scanner.next() and Scanner.nextLine(). Then realize that arrays are 0-based in Java and take a second look at your for loop.
for(int i=1; i<words.length; i++){
should be
for(int i=0; i<words.length; i++){

Categories