Accessing indexes that may not exist Java [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}

The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {

Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code

Related

Counting number of words start with UpperCase letter in strings, java

I have tried to write a Java program that count number of words start with UpperCase in each line separately, like in a txt file, and print the line number next to the number of words start with UpperCase in that line.
I have only come out with how to count the number for a single line using:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine();
char ch;
int count = 0;
for (int i = 1; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
}
}
System.out.println("total number of words start with capital letters are :" + count);
I tried to do it on the way I want, but it keep showing me "File is empty":
FileInputStream in = new FileInputStream("io-02.txt");
Scanner inScanner = new Scanner(in);
FileOutputStream out = new FileOutputStream("io-02-out.txt");
PrintWriter pwr = new PrintWriter(out);
int linenumb=0;
String s="";
char c;
int count = 0;
inScanner.useDelimiter("");
for (int i = 1; i < s.length(); i++) {
s = " " + inScanner.nextLine().trim();
c = s.charAt(i);
if (Character.isUpperCase(c) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
} else if(s == "\n"){
if(linenumb == 0)
pwr.printf("%6s%35s%n", "Line#", "Number of Uppercase characters");
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
count = 0;
}
}
if(linenumb == 0)
System.out.println("Error: The input file is empty");
else{
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
System.out.println("The file output.txt has been created . . . ");
}
Please help.
Java 8 solution:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
final public class UppercaseWordCounter { // https://stackoverflow.com/questions/49193228/counting-number-of-words-start-with-uppercase-letter-in-strings-java
final private static File FILE_WORDS = new File("io-02.txt");
final private static File FILE_RESULTS = new File("io-02-out.txt");
public static void main(final String[] args) {
if (!FILE_WORDS.exists()) {
System.err.println("Input file does not exist: " + FILE_WORDS);
System.exit(1);
}
if (FILE_RESULTS.exists()) {
if (!FILE_RESULTS.delete()) {
System.err.println("Intended output file exists already and can't be deleted: " + FILE_RESULTS);
System.exit(2);
}
}
try (final BufferedReader br = Files.newBufferedReader(FILE_WORDS.toPath(), StandardCharsets.UTF_8);
final BufferedWriter bw = Files.newBufferedWriter(FILE_RESULTS.toPath(), StandardCharsets.UTF_8)) {
int lineCounter = 1;
String line;
while ((line = br.readLine()) != null) {
final int upperCaseWordsInThisLine = countUpperCaseWords(line);
bw.write("Line " + lineCounter + " has " + upperCaseWordsInThisLine + " upper case word" + (upperCaseWordsInThisLine == 1 ? "" : "s") + ".\n");
lineCounter++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
private static int countUpperCaseWords(final String line) {
int ret = 0;
final int length = line.length();
boolean newWord = true;
for (int i = 0; i < length; i++) {
final char c = line.charAt(i);
if (" .,;/".indexOf(c) >= 0) {
newWord = true;
} else if (newWord) {
newWord = false;
if (Character.isUpperCase(c)) {
ret++;
}
}
}
return ret;
}
}
Why don't you use a method from Files class, which is available from java 1.7
List<String> lst = Files.readAllLines(Path path, Charset cs)
then you can loop over the lst List checking your condition

How to get the nextInt after the nextInt but retain the value

My problem is instead of the fixed value of iValueNext, I want the next value on the excel sheet to run, which is 125,152,...
import java.util.*;
import java.io.*;
public class ConvertingData
{
public static void main (String [] args)
{
int i=1;
int j;
int iValue;
int iValueNext;
try
{
Scanner ifsInput = new Scanner(new File("input.csv"));
PrintStream ifsOutput = new PrintStream(new File("output.csv"));
while(ifsInput.hasNextLine())
{
String tokens[] = ifsInput.nextLine().split(",");
String Repeat = tokens[tokens.length - 1];
String Value = tokens[tokens.length - 3];
iValue = Integer.parseInt( Value );
for (i=iValue;i<=iValueNext;i++)
{
System.out.println(i+","+Repeat);
ifsOutput.println(i+","+Repeat);
}
}
ifsInput.close();
ifsOutput.close();
}
catch (FileNotFoundException sMsg)
{
System.out.println("File not found");
}
}
}
Here is part of the csv file:
89,31,31
125,1,32
152,-12,20
155,1,21
181,6,27
287,1,28
290,1,29
308,-8,21
If you need to "peek" at the next line while processing the current line, first read all the lines in:
List<String> lines = new ArrayList<String>();
while(ifsInput.hasNextLine()) {
lines.add(ifsInput.nextLine());
}
ifsInput.close();
then process the lines one by one with access to the next line:
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
String nextLine = i < lines.size() - 1 ? null : lines.get(i + 1);
String tokens[] = line.split(",");
String nextTokens[] = nextLine.split(",");
// whatever logic you need
ifsOutput.close();
}

I am working on a program that checks the spelling of a txt file using a given dictionary in java. I am not getting the right outputs

I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}

Use boolean to search duplicate

I want to use boolean to search duplicate when I need to print out a list of names. So I need to write a program to read names in a text file and print it out to console. But the compiler doesn't work in this case. I don't know why? Can you guys help me?
import java.io.*;
import java.util.*;
public class NameSorter
{
public static void main(String[] args) throws Exception
{
BufferedReader cin, fin;
cin = new BufferedReader(new InputStreamReader(System.in));
//Description
System.out.println("Programmer: Minh Nguyen");
System.out.println("Description: This program is to sort names stored in a file.");
System.out.println();
//Get input
String fileName;
System.out.print("Enter the file's name: ");
fileName = cin.readLine();
fin = new BufferedReader(new FileReader(fileName));
int nNames = 0;
String[] name = new String[8];
//initialize array elements
for(int i=0; i<name.length;i++)
{
name[i]=" ";
}
// read text file
while(fin.ready())
{
String aName = fin.readLine();
String temp = aName;
boolean check;
if(temp.compareTo(" ")>0)
{
for(int i=0; i<name.length;i++)
{
if(temp.compareToIgnoreCase(name[i])==0)
{
check = true;
break;
}
}
}
if(nNames<name.length&& check = false)
{
name[nNames++] = temp;
}
}
}
fin.close();
// Sort the names aphabetically.
for(int i=0;i<nNames; i++)
{
int j;
for(j=i+1;j<nNames; j++)
{
if(name[i].compareToIgnoreCase(name[j])>0)
{
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for(int i=0; i<name.length;i++)
System.out.println(name[i]);
}
}
Your code is :
if(nNames<name.length && check = false)
check= false , assigns false to check. To compare check with false you can use
check==falseor !check.
Depending on what you are trying to validate. The below code will remove the compilation error:
check == false //checks if check is false
Or,
if(nNames<name.length && (check = false))
// above is same as if(nNames<name.length && false) // which will always be false

to print the text file in 2d matrix of same dimension given in file using java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to print 2D Array from .txt file in Java
text file is:
8.00 28.00
18.00 28.00
8.00 23.00
12.00 20.00
15.00 30.00
... etc (many more lines)
i am reached upto:
public class Asgn2backup {
public static double[][] matrix;
public static void main(final String[] args) throws IOException {
System.out.print("Enter the name of the file: ");
final String fileName = readInput();
final BufferedReader br = new BufferedReader(
new FileReader(fileName + ".txt"));
String line;
int order = 0;
int rowIndex = 0;
int counter = 0;
while ((line = br.readLine()) != null) {
counter++;
if (counter == 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
}
if (counter == 2) {
final String source = line;
System.out.println("source: " + source);
}
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
final StringTokenizer theLine =
new StringTokenizer(line, ", ");
int colIndex = 0;
while (theLine.hasMoreTokens()) {
final String st = theLine.nextToken();// .trim();
matrix[rowIndex][colIndex] = Double.parseDouble(st);
colIndex = colIndex + 1;
}
rowIndex = rowIndex + 1;
}
}
for (int x = 0; x < matrix.length - 1; x++) {
for (int p = 0; p < matrix.length - 1; p++) {
System.out.print(matrix[x][p] + " ");
}
}
br.close();
}
private static String readInput() {
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
return in.readLine();
} catch (final IOException e) {
}
return "";
}
}
but it gives numberformatexception runtime error.
give me complete solution.
pls help me.
The parser does not fit the input file at all. In each condition you try to parse the entire line as a single integer value. This will cause NumberFormatExceptions.
Example:
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line); // line = "8.00 23.00" < not an integer
The lines contain float or double values. So you'll have to split the line around multiple whitespaces and parse the two fragments with Double.parseDouble(split[<0|1>]) to double values.

Categories

Resources