How do i declare custom generated strings inside a while loop? - java

What I'm trying to do is to declare a certain amount of strings according to the amount of tokens a scanner scans in a single input, then have these strings equal the next input. This is what I'm trying:
int numberOfTokens = 0;
boolean mainLoop = true;
Scanner input = new Scanner(System.in);
while(mainLoop == true)
{
while(input.hasNext())
{
String int(+ numberOfTokens) = input.next(); (this doesn't work)
numberOfTokens += 1;
}
}
I hope I made it clear of what I am trying to do. I tried using String arrays, but they won't work for what i'm trying to do.
Thanks.

You can do:
String[] myStringArray = new String[abc];
where abc is an integer you get from user
and then
myStringArray[index] = input.next();
and index must be a valid number between 0 and abc

If you don't know in advance how many strings you will need to store then an array is a poor choice of data structure, at least during the input phase. Use a List instead -- these keep the elements in order, yet expand as needed to accommodate new elements. They are convenient to work with overall, but if you ultimately must get the strings in array form (e.g. because some external API requires that form) then it is easy to obtain the corresponding array.
For example:
List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
tokens.add(input.next());
// a List keeps track of its own length
}
If you later wanted the array then you could do
String[] tokenArray = tokens.toArray(new String[0]);
The number of tokens recorded in the List is available at any time as tokens.size(), or after you convert to an array, as tokenArray.length.
In any event, you cannot create new variables at runtime in Java.

Instead of string variables, you should declare one variable like this before the while loop.
List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
tokens.add(input.next());
}
You can then operate on the tokens, like this:
int n = tokens.size();
for (String token : tokens) {
System.out.println(token);
}

Related

JAVA: How to convert String ArrayList to Integer Arraylist?

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)));
}

Continuous input gathering until conditions met?

I am trying to understand gathering user input and looping until conditions.
I want to loop a scanner until user inputs 0, however, I need each inputted integer to be stored so it can be accessed for later use. The hard part is, I can't use an array.
simply you can do something like
List mylist = new ArrayList(); //in java. other wise you can create array[size]
int input = 1;
while(input!=0)
{
/* input number from user here */
if(input!=0)
mylist.add(input);
}
Here is an easy way to loop user input until 0 is entered.
Scanner console = new Scanner(System.in);
boolean loop = true;
String input;
while(loop) {
input = console.nextLine();
//Add input to a data structure
if (input.equals("0")) {
loop = false;
}
}
As far as adding the user input to a data structure, you said you can't use an Array. How about a List or a Set. Even a Stack or a Queue would work. Have you looked at using any of these data structures?
Here is a basic example using a List:
List<String> aList = new ArrayList<String>();
aList.add(input);
And this is how you might use a Stack:
Stack<String> stk = new Stack<String>();
stk.push(input);
Perhaps the most efficient way would be to use a HashSet:
Set<String> set = new HashSet<String>();
set.add(input);
Using arrays here would be little tricky since you don't know the numbe of elements user is going to enter. You can always write the code to create a new array with bigger capacity once user has exhaused initial capacity and copy over existing input elements but using List would be much easier.
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<>();
int nextInt = Integer.MIN_VALUE;
while((nextInt = scanner.nextInt()) != 0){
input.add(nextInt);
}
See this question if you really want to use arrays. Answer explains on creating new arrays and copying over elements. Java dynamic array sizes?

A couple questions regarding anagrams

This is a follow on to a couple questions I've already asked. Earlier I asked how to use a method to determine if elements of one list were present in another. The reason I did this is because I would like like to determine if one list contains anagrams of the other - using user input and a dictionary list. I'm having trouble determining this. I want to pass the lists into a method to determine if one contains the elements of another. Right now it only returns false when I know there is a real anagram present.
Could someone look at my code and help me figure it out? Also, how would I modify this to determine if user input contained multi-word anagrams?
My algorithm works by taking in the two lists and alphabetizing the letters in each word. I'd read about this method in another post and decided to go with it - it remains a work in progress. Here is my code:
public class AnagramSolver1 {
public static void main(String[] args) throws IOException {
//Scanner/Reader
Scanner scan = new Scanner(System.in);
BufferedReader in = new BufferedReader(new FileReader("src/dictionary.txt"));
//Lists to contain unsorted dictionary and input and after alphabetical sort
List<String> dictionary = new ArrayList<String>();
List<char[]> dictionarySort = new ArrayList<char[]>();
List<String> inputList = new ArrayList<String>();
List<char[]> inputSort = new ArrayList<char[]>();
String line = null;
//read in dictionary then sort alphabetically////
while (null!=(line=in.readLine()))
{
dictionary.add(line);
}
in.close();
dictionarySort = sortList(dictionary);
//print statement
/*
for(int i = 0; i < dictionarySort.size(); i++){
System.out.println(dictionarySort.get(i));
}*/
//User input, scan in then sort alphabetically////
System.out.println("Enter Word: ");
String input = scan.next();
inputList.add(input);
inputSort = sortList(inputList);
//print statement
/*
for(int i = 0; i < inputSort.size(); i++){
System.out.println(inputSort.get(i));
}*/
//determine if user input is an angram of any dictionary word
boolean isAnagram = isAnagram(dictionarySort, inputSort);
System.out.println(isAnagram);
}
//sort a string into a char array
public static List<char[]> sortList (List<String>sort){
List<char[]> sortList = new ArrayList<char[]>();
char[] letterSort;
for (int i = 0; i < sort.size(); i++) {
letterSort = sort.get(i).toCharArray();
Arrays.sort(letterSort);
sortList.add(letterSort);
}
return sortList;
}
//Determines if User input is an Anagram or not.
public static boolean isAnagram (List<char[]>dictionarySort, List<char[]>inputSort){
for (char[] c : dictionarySort) {
if (inputSort.contains(c)) {
return true;
}
}
return false;
}
}
There's a major bug here:
for (char[] c : dictionarySort) {
if (inputSort.contains(c)) { // BUG!
This won't work like you think it will. This tests if the exact same char[] object is contained in the list; it does not test if a char array that has the same characters is there.
To work the way you intend, don't store char[], store Strings.
To turn a char[] into a String, do this:
char[] c;
String s = new String(s);
Once you have sorted your chars in an array, turn the char array into a String and store that in your lists. It means that all Lists should be lists of List<String>.
If you want to determine if one word is an anagram of another, sort the letters of both words and the resulting strings must be equal if the words are anagrams.
Try this:
When loading your dictionary, sort the letters of each word. Store the sorted value as well as the dictionary value. Consider storing the dictionary words in a hash map that uses the sorted value as the key and has multiple words as the value.
Sort the letters of the user input.
Search the dictionary (possibly the map) using the sorted user input.
When displaying anagrams from your dictionary, be sure to remove the user input from the list of anagrams (blam is not an anagram of blam).
There are two ways (that I know) to put multiple values in a HashMap.
Store a List as the value and add to it as you read the dictionary.
Use a MultiMap (google has some available; I think the project is guava).
Your problem is that the contains from the list interface implements equals(), in the case of arrays what is being compared is the memory address of the two char[]'s. What you need to do is:
Option 1) Get your program to compare with the elements in dictionary against input using Arrays.equals(char[] one, char[] two), that will compare the contents.
Option 2) Instead of comparing the char[] get it to a point where you are comparing strings, using the string's equals() method which will also compare the contents.

Breaking up a string in Java into a string array

I've researched this subject thoroughly, including questions and answers on this website....
this is my basic code:
import java.util.Scanner;
class StringSplit {
public static void main(String[] args)
{
System.out.println("Enter String");
Scanner io = new Scanner(System.in);
String input = io.next();
String[] keywords = input.split(" ");
System.out.println("keywords" + keywords);
}
and my objective is to be able to input a string like "hello, world, how, are, you, today," and have the program break up this single string into an array of strings like "[hello, world, how, are, you, today]...
But whenever i compile this code, i get this output:
"keywords = [Ljava.lang.String;#43ef9157"
could anyone suggest a way for the array to be outputted in the way i require??
Sure:
System.out.println("keywords: " + Arrays.toString(keywords));
It's not the splitting that's causing you the problem (although it may not be doing what you want) - it's the fact that arrays don't override toString.
You could try using Java's String.Split:
Just give it a regular expression that will match one (or more) of the delimeters you want, and put your output into an array.
As for output, use a for loop or foreach look to go over the elements of your array and print them.
The reason you're getting the output you're getting now is that the ToString() method of the array doesn't print the array contents (as it would in, say, Python) but prints the type of the object and its address.
This code should work:
String inputString = new String("hello, world, how, are, you, today");
Scanner scn = new Scanner(inputString);
scn.useDelimiter(",");
ArrayList<String> words = new ArrayList<String>();
while (scn.hasNext()) {
words.add(scn.next());
}
//To convert ArrayList to array
String[] keywords = new String[words.size()];
for (int i=0; i<words.size(); ++i) {
keywords[i] = words.get(i);
}
The useDelimiter function uses the comma to separate the words. Hope this helps!

Read multiple lines from console and store it in array list in Java?

Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}

Categories

Resources