Read an element of an array whilst containing various data - java

I am currently seeking for a bit of help with the use of arrays. Quite a newbie on the Java language, so excuse the poor etiquette towards the programming format and I forwardly thank for any answers provided.
My current quarrel with the Array is how to fetch data from any array element. Currently I use the method System.out.println(Arrays.toString(listarray)) but the problem with this method is that it's not necessarily User friendly and it can't be formatted (to my little knowledge). So I'd like to ask help on how to fetch data from an element of an array and put it in a way so its readable by any given user.
Here is the code I'm utilizing:
import java.util.Arrays;
import java.util.Scanner;
public class principal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Array Example");
String[] listarray = new String[10];
int i = 0;
byte op;
do {
System.out.println("Select your option:");
System.out.println("1-Add");
System.out.println("2-Check");
System.out.println("3-Change");
op = input.nextByte();
switch (op) {
case 1:
input.nextLine();
System.out.println("First String:");
String a1 = input.nextLine();
System.out.println("Second String:");
String a2 = input.nextLine();
System.out.println("Third String:");
String a3 = input.nextLine();
System.out.println("(" + (i + 1) + "/10)");
listarray[i] = a1 + a2 + a3;
i++;
break;
case 2:
System.out.println(Arrays.toString(listarray));
break;
}
}while(op != 9);
}
}
While the code does work, I'd like to know how to format the data, and from a single element, not every element. Or even if I can. Thanks and I appreciate the time spent reading this question.

You have two questions:
How do you reference an array element?
How do you format output?
When you declare an array like
String[10] names;
You have an array that can hold 10 strings, numbered 0 to 9. To reference the fifth element (remembering that array indices start at 0), you would use
names[4]
You can do various things with a reference. If you put it on the right side of an equals sign, then you are assigning the value at that element to something else.
currentName = names[4];
If you put it on the left side, you are assigning something to that element.
names[4] = "Michael";
And if you put it in a println statement, it will output the value to wherever the println statement is putting things at that time, usually the console:
System.out.println(names[4]);
So much for references. And, incidentally, that's what it is called -- you are referencing the 5th element of the array, or you are referencing the indicated element of the array. You can also put the number in a variable:
var i = 4;
System.out.println[i];
Note that most of these uses of the reference assume there is something IN that element of the array. Until something is assigned there, the element is a null.
To format, I recommend looking (carefully) into the Format / Formatter classes and choosing some simple things to do what you want. As an example, you could have:
String formatString = "The name is currently %s.";
String outputString = String.format(formatString, names[i]);
and String's format method will substitute whatever is in names[i] for the %s in the format. There are also formats for ints, doubles, and dates.
For more info, see the Oracle Tutorial on arrays and on manipulating Strings.
Hope that helps

If you want to traverse the Array that is how you can do it:-
for(int i = 0; i < listArray.length; i++) {
System.out.println(listArray[i]);
}
or
for (String s : listArray) {
System.out.println(s);
}

Related

Can't figure out why I am getting null values

The program is supposed to print out the amount of times each name has been selected (this is indicated by number of asterisks (*). I have most of the code working but for some reason the output contains two null values for each name and I am not sure how to fix the problem. Also if you have the time, I'm also struggling to find out which name has the most amount of asterisks. Here's an example output:
1: nullnull************************ Conner
2: nullnull********************************** John
etc...
(it does this for all 10 names)
public class RandomStudentsLab {
public static void main(String[] args){
//create an array with 10 students
String [] StudentList = new String[10];
String [] StarString = new String[10];
String [] FinalString = new String[10];
//add 10 names to the student list
StudentList[0] = "Conner";
StudentList[1] = "John";
StudentList[2] = "Alex";
StudentList[3] = "Robert";
StudentList[4] = "James";
StudentList[5] = "Carl";
StudentList[6] = "Sarah";
StudentList[7] = "Bob";
StudentList[8] = "Ethan";
StudentList[9] = "Chris";
//loop 250 times selecting each student randomly
for(int i=0; i<250; i++){
int randomNum = (int)((Math.random()*10));
for(int x=0; x<10; x++){
if(randomNum == x){
StarString[x] += "*";
}
}
}
for(int z=0; z<10; z++){
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
}
}
}
Elements in FinalString and StarString arrays are still not initialized. So with += operator its calling toString on the null element and prefix "null" to each string.
As mentioned by Karthik in his answer you never initialized (as in you never assigned values) the FinalString array. That is what is causing your error.
You can easily tell since your System.out.println() is printing:
Number : nullnull Stars Name
So clearly your issue is with FinalString, it is the only variable not printing correctly.
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
You are making the same mistake with the StarString array. You are lucky enough to get away with it in this case since you end up adding variables to StarString in your loop.
However, NOT initialising ANY variable is >>horrible<< practice. You never know what was previously stored in memory, this could lead to your variables being assigned some 'alien' data that was leftover on the memory by some other program. Secondly, and this is the issue in your question, if you forget to initialise you can run into null errors and such.
So as a matter of good coding practice always initialise your variables to something. Even if you are using the variable two lines later - it doesn't matter. When you create your variable assign it a value:
If it's an integer then 0 or -1. It's better if it's a value that won't occur in your program, so if you have an error in your code you can spot it easily because your integer will be -1 instead of x y z.
If it's a string then name it 'banana' or 'peanuts' or whatever.
If it's an object make sure you initialise all of the attributes
And so on...
P.S. Not sure if I came accross as harsh, but it's absolutely not my intention. Good coding practices are simply important and will be extremely helpful in the future.
Best of luck!
EDIT:
Little update to reflect your comment on another answer.
When you create FinalString here String [] FinalString = new String[10]; your are not assigning any values to it, unlike what you did with the names.
So when your code gets to the final for loop here:
for(int z=0; z<10; z++){
System.out.println((z+1)+": "+(FinalString[z] += StarString[z] + " "+StudentList[z]));
}
}
}
And you try to do a System.out.println() for FinalString[z], well FinalString[z] still does not have a value. At no point in your code did you write
FinalString[0] = "Banana";
So obviously it will print null instead.

Finding the index of each character in a substring

I feel like my logic is decent here; I don't feel like I'm completely lost. However, I do know what exactly I'm doing wrong. I can always find the index of the start of the substring, but I can never find the full count (ex. 3,4,5,6) of the index of whatever word the user enters as the substring.
I have been struggling with this for about a week trying to figure out how to do it on my own, I can't get it right.
import java.util.Scanner;
public class midterm
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
String simplePhrase;
String portionPhrase;
int portionIndex;
int portionCount;
int portionIndexTotal;
System.out.println("Enter a simple phrase:");
simplePhrase = keyboard.nextLine();
int phraseLength = simplePhrase.length();
System.out.println("Phrase length:" +phraseLength);
System.out.println("Enter a portion of previous phrase:");
portionPhrase = keyboard.nextLine();
String portionPhraseSub = simplePhrase.substring(portionPhrase);
portionIndex = simplePhrase.indexOf(portionPhraseSub);
for (portionIndex; portionIndex <= portionPhrase; portionIndex++)
{
System.out.println("Portion phrase index:"+portionIndex);
}
}
}
I'm still confused on what you want. There are just two simple things to know and you seem to be making this more complicated than it needs to be.
To get the index of a single character, such as "c" in the word "acorn", you would do this:
String s = "acorn";
int cIndex = s.indexOf("c");
System.out.println("The index of c is: " + cIndex);
If you want to see if the string contains a chunk, you use the exact same method. So if we are looking at the word "acorn" again and you want to see where "orn" happens, you'd do this:
String s = "acorn";
int ornIndex = s.indexOf("orn");
System.out.println("The index of orn is: " + ornIndex);
Remember that indexes start from 0 in java, so the index of "a" in "acorn" is 0, of "c" is 1, of "o" is 2, and so on.
I hope that helps. Good luck :)
EDIT: You just commented this:
"I guess, my question is one i get my code to compile, How would I go about counting every single letter of my substring?"
I'll answer that as best as I can, though again, that still is a confusing question.
What do you even mean by count" every letter? If you want to break your word into individual letters, you can do something like this:
String s = "acorn";
char[] characters = new char[s.length()-1];
for(int i = 0; i < s.length() - 1; i++) {
char[i] = s.charAt(i);
}
But I have no clue why you'd want to do that...you can always access any character in a string at a given index with STRING.charAt(index), or if you want to have a String result, STRING.substring(index, index+1)

Java - Ideas to turn strings into numbers (RegEx/Parsing/etc.)?

I'm reading in from a file, and the input is like this:
Description (1.0,2.0) (2,7.6) (2.1,3.0)
Description2 (4,1)
...
Description_n (4,18) (8, 7.20)
I want to be able to take the numbers inside parentheses and use turn them from strings into numbers so that I can do mathematical operations of them. Right now, to simplify things, my code only reads in the first line and then splits it based on spaces:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(new File("filename.txt")));
//reader reads in the first line
String firstLine = reader.readLine();
//splits into an array of ["Description","(1.0,2.0)","(2,7.6)","(2.1,3.0)"]
String[] parts = first.split(" ");
//now I want to store 1.0, 2, and 2.1 in one array as ints and 2.0, 7.6, and 3.0 in another int array
} catch (Exception e) {
System.exit(0);
}
What are some ways I can store the numbers inside parentheses into two separate arrays of ints (see comment above)? Should I use regular expressions to somehow capture something of the form "( [1-9.] , [1-9.] )" and then pass those into another function that will then separate the first number in the pair from the second and then convert them both into integers? I'm new to regular expression parsing in Java, so I'm not sure how to implement this.
Or is there a simply, better way to do this?
This stores the numbers into Double-arrays (not two-dimensional arrays, arrays of Double objects), since some have .#. int-arrays would eliminate the post decimal part.
It uses the regex \b([\d.]+)\b to find each number within each paren-group, adding each to an ArrayList<Double>. Note that it assumes all input is perfect (nothing like (bogus,3.2). The list is then translated into an array of Double objects.
This should give you a good start towards your goal.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
<P>{#code java DoubleInParenStringsToArrays}</P>
**/
public class DoubleInParenStringsToArrays {
public static final void main(String[] ignored) {
String input = "(1.0,2.0) (2,7.6) (2.1,3.0)";
String[] inputs = input.split(" ");
//"": Dummy string, to reuse matcher
Matcher mtchrGetNums = Pattern.compile("\\b([\\d.]+)\\b").matcher("");
for(String s : inputs) {
ArrayList<Double> doubleList = new ArrayList<Double>();
mtchrGetNums.reset(s);
while(mtchrGetNums.find()) {
//TODO: Crash if it's not a number!
doubleList.add(Double.parseDouble(mtchrGetNums.group(0)));
}
Double[] doubles = doubleList.toArray(new Double[doubleList.size()]);
System.out.println(Arrays.toString(doubles));
}
}
}
Output:
[C:\java_code\]java DoubleInParenStringsToArrays
[1.0, 2.0]
[2.0, 7.6]
[2.1, 3.0]
How to parse per item:
Double.parseDouble("your string here");
As for the storing, I didnt get the pattern you want to store your values. What's the reason why you want 1.0, 2, and 2.1 in 1 array and 2.0, 7.6, and 3.0 to another?
Just do Integer.parseInt(string), or Double.parseDouble(string), then add those to the array. I'm not really 100% sure what you're asking, though.
I would use a String Tokenizer.But need more information and thought for full impl.
This is your line : "Description (1.0,2.0) (2,7.6) (2.1,3.0)"
First thing - can there be cases without parenthesis? Will there always be sets f 2,2,2 numbers ?
Do you want to take care of errors at each number or just skip the line or skip processing if there is an error (like number of numbers does not match?).
Now you need a data structure to hold numbers. You could make a class to hold each individual element in a seperate property if each number has a distinct meaning in the domain or have an array list or simple array if you want to treat them as a simple list of numbers. If a class one sample (incopmplete):
class LineItem{
}
Now to actually break up the string there are many ways to do it. Really depends on the quality of data and how you want to deal with possible errors
One way is find the first opening parenthesis( take rest of string and parse out using a String Tokenizer.
Something like:
int i = str.indexOf("(");
String s2 = str.substring(i);
StringTokenizer st = new StringTokenizer(s2, "() ,";//parenthesis, comma and space
ArrayList<Double> lineVals1 = new ArrayList<Double>();
ArrayList<Double> lineVals1 = new ArrayList<Double>();
int cnt = 0;
while(st.hasMoreTokens()){
cnt++;//use this to keep count of how many numbers you got in line and raise error if need be
String stemp = st.nextToken();
if(isNumeric(stemo)){
if(cnt % 2 == 1){
lineVals1.add(Double.parseDouble(stemp));
}else{
lineVals2.add(Double.parseDouble(stemp));
}
}else{
/raise error if not numberic
}
}
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}

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.

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