convert String to arraylist of integers using wrapper class - java

Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.
String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();
System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();
for (int i = 0; i < userString.length(); i++) {
userInts.add(new Integer(in.nextInt()));
}

If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.
If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.
Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.

Lets look at the lines:
String userString = ""
int[] userInt = new int[userString.length()];
At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.
Also this is an array not an arrayList. An arrayList would look like
ArrayList<Integer> myList = new ArrayList()<Integer>;

I'm assuming the in is for a Scanner.
I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.
List<Integer> arr = new ArrayList<Integer>();
while(in.hasNext())
arr.add(in.nextInt());
And, say you know that you will get 10 numbers..
int count = 10;
while(count-- > 0)
arr.add(in.nextInt());

Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.
5
3 20 602 3 1
The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.
This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.

Related

Formatting entered stream data in java

I am curious how to get input data formatted from a user in java, for example if the user enters 1,2,3 how can I get these numbers in an array when the input look like this:
Scanner s = new Scanner();
String inputString = s.nextLine();
I can get a single number
Integer num = Integer.parseInt(inputString)
but I am unsure how handling multiple numbers would go
Well, you'd use... scanner. That's what it is for. However, out of the box a scanner assumes all inputs are separated by spaces. In your case, input is separated by a comma followed by/preceded by zero or more spaces.
You need to tell scanner this:
Scanner s = new Scanner(System.in);
s.useDelimiter("\\s*,\\s*");
s.nextInt(); // 1
s.nextInt(); // 2
s.nextInt(); // 3
The "\\s*,\\s*" think is a regexp; a bit of a weird concept. That's regexpese for 'any amount of spaces (even none), then a comma, then any amount of spaces'.
You could just use ", " too, that'll work, as long as your input looks precisely like that.
More generally if you have a fairly simple string you can use someString.split("\\s*,\\s*") - regexes are used here too. This returns a string array with everything between the commas:
String[] elems = "1, 2, 3".split("\\s*,\\s*");
for (String elem : elems) {
System.out.println(Integer.parseInt(elem));
}
> 1
> 2
> 3

Giving input separated by spaces

Input:
1 10
How can I provide a space between two inputs so that compiler can take both the inputs differently.
I tried to use
st1=in.nextInt();
in.next();
st2=in.nextInt();
Simply remove the in.next(); call. nextInt() already "ignores" whitespaces. And there is no need to create an array by using split() and to convert the number "manually". Just let the Scanner handle this by using nextInt() like you do already:
Scanner s = new Scanner("1 10 9 5");
while(s.hasNextInt()) {
int number = s.nextInt();
System.out.println(number);
}
The good thing about that is, that you won't get a NumberFormatException like in the other answers if the user does not provide numbers (e.g. a b c).
The following line will give you a String array containing the two numbers as strings:
String[] numbersFromUser = in.nextLine().split(" ");
Assuming that the user properly formats the input.
This would of course also work for a number of arguments greater than 2.
You can then go on to convert numbersFromUser[0] and numbersFromUser[1] into the int values you need:
int st1 = Integer.valueOf(numbersFromUser[0]).intValue();
int st2 = Integer.valueOf(numbersFromUser[1]).intValue();
Use:
data = line.split("\s");
first = data[0];
second = data[1];
third = data[2];
System.out.println(first)
System.out.println(second);
System.out.println(third);
Input:
1 5 6
Output:
1
5
6

Accepting a known number of integers on a single line in java

I know there is a similar question already asked, so let me apologize in advance. I am new to Java and before this, my only programming experience is QBasic.
So here is my dilemma: I need to accept 2 integer values and I would like to be able to enter both values on the same line, separated by a space (IE: Enter "45 60" and have x=45 and y=60).
From what I have seen, people are suggesting arrays, but I am weeks away from learning those... is there a simpler way to do it? We have gone over "for", "if/else", and "while" loops if that helps. I don't have any example code because I don't know where to start with this one.
I have the program working with 2 separate calls to the scanner... just trying to shorten/ clean up the code. Any ideas??
Thanks!
//UPDATE:
Here is the sample so far. As I post this, I am also reading the scanner doc.
And I don't expect you guys to do my homework for me. I'd never learn that way.
The println at the end it my way of checking that the values were stored properly.
public static void homework(){
Scanner hwScan = new Scanner(System.in);
System.out.println("Homework and Exam 1 weights? ");
int hwWeight = hwScan.nextInt();
int ex1Weight=hwScan.nextInt();
System.out.println(hwWeight+" "+ex1Weight);
}
Even simple scanner.nextInt() would work for you like below:
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println("x = " + x + " y = " + y);
Output:
1 2
x = 1 y = 2
If you only have to accept two integer numbers you could do something like this:
String input = System.console().readLine(); //"10 20"
//String input = "10 20";
String[] intsAsString = input.split(" ");
int a = Integer.parseInt(intsAsString[0];
int b = Integer.parseInt(intsAsString[1]);
intsAsString is an array, in simple terms, that means it stores n-strings in one variable. (Thats very simplistic, but since you look at arrays more closely later you will see what i mean).
Be sure to roughly understand each line, not necessarily what exactly the lines do but conceptually: Read data form Console, parse the line so you have the two Strings which represent the two ints, then parse each string to an int. Otherwise you will have a hard time in later on.

Reading a multi datatype file into an ArrayList in Java

I am trying to read a file, which the user inputs, and the file has numbers and characters. I only want to store the numbers in an Arraylist but I keep getting stuck, help would be greatly appreciated. This is what I have. Sorry if this has been answered, I am new to the site.
import java.util.*;
import java.io.*;
public class ArrayListClient {
public static final int SIZE = 100;
public static void main(String[] args) throws FileNotFoundException {
String fileName, fileName2;
UnorderedArrayList list1 = new UnorderedArrayList(SIZE);
Scanner input = new Scanner(System.in);
System.out.print("Please input the name of the file to be opened for the first list: ");
fileName = input.nextLine();
System.out.println();
Scanner inputFile = new Scanner(new File(fileName));
int num = inputFile.nextInt();
while(inputFile.hasNextInt()) {
int num2 = inputFile.nextInt();
list1.insertEnd(num);
num = num2;
}
list1.print();
}
}
the input file is 13 c v b 25 34 x x 67 56 10 a a 20 27 2 a s 5 1 45 59
The loop you provided is correct, although you don't need this line outside of the while loop:
int num = inputFile.nextInt();
If the file you provided didn't have a Integer then this would crash your program.
I think you can simply write this and it should work:
while (inputFile.hasNextInt()) {
int num = inputFile.nextInt();
list1.insertEnd(num);
}
The loop checks to see if there is another Integer left in the file (inputFile.hasNextInt()) and then gets it to add to the list (inputFile.nextInt()).
This sounds like it could be a homework question, so I'm hesitant to just give the answer, but if I were you, I would consider writing a filter function (make it a lazy filter if you have to consider files that are very large/won't fit in memory). Your filter function can try Integer.parseInt(yourString); and catch any NumberFormatExceptions that occur because it tried to parse a letter. This approach has the obvious danger of using exceptions to control program flow (normally considered bad practice), but you won't have to traverse the list twice.
Your other obvious option is to write a filter that filters the characters out so that you are only left with number strings, and then just run parseInt over those number strings to turn them into integer values. If performance is a concern, you can avoid double-traversing the list by writing functions that validate a single string value (reject if it's not a number), and then parse it into an int if it is a number, and then add the parsed integers into your array as you go within a foreach loop.
You are most of the way there already since integer detection is built into the Scanner class and the Integer class contains the parseInt() method. Just mutate an array which you define outside of a for each loop and you're good to go.

Sorting info from a txt file into two different arrays

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.

Categories

Resources