Any idea why this scanner read next won't work - java

I am trying to make an Array that starts at an initial size, can have entries added to it. (I have to use an Array). To print the Array I have to following code :
public String printDirectory() {
int x = 0;
String print = String.format("%-15s" + "%-15s" + "%4s" + "\n", "Surname" , "Initials" , "Number");
// Sorts the array into alphabetical order
// Arrays.sort(Array);
while ( x < count ){
Scanner sc = new Scanner(Array[x]).useDelimiter("\\t");
secondName[x] = sc.next();
initials[x] = sc.next();
extension[x] = sc.next();
x++;
}
x = 0;
while ( x < count){
print += String.format("%-15s" + "%-15s" + "%4S" + "\n", secondName[x] , initials[x] , extension[x]);
x++;
}
return print + "" + Array.length;
}
Please ignore the extra Array.length, on the return statement.
Anyways this is working fine, firstly the Array reads a file which is formated like NameInitialsnumber on each line.
So I tried making a newEntry method and it causes problems when I want to print the Array. When I add a new entry, if the Array is too small, it will make the array bigger and add the entry. I made methods to make sure this worked and it does work. The following code for this method is:
public void newEntry(String surname, String in, String ext) {
if (count == Array.length) {
String entry = surname + "\t" + in + "\t" + ext;
int x = Array.length + 1;
String[] tempArray = new String[x];
System.arraycopy(Array, 0, tempArray, 0, Array.length);
Array = tempArray;
Array[count] = entry;
Arrays.sort(Array);
} else {
String entry = surname + "\t" + in + "\t" + ext;
Array[count] = entry;
Arrays.sort(Array);
}
count++;
}
The problem is when I then call the printDirectory method it has problems with sc.next(). The error message is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ArrayDirectory.printDirectory(ArrayDirectory.java:106)
at ArrayDirectory.main(ArrayDirectory.java:165)
Im really new to coding and im not sure what is wrong. I know its something wrong with the new entry but im not sure what. Really grateful for any help. Thanks.

It seems that your other arrays secondName, initials, and extension are not large enough.
You need to make them bigger as well. Or even better, when you think a bit about it you will recognize that you do not need them at all.

Related

I want to print a formatted array in java

I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342
Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.
You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}
If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}
replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.

Finding Largest String in ArrayList

// Im trying to find the largest String in my ArrayList and print it out and also to include what index the largest element resides at and to print that to screen too. Im just wondering where Im going wrong.
Thanks.
import java.util.Scanner;
import java.util.ArrayList;
public class ArraylistString
{
public static void main(String [] args)
{
// Instance of Scanner class
Scanner keyboardIn = new Scanner(System.in);
// Declare an array list of Strings
ArrayList<String> Str = new ArrayList<>();
// Add names to ArrayList
Str.add("Jim Bob");
Str.add("Bobby Jones");
Str.add("Rob Stiles");
int largestString = Str.size();
int index = 0;
// Use for loop to print out elements from ArrayList
for(int i = 0; i < Str.size(); i++)
{ // Test which String is the largest
if(Str[i].size() > largestString)
{
largestString = Str[i].size();
index = i;
}
}
// Output largest String and index it was found at
System.out.println("Index " + index + " "+ Str[index] + " " + "is the largest and is size " + largestString);
}
}
You can also use java.util.Collections.max or the Stream version:
Java 8
String max = Collections.max(strings, Comparator.comparing(String::length)); // or s -> s.length()
OR
String max = strings.stream().max(comparing(String::length)).get();
Prior Java 8
String max = Collections.max(Str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
Then
System.out.println("Index " + arr.indexOf(max) + " " + max + " " + "is the largest and is size " + max.length());
Please try these code . Here i am trying with get() to access the ArrayList elements, which is working correctly.
import java.util.Scanner;
import java.util.ArrayList;
class ArraylistString
{
public static void main(String args[])
{
ArrayList<String> Str = new ArrayList<String>();
Str.add("Jim Bob");
Str.add("Bobby Jones");
Str.add("Rob Stiles");
int largestString = Str.get(0).length();
int index = 0;
for(int i = 0; i < Str.size(); i++)
{
if(Str.get(i).length() > largestString)
{
largestString = Str.get(i).length();
index = i;
}
}
System.out.println("Index " + index + " "+ Str.get(index) + " " + "is the largest and is size " + largestString);
}
}
You have the correct idea, but wrong syntax. In Java, only arrays support the [] syntax. An ArrayList isn't an array, it's a class that implements the List interface, and you should use the get method to access its members. Similarly, a String doesn't have a size() method, it has a length() method.
I would set your largestString variable to your first String that you add:
int largestString = Str.get(0).length();
Then you should use the following to check for the largest String:
if(Str.get(i).length() > largestString) {
largestString = Str.get(i).length();
index = i;
}
You cannot index into an ArrayList with [] as you were trying to do.
I would also suggest better variable names. If I saw Str as a variable I would think it was a String. Maybe try strList or something like that.
From Java-8 and onwards:
List<Integer> numList = Arrays.stream(Str).map(String::length).collect(Collectors.toList());
Integer m = numList.stream().mapToInt(i->i).max().orElse(4000); //get strings with their length
int k = numList.indexOf(m); //index of String with Maximum Length
System.out.println(Str.get(k)); //get your longest string
Using Java 8:
Optional<String> op = Str.stream().sorted((e1,e2)-> e1.length() > e2.length() ? -1 :1).findFirst();
What are you getting as output?
also, the line
int largestString = Str.size()
is setting largestString as the number of elements in the array Str so that may cause errors. I would set it to 0 or even -1 as a baseline, or maybe Str[0].size() so that you can start your for loop with your first element as your baseline.
EDIT:
I didn't even realize this was Java so like what people are saying, you cannot use the [] operator as you can in most languages and you should use string.length() not str.size()

Java array --> string, but .equals() not working (Or: is there an easier way to do this?)

I'm working on a program which takes in a file with the name of an item of produce, its type (Broccoli, Vegetable), and then another item and its type on a different line. It randomly takes 3 items and puts them in a "boxOfProduce" array. I turn that into a string separated by commas, and then that into a different list. I look at the items at indexes 1,3,5 to see if its a fruit or a vegetable and increase the according count.
But the count is staying at 0 and not increasing. What could I be doing wrong? Or is there an easier was to do this?
Random random = new Random();
String firstProduceType = produce[random.nextInt(size)];
String secondProduceType = produce[random.nextInt(size)];
String thirdProduceType = produce[random.nextInt(size)];
BoxOfProduce boxOfProduce = new BoxOfProduce(firstProduceType, secondProduceType, thirdProduceType);
String produceString = firstProduceType + ", " + secondProduceType + ", " + thirdProduceType;
String[] produceStringArray = produceString.split(",");
int fruitCount = 0;
int vegetableCount = 0;
System.out.println(produceStringArray);
if (produceStringArray[1].trim().equals("Fruit")) {
fruitCount += 1;
}
else if (produceStringArray[1].trim().equals("Vegetable")) {
vegetableCount += 1;
}
if (produceStringArray[3].trim().equals("Fruit")) {
fruitCount += 1;
}
else if (produceStringArray[3].trim().equals("Vegetable")) {
vegetableCount += 1;
}
if (produceStringArray[5].trim().equals("Fruit")){
fruitCount += 1;
}
else if (produceStringArray[5].trim().equals("Vegetable")) {
vegetableCount += 1;
}
EDIT: firstProduceType, secondProduceType, and thirdProduceType are entirely random, so they'll be (item, type).
Try lowercasing everything as well. Equals works if strings are equal
Also you can use
String[] produceStringArray = {firstProduceType, ...};
Should be more safe
Also I think it should be produce[random.nextInt(size-1)];
As indexing starts from 0

Weird IndexOutofBoundsException?

why is there an IndexOutofBoundsException? It seems as if there is no variable that index may be out of bounds. This program is supposed to convert patterns. Could this have something to do with how I read my file? Thanks.
static int checkNestedParenFront(String line){
int count=0;
for(int i=0;i<line.length();i++ ){
if(line.charAt(i)=='(')
count++;
if(line.charAt(i)==')'&&count==0)
return i;
if(line.charAt(i)==')')
count--;
}
return 0;
}
String line = new String(Files.readAllBytes(Paths.get("new.txt")));
PrintWriter writer = new PrintWriter("old.txt");
while(line.contains("F_4")){
while(line.contains("$F_4$")) {
line=line.replace("$F_4$", "$\\AppellFiv");
}
int posAppell = line.indexOf("F_4");
int posSemi = line.indexOf(';', posAppell);
posSemi = line.indexOf(';', posSemi);
int posComma = line.indexOf(',', posSemi);
String check = line.substring(posComma+1);
int i = checkNestedParenFront(check);
String lastAppel = line.substring(posComma, i);
String beforeAppel=line.substring(0, posComma);
String afterAppel = line.substring(i+1);
line = line.replaceAll("F_4[^(]*\\(([^,]+),([^;]+);([^,]+),([^;]+);([^,]+),", "\\AppellFiv#{$1}{$2}{$3}{$4}{$5}");
line = beforeAppel + "{" + lastAppel + "}" + afterAppel;
}
Your problem is that when you call checkNestedParenFront(check), you're returning the count in check of that last parenthesis, which is not the same as the count in line, because check starts partway through line.
Then when you call line.substring(posComma, i), you have i less than posComma, and that causes the exception.
I think you mean to have line.substring(posComma, posComma + i + 1) - but I'm not quite sure about the +1, since it's not clear exactly what you're trying to achieve.

Counting occurrences in a string array and deleting the repeats using java

i'm having trouble with a code. I have read words from a text file into a String array, removed the periods and commas. Now i need to check the number of occurrences of each word. I managed to do that as well. However, my output contains all the words in the file, and the occurrences.
Like this:
the 2
birds 2
are 1
going 2
north 2
north 2
Here is my code:
public static String counter(String[] wordList)
{
//String[] noRepeatString = null ;
//int[] countArr = null ;
for (int i = 0; i < wordList.length; i++)
{
int count = 1;
for(int j = 0; j < wordList.length; j++)
{
if(i != j) //to avoid comparing itself
{
if (wordList[i].compareTo(wordList[j]) == 0)
{
count++;
//noRepeatString[i] = wordList[i];
//countArr[i] = count;
}
}
}
System.out.println (wordList[i] + " " + count);
}
return null;
I need to figure out 1) to get the count value into an array.. 2) to delete the repetitions.
As seen in the commenting, i tried to use a countArr[] and a noRepeatString[], in hopes of doing that.. but i had a NullPointerException.
Any thought on this matter will be much appreciated :)
I would first convert the array into a list because they are easier to operate on than arrays.
List<String> list = Arrays.asList(wordsList);
Then you should create a copy of that list (you'll se in a second why):
ArrayList<String> listTwo = new ArrayList<String>(list);
Now you remove all the duplicates in the second list:
HashSet hs = new HashSet();
hs.addAll(listTwo);
listTwo.clear();
listTwo.addAll(hs);
Then you loop through the second list and get the frequency of that word in the first list. But first you should create another arrayList to store the results:
ArrayList<String> results = new ArrayList<String>;
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": " count;
results.add(result);
}
Finally you can output the results list:
for(String freq : results){
System.out.println(freq);}
I have not tested this code (can't do that right now). Please ask if there is a problem or it doesnÄt work. See these questions for reference:
How do I remove repeated elements from ArrayList?
One-liner to count number of occurrences of String in a String[] in Java?
How do I clone a generic List in Java?
some syntax issues in your code but works fine
ArrayList<String> results = new ArrayList<String>();
for(String word : listTwo){
int count = Collections.frequency(list, word);
String result = word +": "+ count;
results.add(result);
}

Categories