How to re-cast a java array - java

So i'm trying to read some user input which is then checked against two arrays of strings, then if the user input equals something in either of the arrays i want to put the user input into a new array, but when i go to print the new array which should contain the user input it prints that every value in the array is null
String[] VegiFruit = {"Apples", "Lettuce", "Broccoli"};
String[] Meats = {"Ground beef", "Hambuger"};
String[] Input = new String[20];
String[] InputGreen = new String[20];
String done = "done";
Scanner USER_IN = new Scanner(System.in);
Methods Use = new Methods(); //This is another class I have that just makes printing blank lines and borders look nicer
Use.border();
System.out.println("Enter Item name then follow instructions.");
Use.space();
for(int i = 0; i < 21; i++)
{
System.out.print(i+": ");
Input[i] = USER_IN.nextLine();
if(Arrays.asList(VegiFruit).contains(Input))
{
InputGreen[i] = Input[i];
System.out.println(InputGreen[i]); //Prints null for every value
}
}
So am I doing something wrong with the logic? or is it something else?

if(Arrays.asList(VegiFruit).contains(Input))
This line is totally wrong because you are comparing the object(Here Input is an parameter value of .contains method, it is an object) with a List of element, here element of the list is a String value.
So change the code like below,
if (Arrays.asList(VegiFruit).contains(Input[i])) {
InputGreen[i] = Input[i];
System.out.println(InputGreen[i]); //Now it is print the corresponding value.
}

Related

Array validation through a while loop

I am doing "Rock,Paper,Scissors" game and I want to check if the input matches with any arrays, for now I have this code and it works perfect:
String[] rockArray = {"Rock","rock","1"},
paperArray = {"Paper","paper","2"},
scissorsArray = {"Scissors","scissors","3"};
String[][] answersArray = {rockArray, paperArray, scissorsArray};
//Scanner
Scanner scan = new Scanner(System.in);
// Input
System.out.print("\nRock, Paper or Scissors? -> ");
String answer = scan.next();
// Checking if the input contains the right values
while(!Arrays.asList(answerRock).contains(answer) &&
!Arrays.asList(answerPaper).contains(answer) &&
!Arrays.asList(answerScissors).contains(answer)) {
System.out.print("Try again: ");
answer = scan.next();
}
But I want to make it simple and here is my idea but for some reason it doesn't work:
// Here is my arrays
String[] rockArray = {"Rock","rock","1"},
paperArray = {"Paper","paper","2"},
scissorsArray = {"Scissors","scissors","3"};
String[][] globalArray = {rockArray, paperArray, scissorsArray};
// Input
System.out.print("\nRock, Paper or Scissors? -> ");
String answer = scan.next();
//Validation
while(!Arrays.asList(globalArray).contains(answer) {
System.out.println("Try again: ");
answer = scan.next();
}
Thank you very much!
String[][] globalArray = {rockArray, paperArray, scissorsArray};
...
Arrays.asList(globalArray)
This call to Arrays.asList() will create list with 3 elements, the 3 array and not a list with the content of the arrays. When you then use contains to search for the element, you will always get false because answer will never be on of the arrays (how would it, it's a String not an array).
I suggest you do something like this:
List<String> allAnswers = Arrays.asList(rockArray);
allAnswers.addAll(Arrays.asList(paperArray));
allAnswers.addAll(Arrays.asList(scissorsArray));
...
while(!allAnswers.contains(answer)) {
...
This also saves you from calling Arrays.asList() over and over again which improves performance.
!Arrays.asList(globalArray).contains(answer) doesn't work because the Arrays.asList(...) method will output a List<String[]> not List<String>.
If you really want to use asList(...) you have to input an String[] allPossibleInputString
Your second code snippet does not work because you can't do something like this !Arrays.asList(globalArray).contains(answer).
One solution is to copy the contents of the three array into your global array like this:
String[] rockArray = {"Rock","rock","1"},
paperArray = {"Paper","paper","2"},
scissorsArray = {"Scissors","scissors","3"};
String[] globalArray = new String[9];
/* Copy Contents To Global Array */
System.arraycopy(rockArray, 0, globalArray, 0, 3);
System.arraycopy(paperArray, 0, globalArray, 3, 3);
System.arraycopy(scissorsArray, 0, globalArray, 6, 3);
Now you can do this:
while(!Arrays.asList(globalArray).contains(answer)) {
System.out.println("Try again: ");
answer = scan.nextLine();
}

Java file to 2D array

I'm trying to create a 2D array from a .txt file, where the .txt file looks something like this:
xxxx
xxxx
xxxx
xxxx
or something like this:
xxx
xxx
xxx
So I need to handle multiple sizes of a 2D array (Note: Each 2D array will not always be equal x and y dimensions). Is there anyway to initialize the array, or get the number of characters/letters/numbers per line and number of columns? I do not want to use a general statement, something like:
String[][] myArray = new Array[100][100];
And then would filling the array using filewriter and scanner classes look like this?
File f = new File(filename);
Scanner input = new Scanner(f);
for(int i = 0; i < myArray[0][].length; i++){
for(int j = 0; j < myArray[][0].length, j++){
myArray[i][j] = input.nextLine();
}
}
You have several choices as I see it:
Iterate through the file twice, the first time getting the array parameters, or
Iterate through it once, but fill up a List<List<SomeType>> possibly instantiating your Lists as ArrayLists. The latter will give you much greater flexibility in the short and long run.
(per MadProgrammer) The third option is to re-structure the file to provide the meta data required to make decisions about the size of the array.
For example, using your code,
File f = new File(filename);
Scanner input = new Scanner(f);
List<List<String>> nestedLists = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<String> innerList = new ArrayList<>();
Scanner innerScanner = new Scanner(line);
while (innerScanner.hasNext()) {
innerList.add(innerScanner.next());
}
nestedLists.add(innerList);
innerScanner.close();
}
input.close();
Java Matrix can have each line (which is an array) by your size desicion.
You can use: ArrayUtils.add(char[] array, char element) //static method
But before that, you need to check what it the file lines length
Either this, you can also use ArrayList> as a collection which is holding your data

Cannot assign a substring from a file to my array

I have a file with 50 states and capitals in this format:
Alabama,Tallahasee,
Wisconsin,Madison,
........
I am trying to assign the states and capitals to seperate arrays and I am having a problem with the for loop. My code is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class StatesAndCapitals {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream is = new FileInputStream("capitals.txt");
Scanner input = new Scanner(is);
String[] states = new String[50];
String[] capitals = new String[50];
for (int i = 0; i < states.length; i++){
int a = states[i].lastIndexOf(",");
String states1 = states[i].substring(0, a);
states[i] = states1;
input.nextLine();
}//end for loop
System.out.println(states);
}
}
The error I am getting is
Exception in thread "main" java.lang.NullPointerException
at StatesAndCapitals.main(StatesAndCapitals.java:12)
any help would be appreciated.
When you do
states[i].lastIndexOf(",");
you're analyzing the content of states[i]. But that is your destination array, and not the source containing the text. The source is what is returned from input.nextLine(), which should be the first thing you should do at each iteration:
for (int i = 0; i < states.length; i++){
String currentLine = input.nextLine();
// now extract the data from current line, and store them in the arrays.
}
for (int i = 0; i < states.length; i++){
int a = states[i].lastIndexOf(",");
String states1 = states[i].substring(0, a);
states[i] = states1;
input.nextLine();
}//end for loop
This whole loop is backwards. When you first enter at i = 0 you attempt to take a substring of your states array which has never seen any sort of assignment. You then work on that substring within the loop before ending with input.nextLine(); which is never actually used.
The input variable, when used correctly will actually hold data from the file you open and will allow you to manipulate strings with substring. You need to reorder and fix your loop.
The default value for an object is null.
String[] states = new String[50]; //<-- you declare an array that can holds 50 Strings but they're actually null if you don't initialize them.
So when doing states[i].lastIndexOf(","); it throws a NPE.
Same behavior for your capitals array.
Read the Default Values section.
You need to store the datas in a String variable first :
for (int i = 0; i < states.length; i++){
String data = input.nextLine();
// Now process with data and add corresponding parts to states and capitals array
}//end for loop
And then process on this String and add it to the corresponding array.
Not that if you don't have enough lines in your file (less than 50), it will throw java.util.NoSuchElementException because no more lines are found.
You can add this condition to the loop : for (int i = 0; i < states.length && input.hasNextLine(); i++){
When you will get this working correctly, I suggest you to deal with a List.

Scanning from a certain, random line of a file in java?

I have a .txt file that lists integers in groups like so:
20,15,10,1,2
7,8,9,22,23
11,12,13,9,14
and I want to read in one of those groups randomly and store the integers of that group into an array. How would I go about doing this? Every group has one line of five integers seperated by commas. The only way I could think of doing this is by incrementing a variable in a while loop that would give me the number of lines and then somehow read from one of those lines that is chosen randomly, but I'm not sure how it would read from only one of those lines randomly. Here's the code that I could come up with to sort of explain what I'm thinking:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
while (filescan.hasNextLine())
{
line++;
}
Random r = new Random(line);
Now what do I do to make it scan line r and place all of the integers read on line r into a 1-d array?
There is an old answer in StackOverflow about choosing a line randomly. By using the choose() method you can randomly get any line. I take no credit of the answer. If you like my answer upvote the original answer.
String[] numberLine = choose(new File("Coords.txt")).split(",");
int[] numbers = new int[5];
for(int i = 0; i < 5; i++)
numbers[i] = Integer.parseInt(numberLine[i]);
I'm assuming you know how to parse the line and get the integers out (Integer.parseInt, perhaps with a regular expression). If you're sing a scanner, you can specify that in your constructor.
Keep the contents of each line, and use that:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
List<String> content = new ArrayList<String>(); // new
while (filescan.hasNextLine())
{
content.add(filescan.next()); // new
line++;
}
Random r = new Random(line);
String numbers = content.get(r.nextInt(content.size()); // new
// Get numbers out of "numbers"
Read lines one by one from the file, store them in a list and generate a random number from the list's size and use it to get the random line.
public static void main(String[] args) throws Exception {
List<String> aList = new ArrayList<String>();
Scanner filescan = new Scanner(new File("Coords.txt"));
while (filescan.hasNextLine()) {
String nxtLn = filescan.nextLine();
//there can be empty lines in your file, ignore them
if (!nxtLn.isEmpty()) {
//add lines to the list
aList.add(nxtLn);
}
}
System.out.println();
Random r = new Random();
int randomIndex=r.nextInt(aList.size());
//get the random line
String line=aList.get(randomIndex);
//make 1 d array
//...
}

java store a string in a char array

In Java, How can I store a string in an array? For example:
//pseudocode:
name = ayo
string index [1] = a
string index [2] = y
string index [3] = o
Then how can I get the length of the string?
// this code doesn't work
String[] timestamp = new String[40]; String name;
System.out.println("Pls enter a name and surname");
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
name=timestamp.substring(0, 20);
If you want a char array to hold each character of the string at every (or almost every index), then you could do this:
char[] tmp = new char[length];
for (int i = 0; i < length; i++) {
tmp[i] = name.charAt(i);
}
Where length is from 0 to name.length.
This code doesn't compile because the substring method can only be called on a String, not a String array if I'm not mistaken. In the code above, timestamp is declared as a String array with 40 indexes.
Also in this code, you're asking for input from a user and assigning it to name in this line:
name = sc.nextLine();
and then you are trying to replace what the user just typed with what is stored in timestamp on the next line which is nothing, and would erase whatever was stored in name:
name = timestamp.substring(0,20);
And again that wouldn't work anyway because timestamp is an array of 40 strings instead of one specific string. In order to call substring it has to be just one specific string.
I know that probably doesn't help much with what you're trying to do, but hopefully it helps you understand why this isn't working.
If you can reply with what you're trying to do with a specific example I can help direct you further. For example, let's say you wanted a user to type their name, "John Smith" and then you wanted to seperate that into a first and last name in two different String variables or a String array. The more specific you can be with what you want to do the better. Good luck :)
BEGIN EDIT
Ok here are a few things you might want to try if I understand what you're doing correctly.
//Since each index will only be holding one character,
//it makes sense to use char array instead of a string array.
//This next line creates a char array with 40 empty indexes.
char[] timestamp = new char[40];
//The variable name to store user input as a string.
String name;
//message to user to input name
System.out.println("Pls enter a name and surname");
//Create a scanner to get input from keyboard, and store user input in the name variable
Scanner sc = new Scanner(System.in);
name = sc.nextLine();
//if you wanted the length of the char array to be the same
//as the characters in name, it would make more sense to declare it here like this
//instead of declaring it above.
char[] timestamp = new char[name.length()];
//For loop, loops through each character in the string and stores in
//indexes of timestamp char array.
for(int i=0; i<name.length;i++)
{
timestamp[i] = name.charAt(i);
}
The other thing you could do if you wanted to just seperate the first and last name would be to split it like this.
String[] seperateName = name.split(" ");
That line will split the string when it finds a space and put it in the index in the seperateName array. So if name was "John Smith", sperateName[0] = John and seperateName[1] = Smith.
Are you looking for a char[]? You can convert a character array to a String using String.copyValueOf(char[]).
Java, substring an array:
Use Arrays.copyOfRange:
public static <T> T[] copyOfRange(T[] original,
int from,
int to)
For example:
import java.util.*;
public class Main{
public static void main(String args[]){
String[] words = new String[3];
words[0] = "rico";
words[1] = "skipper";
words[2] = "kowalski";
for(String word : words){
System.out.println(word);
}
System.out.println("---");
words = Arrays.copyOfRange(words, 1, words.length);
for(String word : words){
System.out.println(word);
}
}
}
Prints:
rico
skipper
kowalski
---
skipper
kowalski
Another stackoverflow post going into more details:
https://stackoverflow.com/a/6597591/445131

Categories