Converting an ArrayList to an array - java

I have the following problem... I want to read unknown number of strings from the input. So, I made an arraylist 'words' and added all the strings from the input. Then I wanted to convert this arraylist into simpler String array 'wordsarray'(String[])... As I did that I wanted to check if everything is ok (if words are saved in 'wordsarray') so I
tried to print out the whole array... but it doesn't give me what I wanted... It seems like my code does not work. Where is the problem?
Thanks for your help
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
String[] wordsarray = new String[words.size()];
for(int i = 0; i < words.size(); i++) {
wordsarray[i] = words.get(i);
}
for(int i = 0; i < words.size(); i++) {
System.out.println(wordsarray[i]);
}
}

There is a precooked method to do what you are trying to do:
ArrayList<String> words = new ArrayList<String>();
String[] array = words.toArray(new String[words.size()]);
But your code seems correct, are you sure everything is fetched fine inside the ArrayList?
By your comment I guess that the problem is the fact that you don't place everything inside a loop. This code:
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
works only once. If you keep inserting words and pressing enter you are already outside the loop because the Scanner already reached a point in which it didn't have any more lines to fetch.
You should do something like:
boolean finished = false;
while (!finished) {
while(sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals(""))
finished = true;
else
words.add(sc.nextLine());
}
}
}

This works fine for me:
import java.util.*;
public class a
{
public static void main (String [] args) throws Exception
{
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(words.size () < 3 && sc.hasNextLine ()) {
String s = sc.nextLine();
System.out.println ("Adding " + s);
words.add(s);
}
String[] wordsarray = words.toArray(new String [] {});
for(int i = 0; i < words.size(); i++) {
System.out.println("Printing ..." + wordsarray[i]);
}
}
}
Output:
java a
1
Adding 1
2
Adding 2
3
Adding 3
Printing ...1
Printing ...2
Printing ...3

Related

Java Stdin Cannot convert from String[] to String, but inputs are String?

I am doing a programming assignment that takes all of its input from stdin. The first input is an int n to tell you how many strings will follow, and the next n inputs are strings of varying lengths. The goal is to find the longest string(s) and print them.
I thought this was easy, but for the life of me, I cannot get the stdin to work with me. The eclipse arguments entered are (separated by enter):
3
a2
b3c
7
Yet I run the program, and it tells me it cannot convert from String[] to String. I do not understand how any of the above are String[]. The code is below:
import java.util.Scanner;
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
Scanner sc = new Scanner(System.in);
for (int i=0; i < size; i++) {
str[i] = sc.nextLine().split(" "); // The error
//str[i] = sc.next(); This line and the line below throw
//str[i] = sc.nextLine(); no errors, but also gives no output.
}
String[] longest = new String[size];
String[] temp = new String[size];
longest[0] = str[0];
int numToBeat = str[0].length();
int k = 0;
for (int i=0; i < size; i++) {
if (str[i].length() > numToBeat) {
numToBeat = str[i].length();
k = 0;
longest = temp;
longest[k] = str[i];
k++;
}
else if (str[i].length() == numToBeat) {
longest[k] = str[i];
}
}
System.out.println("The longest input strings are:");
for (int i=0; i < k; i++) {
System.out.println(longest[i]);
}
sc.close();
}
}
Tried:
Changing str[i] = sc.nextLine().split(" "); to its other variations in the code
Changing input values
Googling stdin for the last hour trying to find any documentation that helps me
If you are using eclipse arguments separated by enter then your logic is wrong:
according to your logic get 1st element from the eclipse argument like args[0]
another Input is taken from the console.
if you need to take all elements from the eclipse argument follow the below code:
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
int length=0;
String loggestString="";
for (int i=1; i < size; i++) {
str[i] = args[i];
int strLen = str[i].length();
if(strLen>length) {
length=strLen;
loggestString=str[i];
}
}
System.out.println(loggestString);
}
}

Null output while storing tokenized output from StringTokenizer class nextToken() method in an array

I am trying to store the tokens obtained by using StringTokenizer class's nextToken() method. The tokens print fine when I print them. But when I try to store them in an array, they return null. I don't understand what is at play here. Could you please have a look and see what's happening here?
import java.util.*;
class TestSt{
public static void main(String[] args){
String s = "My name is Sugandha";
int len = 0, i=1;
String[] ar = new String[50];
StringTokenizer s1 = new StringTokenizer(s," ");
while(s1.hasMoreTokens()){
ar[i] = s1.nextToken();
i++;
System.out.println(ar[i]);
}
}
}
You are trying to print the value after incrementing i , which means you are printing the next value which is unassigned yet and hence it will print null.
Also noticed you are saving values in the array from 1 index instead of 0, maybe you can fix that as well.
Here is a working code:
import java.util.StringTokenizer;
public class Temp {
public static void main(String[] args) {
String s = "My name is Sugandha";
int i = 0;
StringTokenizer s1 = new StringTokenizer(s, " ");
String[] ar = new String[s1.countTokens()];
while (s1.hasMoreTokens()) {
ar[i++] = s1.nextToken();
}
for(int j= 0 ;j<ar.length;j++){
System.out.println(ar[j]);
}
}
}
use the below code...
public static void main(String[] args) {
String s = "My name is Sugandha";
int len = 0, i = 1;
String[] ar = new String[50];
StringTokenizer s1 = new StringTokenizer(s, " ");
while (s1.hasMoreTokens()) {
ar[i] = s1.nextToken();
System.out.println(ar[i]);
i++; // this line is moved, print and increment
}
}

How to remove duplicate words in string and display them in same order

This is my program to remove duplicate words in a string using set the program
works fine removing duplicate elements, but the output is not in the correct order
public class Remove_DuplicateIN_String {
public static void main(String a[]) throws IOException {
String a1;//=new String[200];
int i;
InputStreamReader reader=new InputStreamReader(System.in);
BufferedReader in =new BufferedReader(reader);
System.out.println("Enter the String ");
a1=(in.readLine());
System.out.print(a1);
System.out.println("\n");
String words[]=new String[100];
words=a1.split(" ");
System.out.println(words.length);
Set<String> uniq=new HashSet<String>();
for(i=0;i<words.length;i++)
{
uniq.add(words[i]);
}
Iterator it=uniq.iterator();
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
Enter the String
hi hi world hello a
hi hi world hello a
5
hi a world hello
I want output as hi world hello a
Use LinkedHashSet
It maintains order and avoid duplicates.
Set wordSet = new LinkedHashSet();
Use LinkedHashSet.
It will track order and also avoid duplicates of elements.
Set<String> linkedHashSet = new LinkedHashSet<String>();
If you have already stored elements in array of strings, you can use collection api to addAll into set.
String words[]=a1.split(" ");
Set<String> linkedHashSet=new LinkedHashSet<String>();
linkedHashSet.addAll(Arrays.asList(words));.
package StringPrograms;
import java.util.Scanner;
public class RemoveDuplicateWords {
public static void main(String[] args) {
boolean flag;
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] str = input.split(" ");
int count = 0;
String[] out = new String[str.length];
for (int i = 0; i < str.length; i++) {
flag = true;
for (int j = 0; j <count; j++) {
if (str[i].equalsIgnoreCase(out[j])) {
flag = false;
break;
}
}
if (flag) {
out[count] = str[i];
count++;
}
}
for (int k = 0; k < out.length; k++) {
if (out[k] != null)
System.out.print(out[k] + " ");
}
}
}
String noDuplicates = Arrays.asList(startingString.split(" ")).stream()
.distinct()
.collect(Collectors.join(" "));
This approach doesn't handle commas and special characters though.

Putting unordered items into an array from a file

I have three CSV files with data that is linked by a string of numbers, I've created a 2d array to store all the data together and have one of the csv files, the data in the other files is not in the same order so I can't simply read line 1 of the file into the first row of the array.
Here's my code
public class grades {
public static void main(String[] args) throws FileNotFoundException
{
int rowc = 0;
String inputLine = "";
String[][] students = new String[10][6];
//Get scanner instance
Scanner scanner = new Scanner(new File("/IRStudents.csv"));
//Set the delimiter used in file
scanner.useDelimiter(",");
while (scanner.hasNextLine()) {
inputLine = scanner.nextLine();
String [] line = inputLine.split(",");
for (int x = 0; x < 2; x++) {
students[rowc][x] = line[x];
}
if (rowc < 9) {
rowc++;
}
else {
break;
}
}
System.out.println(Arrays.deepToString(students));
scanner.close();
Scanner input = new Scanner(new File("/IR101.csv"));
input.useDelimiter(",");
while (input.hasNext()) {
inputLine = input.nextLine();
String[] line = inputLine.split(",");
for (int i = 0; i < 1; i++) {
System.out.println(line[0]);
System.out.println(students[0][i]);
if (line[0].equals(students[0][i])) {
students[2][i] = line[0];
}
}
}
System.out.println(Arrays.deepToString(students));
}
}
I know a lot of it's not very tidy or efficient, but I'd rather it was working. Anyway, how would I loop through the file and add each item to the 3rd column of the array where the corresponding string is that links them?
Thanks.
I hope i understood your problem correctly.
In your case, you could load the 3rd csv into memory and then loop through the arrays (a for inside another for) and check the keys of one array that matches the key on the other (strings that links them) and bind them.
tip: you could initialize the students attributes like this:
students[rowc] = line;

How do I reverse all Strings in my array?

How do I reverse my array output? Like "peter" to "retep" or "max" to "xam"
I tried to use collections but it's not working
This is my code:
import java.util.Scanner;
import java.util.Collections;
public class sdf {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
}
for(int i = 0; i < my_friend_names.length; i++) {
System.out.println("Name: " + my_friend_names[i]);
}
Collections.reverse(input);
System.out.println("After Reverse order: " +input);
}
}
Seems you create a string array, but than proceed to try reverse the input.
If you want to use collections you may do something like this:
List<String> list = Arrays.asList(my_friend_names);
Collections.reverse(list);
System.out.println("After Reverse order: " + list);
Your posted code does not compile, for example you call Collections.reverse() on your scanner variable.
Things that might help you.
You've assumed Collections.reverse() will reverse the Strings within the array - it won't, it simply reverses the order of the Strings, e.g.
Collections.reverse() works on java.util.List not a primitive array, you can use Arrays.toList() if you need it
StringBuilder provides a handle reverse() method
Example, use StringBuilder.reverse() to update replace each item in the array with a reversed String
String[] my_friend_names = { "fred", "alice" };
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = new StringBuilder(my_friend_names[i])
.reverse().toString();
}
System.out.println(Arrays.toString(my_friend_names));
Output
[derf, ecila]
You are trying to print out input which is of type Scanner. Try using StringBuilder
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
String reversedName = new StringBuilder(my_friend_names[i]).reverse().toString();
System.out.println("After reverse: " + reversedName);
}
I think it would be the best way to make a char[] from the String, reverse that char[] and convert it back to a String.
Something like this should do the job:
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
}
input.close();
for(String name : my_friend_names) {
System.out.println("Name: " + name);
}
for(int i=0; i<my_friend_names.length; i++) {
char[] characters=my_friend_names[i].toCharArray();
List<char[]> reverse=Arrays.asList(characters);
Collections.reverse(reverse);
my_friend_names[i]=new String(characters);
}
System.out.println("After Reverse order: ");
for(String name : my_friend_names) {
System.out.println("Name: " + name);
}
Let me know whether it works (or not)
Happy coding :) -Charlie

Categories