I want to organize a text file with multiple data
A 33 9.25
V 92 1.123
H 100 2.4
into a parallel Array
So far I got to declaring the arraylist and i know i need to do something with a while loop and hasnext... not sure where to go from there.
public static void main(String[] args) throws IOException
{
Scanner fileIn = new Scanner ( new File("sortdata.txt"));
ArrayList<Character> array1 = new ArrayList<Character>();
ArrayList<Integer> array2 = new ArrayList<Integer>();
ArrayList<Double> array3 = new ArrayList<Double>();
while (fileIn.hasNext())
String i = fileIn.next();
int k = 0;
for(i.index(k);i.length();i.index(k++))
if (i.index(k) =='.')
{
}
}
I know some of my code is wrong but I've been looking at it for a long time, think i'm just missing something minor here.
After reading each line from the file here String i = fileIn.next();, trim() the String(to eliminate leading and trailing white spaces as suggested by #X86) and then follow the below steps.
Split the String on white space using the String#split() method.
The String[] returned by the split method above contains all the 3 data required.
From the string[0] get the character using string.charAt(0) and put it into the Character ArrayList.
Parse string[1] as a Integer using Integer.parseInt(string[1]) and put it into the Integer ArrayList.
Parse string[2] as a Double using Double.parseDouble(string[2]) and put it into the Double ArrayList.
This should work:
while (fileIn.hasNextLine()) {
String c[]= fileIn.nextLine().split(" ");
array1.add(new Character(c[0].charAt(0)));
array2.add(new Integer(c[1].trim()));
array3.add(new Double(c[2].trim()));
}
Related
This is a project from school, but i'm only asking for help in the logic on one small part of it. I got most of it figured out.
I'm being given a file with lines of string integers, for example:
1234 123
12 153 23
1234
I am to read each line, compute the sum, and then go to the next one to produce this:
1357
188
1234
I'm stuck on the scanner part.
public static void doTheThing(Scanner input) {
int[] result = new int[MAX_DIGITS];
while(input.hasNextLine()) {
String line = input.nextLine();
Scanner linesc = new Scanner(line);
while(linesc.hasNext()) {
String currentLine = linesc.next();
int[] currentArray = convertArray(stringToArray(currentLine));
result = addInt(result, currentArray);
}
result = new int[MAX_DIGITS];
}
}
In a nutshell, I want to grab each big integer, put it an array of numbers, add them, and then i'll do the rest later.
What this is doing it's basically reading all the lines and adding everything and putting it into a single array.
What i'm stuck on is how do I read each line, add, reset the value to 0, and then read the next line? I've been at this for hours and i'm mind stumped.
Edit 01: I realize now that I should be using another scanner to read each line, but now i'm getting an error that looks like an infinite loop?
Edit 02: Ok, so after more hints and advice, I'm past that error, but now it's doing exactly what the original problem is.
Final Edit: Heh....fixed it. I was forgetting to reset the value to "0" before printing each value. So it makes sense that it was adding all of the values.
Yay....coding is fun....
hasNext method of the Scanner class can be used to check if there is any data available in stream or not. Accordingly, next method used to retrieve next continuous sequence of characters without white space characters. Here use of the hasNext method as condition of if doesn't make any sense as what you want is to check if the there are any numerical data left in the current line. You can use next(String pattern).
In addition, you can try this solution even though it is not optimal solution...
// In a loop
String line = input.nextLine(); //return entire line & descard newline character.
String naw[] = line.split(" "); //split line into sub strings.
/*naw contains numbers of the current line in form of string array.
Now you can perfom your logic after converting string to int.*/
I would also like to mention that it can easily & efficiently be done using java-8 streams.
An easier approach would be to abandon the Scanner altogether, let java.nio.io.Files to the reading for you and then just handle each line:
Files.lines(Paths.get("/path/to/my/file.txt"))
.map(s -> Arrays.stream(s.split("\\s+")).mapToInt(Integer::parseInt).sum())
.forEach(System.out::println);
If i were you i would be using the BufferedReader insted of the Scanner like this:
BufferedReader br = new BufferedReader(new FileReader("path"));
String line = "";
while((line = br.readLine()) != null)
{
int sum = 0;
String[] arr = line.split(" ");
for(String num : arr)
{
sum += Integer.parseInt(num);
}
System.out.println(sum);
}
Considering the level you're on, I think you should consider this solution. By using only the scanner, you can split the lines into an array of tokens, then iterate and sum the tokens by parsing them and validating that they're not empty.
import java.util.*;
class SumLines {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
while(S.hasNext()) {
String[] tokens = S.nextLine().split(" ");
int sum = 0;
for(int i = 0; i < tokens.length; i++) {
if(!tokens[i].equals("")) sum += Integer.parseInt(tokens[i]);
}
System.out.println(sum);
}
}
}
I am trying to write a code that looks at a text file, and does a while loop so that it reads each line, but I need each word per line to be in an array so I can carry out some if statements. The problem I am having at the moment is that my array is currently storing all the words in the file in an array.. instead of all the words per line in array.
Here some of my current code:
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("test.txt"));
List<String> listwords = new ArrayList<>();
while (in.hasNext()) {
listwords.addAll(Arrays.asList(in.nextLine().split(" ")));
}
if(listwords.get(4) == null){
name = listwords.get(2);
}
else {
name = listwords.get(4);
}
If you want to have an array of strings per line, then write like this instead:
List<String[]> listwords = new ArrayList<>();
while (in.hasNext()) {
listwords.add(in.nextLine().split(" "));
}
Btw, you seem to be using the term "array" and "ArrayList" interchangeably.
That would be a mistake, they are distinct things.
If you want to have an List of strings per line, then write like this instead:
List<List<String>> listwords = new ArrayList<>();
while (in.hasNext()) {
listwords.add(Arrays.asList(in.nextLine().split(" ")));
}
You can use
listwords.addAll(Arrays.asList(in.nextLine().split("\\r?\\n")));
to split on new Lines. Then you can split these further on the Whitespace, if you want.
My question is -
how to convert a String ArrayList to an Integer ArrayList?
I have numbers with ° behind them EX: 352°. If I put those into an Integer ArrayList, it won't recognize the numbers. To solve this, I put them into a String ArrayList and then they are recognized.
I want to convert that String Arraylist back to an Integer Arraylist. So how would I achieve that?
This is my code I have so far. I want to convert ArrayString to an Int Arraylist.
// Read text in txt file.
Scanner ReadFile = new Scanner(new File("F:\\test.txt"));
// Creates an arraylist named ArrayString
ArrayList<String> ArrayString = new ArrayList<String>();
// This will add the text of the txt file to the arraylist.
while (ReadFile.hasNextLine()) {
ArrayString.add(ReadFile.nextLine());
}
ReadFile.close();
// Displays the arraystring.
System.out.println(ArrayString);
Thanks in advance
Diego
PS: Sorry if I am not completely clear, but English isn't my main language. Also I am pretty new to Java.
You can replace any character you want to ignore (in this case °) using String.replaceAll:
"somestring°".replaceAll("°",""); // gives "sometring"
Or you could remove the last character using String.substring:
"somestring°".substring(0, "somestring".length() - 1); // gives "somestring"
One of those should work for your case.
Now all that's left is to parse the input on-the-fly using Integer.parseInt:
ArrayList<Integer> arrayInts = new ArrayList<Integer>();
while (ReadFile.hasNextLine()) {
String input = ReadFile.nextLine();
try {
// try and parse a number from the input. Removes trailing `°`
arrayInts.add(Integer.parseInt(input.replaceAll("°","")));
} catch (NumberFormatException nfe){
System.err.println("'" + input + "' is not a number!");
}
}
You can add your own handling to the case where the input is not an actual number.
For a more lenient parsing process, you might consider using a regular expression.
Note: The following code is using Java 7 features (try-with-resources and diamond operator) to simplify the code while illustrating good coding practices (closing the Scanner). It also uses common naming convention of variables starting with lower-case, but you may of course use any convention you want).
This code is using an inline string instead of a file for two reasons: It shows that data being processed, and it can run as-is for testing.
public static void main(String[] args) {
String testdata = "55°\r\n" +
"bad line with no number\r\n" +
"Two numbers: 123 $78\r\n";
ArrayList<Integer> arrayInt = new ArrayList<>();
try (Scanner readFile = new Scanner(testdata)) {
Pattern digitsPattern = Pattern.compile("(\\d+)");
while (readFile.hasNextLine()) {
Matcher m = digitsPattern.matcher(readFile.nextLine());
while (m.find())
arrayInt.add(Integer.valueOf(m.group(1)));
}
}
System.out.println(arrayInt);
}
This will print:
[55, 123, 78]
You would have to create a new instance of an ArrayList typed with the Integer wrapper class and give it the same size buffer as the String list:
List<Integer> myList = new ArrayList<>(ArrayString.size());
And then iterate through Arraystring assigning the values over from one to the other by using a parsing method in the wrapper class
for (int i = 0; i < ArrayString.size(); i++) {
myList.add(Integer.parseInt(ArrayString.get(i)));
}
I'm trying to sort a list of strings in array into alphabetical order without using the sort method.
public static String[] sortedAdjectives(String[] original)
{
String[] sortedArray;
int aValue = 65;
String word = "";
sortedArray = new String[25];
for(int i = 0; i <25; i++)
{
original[i]=word;
char c = word.charAt(0);
sortedArray[c-aValue]=word;
}
return sortedArray;
Is my method, and
public static void main(String[] args) throws FileNotFoundException {
Scanner names = new Scanner(new File("names.txt"));
Scanner adjectives = new Scanner(new File("adjectives.txt"));
String[] adjectiveArray;
adjectiveArray = new String[25];
int counter = 0;
while (counter<25)
{
String in = adjectives.next();
fixCapitalization(in); //method that fixes capitalization
adjectiveArray[counter]=in;
counter++;
}
sortedAdjectives(adjectiveArray);
Is where I put the items from the file into an array. I'm getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hmwk.sortedAdjectives(Hmwk.java:56)
at Hmwk.main(Hmwk.java:24)
When I try to run my program and I can't figure out where I'm going wrong. If you could point me in the right direction i'd be much appreciative. Thanks for your time.
You have word initialized as an empty string:
String word = "";
Then you are calling charAt(0) on an empty string. Can't do that.
Your string needs to be at least longer than 1 character in order to call that method.
You made a little mistake in the for loop.
It should probably be word = original[i]; which you did it inversely and makes the word never take the original parameter as reference.
Also a few things to improve here: using arraylist would have better extensibility and avoid erasing repetitive letters.
I have as an input a String which is a set of numbers with spaces between them, for example:
"30 129 48 29 110 90"
What I want to do is to take that String and input it in an array as integers without firstly using a second array which will store the numbers as Strings. This is what I know how to do:
String line = input.nextLine();
String[] arr = line.split(" ");
int[] array = new int[arr.length];
for (int i = 0; i < arr.length; i++){
array[i] = Integer.parseInt(arr[i]);
}
I want to not make 2 arrays to do the job but in some way to have it done at once in the for loop, I just want it like that because it would be better to my eyes and I like writing clean code which I'll be able to easily correct later.
EDIT:After jogabonito's answer this is what I managed to do
Scanner input = new Scanner(System.in);
System.out.printf("Input: ");
StringTokenizer line = new StringTokenizer(input.nextLine());
int[] numbers = new int[line.countTokens()];
for (int i = 0; line.hasMoreTokens(); i++){
numbers[i] = Integer.parseInt((String)line.nextElement());
}
Your current approach is fine, but if you want you "could" do this using StringTokenizer.
Create an int[] of size determined by countElements(), and then in a while -loop doing an Integer.parseInt(tokenizer.nextElement())
Tested code:
String input = "30 129 48 29 110 90";
StringTokenizer tokenizer = new StringTokenizer(input);
int count = tokenizer.countTokens();
int x[] = new int[count];
int i=0;
while (tokenizer.hasMoreElements()) {
x[i++] = Integer.parseInt((String)tokenizer.nextElement());
}
You can use the Scanner:
Scanner sc = new Scanner(System.in);
while sc.hasNextInt()
int i = sc.nextInt();
I don't know if it is more readable though, or even if it is better performant. But it sure is another way of doing it. And you cannot know beforehand how many ints would be there, so you'll need to use a list.
Are you sure you WANT to use an array instead of a Collection?
I think something along the following lines
String input = "30 129 48 29 110 90";
List<Integer> list = new ArrayList<Integer>();
for (String token: input.split(" ")) {
list.add( Integer.valueOf( token ) );
}
You could of course convert the list to an array:
Integer[] array = list.toArray( new Integer[] {} );
I just want it like that because it would be better to my eyes and I like writing clean code which I'll be able to easily correct later.
In that case, don't change a thing. What you have is probably as readable as it can be.