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.
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 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()));
}
I'm trying to make a program that asks the user to type in 3 cities and the program
is supposed to take the 3 cities , and put them in a String Array , the first city in
[0],second in [1] and third in [2] , I got it to ask for them , collect the answers
but it's only Printing out the first answer, not all 3. Any ideas how I can fix that?
My code looks like this atm
public static void main(String[] args) {
String ans;
String[] favoritStad = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String Användarinlägg1 = scanner1.nextLine();
String Användarinlägg2 = scanner1.nextLine();
String Användarinlägg3 = scanner1.nextLine();
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg1;
favoritStad[2] = Användarinlägg1;
System.out.print(Användarinlägg1);
}
Användarinlägg is userinputt , favorit stad is favcity
the string "ans" was just an idea I tried to make to collect all 3 answers and print it out
but never figured it out
Solved it ! Just needed to add
System.out.print(Användarinlägg2);
System.out.print(Användarinlägg3);
As I suggested in my comment below your question - use a for loop. Also always check twice if you are not using the same variable (for example Användarinlägg1) over and over.
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
In your code you've added the same element 3 times.
You need to use:
favoritStad[0] = Användarinlägg1;
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
And in order to print you can use for loop or just:
System.out.print(favoritStad[0]);
System.out.print(favoritStad[1]);
System.out.print(favoritStad[2]);
You can use for loop to print all the values of an array. You can use something like below:
for (int i=0; i<favoritStad.length();i++){
System.out.println(favoritStad[i])
}
Try this way
favoritStad[1] = Användarinlägg2;
favoritStad[2] = Användarinlägg3;
Now Print Array:
1st way :
for(int i=0; i<favoritStad.length; i++) {
System.out.println(favoritStad[i]);
}
2nd way:
for(String s :favoritStad) {
System.out.println(s);
}
Also you need to print...
System.out.print(favoritStad);
instead of
System.out.print(Användarinlägg1);
For a uni assignment, I have to take input from a text file and sort it into two separate arrays. The text file is a football league table, arranged as such:
Barcelona 34
Real Madrid 32
I have written a piece of code like this:
holdingString = fileInput.readLine ();
StringTokenizer sort = new StringTokenizer (holdingString + " ");
countOfTokens = sort.countTokens();
System.out.println (countOfTokens + " tokens: " + holdingString);
This prints out the number of tokens and what the tokens are for each line, so it gives output of
Two tokens: Barcelona 34
Three tokens: Real Madrid 32
I've then written this piece of code:
for (int i = 0; i < countOfTokens; i++)
{
String temp = sort.nextToken ();
System.out.println(temp);
}
This reads just the next token and prints it out.
However, rather than printing the next token out, I want to check if it is a word or a number, and separate it into a different array accordingly, so it will be like this:
ArrayTeam Zero Element Barcelona
ArrayTeam First Element Real Madrid
ArrayPoints Zero Element 34
ArrayPoints First Element 32
What's the easiest way to do this? I've tried using a try/catch, but didn't get it right. I've also tried using an if statement with \d, but that's not worked either.
Like AmitD, I agree that using split is more appropriate in this case, but if you still like to use a StringTokenizer you do something like:
StringBuilder teamName=new StringBuilder();
for (int i = 0; i < countOfTokens-1; i++)
{
if (i>0) teamName.append(' ');
teamName.append(sort.nextToken());
}
teamNames[k]=teamName.toString(); //add the new team to your teamNames array
points[k]=Integer.parseInt(sort.nextToken()); //if your points array is of int type
you could use java.util.Scanner class to read data from the file. it has methods such as nextInt(), nextDouble ...whhich might be useful in your case.
Scanner scan = new Scanner(file);
int number;
if(scan.hasNextInt()){
number = scan.nextInt();
}
check Scanner API
String readLine = "Real Madrib 40";
String[] team = readLine.split( "\\d" );
System.out.println(team[0]);
String score = readLine.replace( team[0],"" );
System.out.println(score);
Output :
team[0] : Real Madrib
score : 40
You can save all that trouble using split
String strs[] = holdingString.split("\\s");
E.g.
"Barcelona 34".split("\\s"); will return you Array of Strings where
array[0]=Barcelona array[1]=34
From Javadoc of StringTokenizer
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
Update
As #madhairsilence pointed out
You need another deliminator. You can use = like property files
"Real Madrid =34".split("=");//will return you Array of Strings where
array[0]=Real Madrid, array[1]=34
You can use Scanner as you are reading from file.
I am new to Java. How can i read each integer from a line in a text file. I know the reader class has the read and readline functions for it. But in my case i not only want to read the integers in the file but want to know when the line changes. Because the first element of every line denotes an array index and all the corresponding elements are the linked list values attached to that index.
For example, see the 4 line below. In this case i not only want to read each integer but the first integer of every line would be an array index so i will have an a 4 element array with each array element correspoding to a list where A[1]-> 4, A[2]-> 1,3,4 and soo on.
1 4
2 1 3 4
3 2 5
4 2
After retrieving the integers properly i am planning to populate them via
ArrayList<Integer>[] aList = (ArrayList<Integer>[]) new ArrayList[numLines];
EDITED : I had been asked in one the comments that what i have thinked soo far and where exctly i am stucken so below is what i am thinking (in terms of original and pseoudo code mixed)..
while (lr.readLine() != null) {
while ( // loop through each character)
if ( first charcter)
aList[index] = first character;
else
aList[index]->add(second char.... last char of the line);
}
Thanks
Thanks for the scanner hint, Andrew Thompson.
This is how i have achieved it
Scanner sc =new Scanner(new File("FileName.txt"));
ArrayList<Integer>[] aList = (ArrayList<Integer>[]) new ArrayList[200];
String line;
sc.useDelimiter("\\n");
int vertex = 0;
while (sc.hasNextLine()) {
int edge = 0;
line = sc.nextLine();
Scanner lineSc = new Scanner(line);
lineSc.useDelimiter("\\s");
vertex = lineSc.nextInt() - 1;
aList[vertex] = new ArrayList<Integer>();
int tmp = 0;
System.out.println(vertex);
while (lineSc.hasNextInt()) {
edge = lineSc.nextInt();
aList[vertex].add(edge);
System.out.print(aList[vertex].get(tmp) + " ");
++tmp;
}
System.out.println ();
}