alphabetizing a list from a single string - java

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++){

Related

Getting confused about taking multiple strings in a for loop

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

How can I convert a string in a file into an array?

I have a .txt file and it has some numbers like
0,3,4, ... 9
................
1,2,5, ... 6
This is a sudoku design, I want to take this into an array
Scanner in = new Scanner (new File ("sudoku1.txt")); //here I specified the target of the file like C:\\...
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
String n = in.next();
grid [i][j] = Integer.parseInt(n);
}
}
System.out.println(grid);
when I try to see the array, it give an error because of the " , " in the text file, if I delete commas and put spaces instead of commas, it works but even it shows me only 1 row and it does not work correctly.
Do it as follows:
Scanner in = new Scanner (new File ("sudoku1.txt"));
for(int i=0; i<9 && in.hasNextLine(); i++){
String []nums = in.nextLine().split(",");
for(int j=0; j<nums.length; j++){
String n = nums[j].trim();
grid [i][j] = Integer.parseInt(n);
}
}
System.out.println(Arrays.deepToString(grid));
Scanner can use other delimiters. The default one matches the whitespaces.
Here is an example.
String myDelimiterGroup = "[,\\r\\n]"; // a pattern definition
Scanner scanner = new Scanner(yourFile).useDelimiter(myDelimiterGroup);
Hope it helps.

How to implement infinite for loop in array list if size is not specified

I've tried the following but am not getting any output:
ArrayList<String> list=new ArrayList ();
Scanner s=new Scanner(System.in);
for(int i=0; i<list.size(); i++)
{
System.out.println("Enter string "+(i+1));
String se = s.next();
list.add(se);
}
for(int i=0; i<list.size(); i++)
{
System.out.print(list.get(i));
}
You need to loop on your Scanner input until you get an empty line, not on your List. Your List is empty to start with so you will not enter your loop.
List<String> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
int counter = 1;
String userInput;
System.out.println("Enter string "+ counter);
while (true) { // Infinite loop, you need a break inside of the loop to get out of it
// Assign the input value to the userInput variable
userInput = s.nextLine();
// Stop looping when it is an empty line
if (userInput.isEmpty()) {
break;
}
list.add(userInput);
counter++;
System.out.println("Enter string "+ counter);
}
for (String st : list) {
System.out.println(st);
}
here the size is specified by the user...
now it works...
ArrayList<String> list=new ArrayList ();
Scanner s = new Scanner(System.in);
System.out.println("How many strings to add");
int a = s.nextInt();
for(int i=0; i<a; i++)
{
System.out.println("Enter string "+(i+1));
String se = s.next();
list.add(se);
}
for(int i=0; i<list.size(); i++)
{
System.out.print(list.get(i));
}
The reason you are not getting any output is because you are using list.size() as a comparison value in a loop before you've populated the list with elements. It is empty so it's size will always be 0 until you add some elements to it.
Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
The quote above is from the List Javadoc. Keep in mind that it's always a good idea to read the documentation of new concepts you are trying to use.
You can't use a for-loop on the list's size for the purpose of creating the list in the first place. You need to have some other control mechanism, such as a while-loop that continues until the user enters some sort of "finished" value.
So instead of using the list size (like the comment above states) you should be using another control mechanism like a local variable which can define the size of your list. It can also be used to set the initial capacity of your list.
// Use this local variable as a control mechanism
final int listSize = 10;
// Create new array with the initial capacity set to 10
List<String> list = new ArrayList<>(listSize);
Scanner s = new Scanner(System.in);
// Use a dedicated integer value for the loop
for(int i = 0; i < listSize; i++)
{
System.out.println("Enter string " + (i+1));
String se = s.nextLine();
list.add(se);
}
// Once the list has been populated we can use it's
// size as a comparison value in a loop
for(int i = 0; i < list.size(); i++)
{
// Print each string in a new line
System.out.println(list.get(i));
}
Couple of notes that might help you in the future:
Use System.out.println instead of System.out.print whenever you want to print each log in a separate line.
Format your code in a readable manner so it's easier for both you and others to review it. In my opinion this includes separating each element in a syntax with at least a single whitespace as well as following the proper naming convention.
First loop in your code tries to iterate over values between 0 and list.size() - also 0, because your list is empty.
In this example your program will keep asking for string unless user provide STOP_WRITING_CODE value which is exit.
static final String STOP_WRITING_CODE = "exit";
ArrayList<String> list=new ArrayList();
Scanner s=new Scanner(System.in);
String se = "";
while (true) {
System.out.println("Enter string: ");
se = s.next();
if(se != STOP_WRITING_CODE)
break;
list.add(se);
}
for(int i=0; i < list.size(); i++) {
System.out.print(list.get(i));
}

Using split() method in a two dimensional array?

I want to take input as a single line with spaces then enter that data into the two dimensional array.
String[][] examples = new String[100][100];
for (int i = 0; i < 2; i++) {
System.out.println("enter line " + i);
String line = sc.next();
String[] linearr = line.split("\\s+");
for (int j = 0; j < 5; j++) {
examples[i][j] = linearr[j];
System.out.println(linearr[j]);
}
}
Only the linearr[0] gets value entered ...linearr[1] , linearr[2] , so on do not get values rather says index out of bounds.
sc.next() only returns the first word.
sc.nextLine() returns the whole line.
And instead of
for(int j=0;j<5;j++)
{
examples[i][j]=linearr[j];
System.out.println(linearr[j]);
}
you can just do
examples[i] = linearr;
Instead of the sc.next():
String line=sc.next();
You should use:
String line=sc.nextLine();
Because next() can read input only till space and should be used for only single word.And if you are about to read a line you should use nextLine()
To know more read this
You wanted to receive a line, but your current code only receive a word per input.
Instead of using:
String line=sc.next(); //receive a word
Change it to:
String line=sc.nextLine(); //receive a line
so on dont get values rather says index out of bounds.....
Instead of using 5, the number of String tokens from the split can be used as the loop control for your inner loop, so you may want:
for(int j=0; j < linearr.length; j++)
This will prevent IndexOutOfBoundsException when there are lesser than 5 words in the input.

Why do I get 2 values as input not the 3 values

In this code I can get upto only 2 values instead of 3 input values. Why does it so? Please explain me.
Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
String arr[] = new String[size];
System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
arr[i] = input.nextLine();
System.out.println(i);
}
nextInt will get the integer from the input buffer and will leave the new line character in the buffer. So when you call nextLine after that, the new line character in the buffer will be returned. To fix this, add a nextLine after calling nextInt
Scanner input = new Scanner(System.in);
System.out.println("Enter how many string to get");
int size;
size = input.nextInt();
input.nextLine();//get the new line character and ignore it
String arr[] = new String[size];
System.out.println("Enter strings one by one");
for(int i = 0; i < size; i++) {
arr[i] = input.nextLine();
System.out.println(i);
}
See the answer from this link , it explains in detail what you are experiencing: Using scanner.nextLine()
In short the first nextLine reads the rest of the line from your nextInt call.
Use input.nextInt() instead of input.nextLine().
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
next() reads the input only till the space. It doesnt read the space between words.

Categories