I'm a beginner so this is definitely common knowledge, so I came here to ask.
If I want to make a very large array that just contains different words, such as this
adjectives[0] = "one";
adjectives[1] = "two";
adjectives[2] = "three";
adjectives[3] = "four";
adjectives[4] = "five";
This is just a small example, the array I'm actually making is very large. Surely I don't have to hardcode this and do each line one by one. How can I do this more efficiently?
EDIT:
Question has slightly shifted while still on the topic.
I want to turn a txt file like this
A
B
C
D
E
into an array list, which is spit out by the program into the console, for use in another program.
Basically textfile.txt -> program -> arraylist.txt
Use a for() loop:
String[] adjectives = new String[6]; //first letter of a non-final variable should be lowercase in java
for(int i = 0; i < adjectives.length; i++) { //loop index from 0 to the arrays length
adjectives[i] = Integer.toString(i) //you could also use an int[]
}
Done.
Also take a look at this:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
If you're trying to simply assign ascending numbers, then use a for loop:
int[] adjectives = int[5];
//replace 5 with whatever you want
for(int x = 0; x < adjectives.length; x++){
adjectives[x] = x
}
If you want to place strings/objects in there that don't have some incremental order, then you can condense the assignment statement to a single line:
String[] adjectives = {"hey", "there", "world", "hello"}
Given the words are comming from a text variable, you could just split it :
String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
String[] words = text.split("[ \n]");
System.out.println(Arrays.toString(words));
You can use a for loop and parse the index of the lop to string:
final String[] foo = new String[10];
for (int i = 0; i < foo.length; i++) {
foo[i] = Integer.toString(i);
}
System.out.println(Arrays.toString(foo));
read a text file line by line and store each read line into an ArrayList with a BufferedReader
`
import java.io.*;
import java.util.ArrayList;
class TxtFileToArrayList
{
public static void main(String args[])
{
ArrayList lines = new ArrayList();
try{
// Open the file
FileInputStream fstream = new FileInputStream("text.txt"/*file path*/);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
//Read File Line By Line
while ((readLine = br.readLine()) != null) {
lines.add(readLine);// put the line in the arrayList
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
}
}
}
`
or use readAllLines()
You can use arraylist and then if you really want arrays only then convert arraylist to array datatype--
List<String> ls=new ArrayList<String>();
for(int i=0;i<=Integer.MAX_VALUE-1;i++)
ls.add(Integer.toString(i));
String array[]=ls.toArray(new String[ls.size()]);
Related
So, I've found a word in a document and print the line in which the word is present like this:
say example file contains : "The quick brown fox jumps over the lazy dog.Jackdaws love my big sphinx of quartz."
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(int i=0;i<lineWords.length;i++){
System.out.print(lineWords[i]+ ' ');
}
And if I search for 'fox' , then linewords[] will contain tokens from the first sentence. and linewords[3] = fox. To print the color of the fox, I need linewords[2].
I was wondering how can we get the 'i' of a token in that linewords[i], because I want the output to be linewords[i-1]
You could use a hashMap which stores the word and a list with the indices.
HashMap<String, List<Integer>> indices = new HashMap<>();
So in the for loop you fill the HashMap:
for(int i=0;i<lineWords.length;i++){
String word = lineWords[i];
if (!indices.contains(word)) {
indices.put(word, new ArrayList<>();
}
indices.get(word).add(i);
}
To get all the indices of a specific word call:
List<Integer> indicesForWord = indices.get("fox");
And to get the i - 1 word call:
for (int i = 0; i < indicesForWord.size(); i++) {
int index = indicesForWord[i] - 1;
if (index >= 0 || index >= lineWords.length) {
System.out.println(lineWords[index]);
}
}
If you are using Java 8, it is straightforward:
List<String> words = Files.lines(Paths.get("files/input.txt"))
.flatMap(line -> Arrays.stream(line.split("\\s+")))
.collect(Collectors.toList());
int index = words.indexOf("fox");
System.out.println(index);
if(index>0)
System.out.println(words.get(index-1));
This solution works also when the word you are searching is the first words in a line. I hope it helps!
If you need to find all occurences, you can use the indexOfAll method from this post.
That can be done by traversing the array and when you get your word , print the one before it.Here's how:-
if(lineWords[0].equals(testWord)
return;//no preceding word
for(int i=1;i<lineWords.length;i++){
if(lineWords[i].equals(testWord){
System.out.println(lineWords[i-1]);
break;
}
}
I got this code here:
try{
FileReader file = new FileReader("/Users/Tda/desktop/ReadFiles/tentares.txt");
BufferedReader br = new BufferedReader(file);
String line = null;
while((line = br.readLine()) != null){
String[] values = line.split(",");
grp1 = new int[values.length];
for(int i=0; i<grp1.length; i++){
try {
grp1[i]= Integer.parseInt(values[i]);
}catch (NumberFormatException e) {
continue;
}
}
System.out.println(Arrays.toString(grp1));
}
System.out.println("");
br.close();
}catch(IOException e){
System.out.println(e);
}
This is what the file im reading contains.
grp1:80,82,91,100,76,65,85,88,97,55,69,88,75,97,81
grp2:72,89,86,85,99,47,79,88,100,76,83,94,84,82,93
Right now im storing the values into one int array.
But if i wanted to store each line of values into two arrays?
Thought about using Arrays.CopyOfRange somehow, and copy the values from the int array
into two new arrays.
This answer won't correspond to your question, but will give a hint to my comment under your question post.
Try this at the beginning of your while loop:
Use String.IndexOf() to find the first occurence of the char : into each line. This will be the beginning index for the second part.
Call String.Substring() from your new beginning index to line.length. This will give you the line without the characters and your first numbers aren't lost.
Before the while
List<int[]> groups = new ArrayList<>();
Before the end of the loop:
groups.add(grp1);
Afterwards:
for (int[] grp : groups) {
...
}
A List is useful for a growing "array".
groups.size() grp1.length
groups.get(3) grp1[3]
groups.set(3, x) grp1[3 = x
I'm trying to make an array of strings using a list of names coming from a txt file.
So for example: If I have string[] names = {all the names from the txtfile(one name perline)}
I want to pass "names" into a method that takes in a array like "names"(the one I made above). The method will then run the names through another for loop and create a linked list. I'm really confusing myself on this and tried number of things but nothing seems to work. Right now It'll print out the first name correctly but every name after that just says null. So I have about 70 nulls being printed out.
public static void main(String[] args) {
//String[] names = {"Billy Joe", "Alan Bowe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
Scanner in = new Scanner(System.in);
System.out.println("Enter File Name: ");
String Finame = in.nextLine();
System.out.println("You Entered " + Finame);
try {File file = new File(Finame);
BufferedReader readers = new BufferedReader(new FileReader(file));
// String nameLine = ;
String[] name;
name = new String[73];
String[] nameTO;
String nameLine;
// while ((nameLine = readers.readLine()) != null) {
for (int i = 0; i < name.length; i++){
name[i] = readers.readLine();
x.populateNodes(name);
} //}
} catch(IOException e) {
}
Why is x.populateNodes(name) inside the loop? Wouldn't you be populating it after filling your array?
Since I've no idea what BigNode is, I assume it should be one of the following
x.populateNodes(name[i]) inside the loop or x.populateNodes(name) outside the loop.
I want to make something read from inputstream to store in an int[] when I type "read 1 2 3 4". what should i do?
I do not know the size of the array, everything is dynamic...
Here is the current code:
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
StringTokenizer st = new StringTokenizer(line);
String command = st.nextToken();
if (command.equals("read")) {
while (st.nextToken() != null) {
//my problem is no sure the array size
}
}
You need to build something to parse the input stream. Assuming it's literally as uncomplex as you've indicated the first thing you need to do is get the line out of the InputStream, you can do that like this:
// InputStream in = ...;
// read and accrue characters until the linebreak
StringBuilder sb = new StringBuilder();
int c;
while((c = in.read()) != -1 && c != '\n'){
sb.append(c);
}
String line = sb.toString();
Or you can use a BufferedReader (as suggested by comments):
BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
String line = rdr.readLine();
Once you have a line to process you need to split it into pieces, then process the pieces into the desired array:
// now process the whole input
String[] parts = line.split("\\s");
// only if the direction is to read the input
if("read".equals(parts[0])){
// create an array to hold the ints
// note that we dynamically size the array based on the
// the length of `parts`, which contains an array of the form
// ["read", "1", "2", "3", ...], so it has size 1 more than required
// to hold the integers, thus, we create a new array of
// same size as `parts`, less 1.
int[] inputInts = new int[parts.length-1];
// iterate through the string pieces we have
for(int i = 1; i < parts.length; i++){
// and convert them to integers.
inputInts[i-1] = Integer.parseInt(parts[i]);
}
}
I'm sure some of these methods can throw exceptions (at least read and parseInt do), I'll leave handling those as an exercise.
You either use a storing structure with nodes, that you can easily append one after another, or, if you really must use arrays, you need to allocate space periodically, as it becomes necessary.
Parse-out the data and keyword from your string then push it into something like this:
public static Integer[] StringToIntVec( String aValue )
{
ArrayList<Integer> aTransit = new ArrayList<Integer>();
for ( String aString : aValue.split( "\\ ") )
{
aTransit.add( Integer.parseInt( aString ) );
}
return aTransit.toArray( new Integer[ 0 ] );
}
I have a multidimensional array built from Strings that is initially created with the size [50][50], this is too big and now the array is full of null values, I am currently trying to remove these said null values, I have managed to resize the array to [requiredSize][50] but cannot shrink it any further, could anyone help me with this? I have scoured the internet for such an answer but cannot find it.
Here is my complete code too (I realise there may be some very unclean parts in my code, I am yet to clean anything up)
import java.io.*;
import java.util.*;
public class FooBar
{
public static String[][] loadCSV()
{
FileInputStream inStream;
InputStreamReader inFile;
BufferedReader br;
String line;
int lineNum, tokNum, ii, jj;
String [][] CSV, TempArray, TempArray2;
lineNum = tokNum = ii = jj = 0;
TempArray = new String[50][50];
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the file path of the CSV");
String fileName = in.readLine();
inStream = new FileInputStream(fileName);
inFile = new InputStreamReader(inStream);
br = new BufferedReader(inFile);
StringTokenizer tok,tok2;
lineNum = 0;
line = br.readLine();
tokNum = 0;
tok = new StringTokenizer(line, ",");
while( tok.hasMoreTokens())
{
TempArray[tokNum][0] = tok.nextToken();
tokNum++;
}
tokNum = 0;
lineNum++;
while( line != null)
{
line = br.readLine();
if (line != null)
{
tokNum = 0;
tok2 = new StringTokenizer(line, ",");
while(tok2.hasMoreTokens())
{
TempArray[tokNum][lineNum] = tok2.nextToken();
tokNum++;
}
}
lineNum++;
}
}
catch(IOException e)
{
System.out.println("Error file may not be accessible, check the path and try again");
}
CSV = new String[tokNum][50];
for (ii=0; ii<tokNum-1 ;ii++)
{
System.arraycopy(TempArray[ii],0,CSV[ii],0,TempArray[ii].length);
}
return CSV;
}
public static void main (String args[])
{
String [][] CSV;
CSV = loadCSV();
System.out.println(Arrays.deepToString(CSV));
}
}
The CSV file looks as follows
Height,Weight,Age,TER,Salary
163.9,46.8,37,72.6,53010.68
191.3,91.4,32,92.2,66068.51
166.5,51.1,27,77.6,42724.34
156.3,55.7,21,81.1,50531.91
It can take any size obviously but this is just a sample file.
I just need to resize the array so that it will not contain any null values.
I also understand a list would be a better option here but it is not possible due to outside constraints. It can only be an multi dimensional array.
I think you need 3 changes to your program
After your while loop lineNum will be 1 more than the number of lines in the file so instead of declaring CSV to String[tokNum][50] declare it as CSV = new String[tokNum][lineNum-1];
tokNum will be the number of fields in a row so your for loop condition should be ii<tokNum rather than ii<tokNum-1
The last parameter for your arraycopy should be lineNum-1
i.e. the modified code to build your CSV array is:
CSV = new String[tokNum][lineNum-1];
for (ii=0; ii<tokNum ;ii++)
{
System.arraycopy(TempArray[ii],0,CSV[ii],0,lineNum-1);
}
and the output will then be:
[[Height, 163.9, 191.3, 166.5, 156.3], [Weight, 46.8, 91.4, 51.1, 55.7],
[Age, 37, 32, 27, 21], [TER, 72.6, 92.2, 77.6, 81.1],
[Salary, 53010.68, 66068.51, 42724.34, 50531.91]]
Notice that you don't really need to handle the first line of the file separately from the others but that is something you can cover as part of your cleanup.
10 to 1 this is a homework assignment. However, it looks like you've put somethought into it.
Don't make the TempArray variable. Make a "List of List of Strings". Something like:
List<List<String>> rows = new ArrayList<ArrayList<String>>();
while(file.hasMoreRows()) { //not valid syntax...but you get the jist
String rowIText = file.nextRow(); //not valid syntax...but you get the jist
List<String> rowI = new ArrayList<String>();
//parse rowIText to build rowI --> this is your homework
rows.add(rowI);
}
//now build String[][] using fully constructed rows variable
Here's an observation and a suggestion.
Observation: Working with (multidimensional) arrays is difficult in Java.
Suggestion: Don't use arrays to represent complex data types in Java.
Create classes for your data. Create a List of people:
class Person {
String height; //should eventually be changed to a double probably
String weight; // "
//...
public Person( String height, String weight /*, ... */ ) {
this.height = height;
this.weight = weight;
//...
}
}
List<Person> people = new ArrayList<Person>();
String line;
while ( (line = reader.nextLine()) != null ) {
String[] records = line.split(",");
people.add(new Person (records[0], records[1] /*, ... */));
}