java.lang.ArrayIndexOutOfBoundsException mistake - java

I am trying to search through a file to print out scores. Here is what I have:
while (input.hasNextLine()) {
String record = input.nextLine();
String[] field = record.split(" ");
if(field[1].equals(targetState)) {
System.out.print(field[0] + ": ");
System.out.println(field[2]);
}
}
And the data in file looks like this:
2007,Alabama,252
When I ran this code, I get that java.lang.ArrayIndexOutOfBoundsException error.
I just wonder what is wrong with the code
Thanks

You need to split using comma and not space. Change this
String[] field = record.split(" ");
to
String[] field = record.split(",");
As you don’t have the spaces in your input string, so it is not getting split and hence the output array does not have multiple items, leading to ArrayIndexOutOfBoundException

Related

Unable to obtain values if for loop placed in a different line of code

I'm tasked to take the words out of a txt file and then eliminate the duplicates and print out the rest. However there seems to be something weird going on when I place the for loop used to print out the array of words that are taken from the txt file.
When I do
for (String word:arr)
{
words = word.split(" ");
for (int i = 0; i < words.length; i++)
{
// Printing the elements of String array
System.out.print(words[i] + " ");
}
}
where, arr is an array of string; filled with sentences from the text file , and words is the individual words of the text file stored in array of strings, printing the array words will give what it is supposed to,
however when I do
for (String word:arr)
{
words = word.split(" ");
}// not nested so happens seperately
for (int i = 0; i < words.length; i++)
{
// Printing the elements of String array
System.out.print(words[i] + " ");
}
I only obtain 4 words out of the hundreds that are stored in the txt file.
Can someone help explain this? Thanks in advance!
In the second case you are processing outside of the first for, and you process just the last String that is in your array. Words variable gets overwritten in each itteration. My suggestion is to learn how to debug, it will greatly help you to learn.

How do i print the the first initial of a string and the last word of a string?

How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());

Java input/output confusion

I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.

Store user input in Arraylist<String> until new line

The problem requires to input different values for each attribute.Ex:
Color Black White
Water Cool Hot Medium
Wind Strong Weak
I made ArrayList of ArrayList of String to store such thing as no. of values of each attribute is not fixed.The user inputs Black White and on hitting new line the program has to start taking values of NEXT attribute( Cool Hot Medium).The no. of attributes has been already specified.I followed some (almost related) answers here and wrote the following code:
ArrayList<ArrayList<String>> attributes = new ArrayList<ArrayList<String>>();
String input;
for(i=0; i<num_of_Attributes ;i++)
{ System.out.print(" Enter attribute no." + i+1 + " : ");
ArrayList<String> list = new ArrayList<String>();
while(! input.equals("\n"))
{
list.add(input);
input = sc.nextLine();
}
attributes.add(list);
}
The program prints "Enter Attribute 1 : " but even after new line it doesn't print "Enter attribute 2 : ".It goes into infinite loop. How can I achieve what the program requires to do? sc is my Scanner object.
You should read:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29
specifically the part that states:
This method returns the rest of the current line, excluding any line separator at the end
So, if the user inputs an empty line with only the line separator \n, you will read an empty line without such line separator.
Check while (!input.isEmpty()) or, even better, while (!input.trim().isEmpty())
As a more general rule, you can debug your program (or even just print input) to try to find out yourself what is the actual value you are checking.
As a quick-Hack you can do sth. like
for (i = 0; i < num_of_Attributes; i++) {
input = " ";
System.out.print(" Enter attribute no." + (i + 1) + " : ");
ArrayList<String> list = new ArrayList<String>();
while (!input.isEmpty()) {
list.add(input);
input = sc.readLine();
}
attributes.add(list);
}
not nice but it works. Please also watch out for calculating in String concaternation. In you code it will print 01, 11, 21 and so on. With brackets it will work.

Scanner problems in Java

I have a method that returns a scanner to a text file that has lines of input (I can't get this to display properly, but like - Hi (new line) This (\n) Is (\n) Me (\n)). Then in main, I used the scanner to count the number of lines of input there are, and then resetted the scanner. I later used the scanner to put the lines of input into an array (I don't want an ArrayList), but Java says "java.util.NoSuchElementException: No line found"...
while(scanner.hasNextLine()){
numOfStrings++;
scanner.nextLine();
}
scanner.reset();
String[] stringsOfInput = new String[numOfStrings];
for(int i = 0; i < numOfStrings; i++){
String s = scanner.nextLine(); //returns "No line found" error message
stringsOfInput[i] = s;
}
Does anyone know how to fix this so it does what it should?
The most versatile way to do this would be to add the lines into an ArrayList<String> then make that into an Array(String[] stringsOfInput = myArrayList.toArray(new String[myArrayList.size()]);)
You may want to try putting the content of the for loop within the while. That way you can get the number of strings and each string in one loop through the file.
EDIT:
Sample with ArrayList
ArrayList<String> stringsOfInput = new ArrayList<String>();
while(scanner.hasNextLine())
{
stringsOfInput.add(scanner.nextLine());
numOfStrings++;
}

Categories

Resources