Hello I am working on a project and I continue to get an error message and I can't figure out why. Can someone please help?
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.StringIndexOutOfBoundsException;
public class Authorship{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
System.out.println("Name of input file:");
String correctAnswers = scanner.next();
File file =new File(scanner.next());
if(!file.exists()){
System.out.println(" This file does not exist");
} else {
BufferedReader reader = null;
ArrayList<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
int count[] = new int[13];
while ((text = reader.readLine()) != null) {
String[] line = text.split(" ");
for(int i=0;i<line.length;i++){
int wordCount = line[i].length();
count[wordCount-1]++;
totalWordCount++;
}
}
for(int i = 0;i < 13;i++){
float percentage =count[i]*100/totalWordCount;
if(i != 12) {
System.out.printf("Proportion of "+(i+1)+"-letter words: %.2f%%(%d words)", percentage, count[i]);
} else {
System.out.printf("Proportion of 13- (or more)letter words: %.2f%%(%d words)", percentage, count[i]);
System.out.println("\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
}
}
I receive the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Authorship.main(Authorship.java:36)
if wordCount is 0 then [wordCount - 1] is -1
so you are getting ArrayIndexOutOfBoundsException: -1 exception when access -1 index . count[wordCount - 1]//error occured
to avoid this check wordcount length first.access wordCount - 1 only when wordCount > 0
while ((text = reader.readLine()) != null) {
String[] line = text.split(" ");
for (int i = 0; i < line.length; i++) {
int wordCount = line[i].length();
if (wordCount > 0) {
count[wordCount - 1]++;
totalWordCount++;
}
}
}
I believe I fixed your code. It should run fine now.
You needed to change totalWordCount++; to wordCount and *100/totalWordCount; to i
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.StringIndexOutOfBoundsException;
public class Authorship{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
System.out.println("Name of input file:");
String correctAnswers = scanner.next();
File file =new File(scanner.next());
if(!file.exists()){
System.out.println(" This file does not exist");
} else {
BufferedReader reader = null;
ArrayList<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
int count[] = new int[13];
while ((text = reader.readLine()) != null) {
String[] line = text.split(" ");
for(int i=0;i<line.length;i++){
int wordCount = line[i].length();
count[wordCount-1]++;
wordCount++;
}
}
for(int i = 0;i < 13;i++){
float percentage =count[i]*100/i;
if(i != 12) {
System.out.printf("Proportion of "+(i+1)+"-letter words: %.2f%%(%d words)", percentage, count[i]);
} else {
System.out.printf("Proportion of 13- (or more)letter words: %.2f%%(%d words)", percentage, count[i]);
System.out.println("\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
}
Related
I am new to java and this might sound really stupid but !
Assume you have this txt file somewhere in your pc
The_txt.txt
Anthony
anthonyk#somewhere.com
01234567891
location
Maria
maria#somewhere.com
1234561234
location2
George
george#somewhere.com
1234512345
location3
What i want to do with this txt is that , I prompt the user to insert a Phone number so if for example the user provides Maria's phone number (1234561234) the program will output
Maria
maria#somewhere.com
1234561234
location2
My piece of code for this task :
private static void Search_Contact_By_Phone(File file_location){
Scanner To_Be_String = new Scanner(System.in);
String To_Be_Searched = To_Be_String.nextLine();
System.out.println("\n \n \n");
BufferedReader Search_Phone_reader;
try {
Search_Phone_reader = new BufferedReader(new FileReader (file_location));
String new_line = Search_Phone_reader.readLine();
while (new_line != null) {
if (To_Be_Searched.equals(new_line)){
for (int i=0;i<=3;i++){
System.out.println(new_line);
new_line = Search_Phone_reader.readLine();
}
break;
}
new_line = Search_Phone_reader.readLine();
}
Search_Phone_reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thank you in advance!!!
package com.mycompany.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// For a small file
Path path = Paths.get("The_txt.txt");
String toBeSearched = "1234512345";
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Better performance if i starts at 2 and i += 4
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).equals(toBeSearched)) {
System.out.println(lines.get(i - 2));
System.out.println(lines.get(i - 1));
System.out.println(lines.get(i));
System.out.println(lines.get(i + 1));
}
}
// Else
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line1;
while ((line1 = reader.readLine()) != null) {
String line2 = reader.readLine();
String line3 = reader.readLine();
if (line3.equals(toBeSearched)) {
// Found
System.out.println(line1);
System.out.println(line2);
System.out.println(line3);
System.out.println(reader.readLine());
break;
} else {
reader.readLine();
}
}
}
}
}
I am trying to read a file from my computer, and have the system print out the file only containing the letters, and not printing the numbers. I have other functions in my code already so please look near the bottom where I am stuck with arraylist. How do I ignore the integers when printing?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("/Users/wolftrek/Downloads/example.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
myFileLines.add(sCurrentLine);
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
for (int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains("example word")) {
System.out.println(myFileLines.get(i));
}
}
Scanner myScanner = new Scanner (System.in);
String enteredString = "";
System.out.println("Please enter the characters to search for: ");
enteredString = myScanner.nextLine();
for(int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains(enteredString)) {
System.out.println(myFileLines.get(i));
}
}
ArrayList<String> input = myFileLines;
String extract = input.replaceAll("[^a-zA-Z]+", "");
System.out.println(extract);
}
}
The error is you are applying replaceAll on a list and also the regex is not correct. Something like below will do the job. I am not clear if that's what you want though.
ArrayList<String> input = myFileLines;
for (String e : input) {
String extract = e.replaceAll("\\d+", "");
System.out.println(extract);
}
I wrote code for a program that reads a file containing a list of numbers and outputs, for each number in the list, the next bigger number. I'm using eclipse for this project and when i go an run the program I'm getting an error and i cant seem how to fix it.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string:
"78,22,56,99,12,14,17,15,1,144,37,23,47,88,3,19"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at numbers.main(numbers.java:25)
Here's my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class numbers {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> nextList = new ArrayList<Integer>();
File file = new File("list.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// read the list of number from file
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
// loop through each number
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
int max = Integer.MAX_VALUE;
// get the next max value of each number
for (int j = 0; j < list.size(); j++) {
if (num < list.get(j) && list.get(j) < max) {
max = list.get(j);
}
}
nextList.add(max);
}
// print the numbers
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + " : " + nextList.get(i));
}
} catch (FileNotFoundException e) {
// if file not found
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// close the file at the end
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
You need to split ( and also trim() ) your line over a comma (,) and then parse over all the elements you obtain.
Hope this solves your query.
The issue is you are trying to convert a string with multiple numbers to a single integer, which is causing your exception. Try this instead:
while ((text = reader.readLine()) != null) {
String [] textArray = text.split(",");
for (int i = 0; i < textArray.length; i++) {
list.add(Integer.parseInt(textArray[i]));
}
}
String line="";
while ((text = reader.readLine()) != null) {
line=text; //read the text
}
line.trim();
// loop through each number
for(String num:line.split(",")){
list.add(Integer.parseInt(num)); //add the item to the list
}
The text could have some non numeric characters so you should check about them so try like this
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
List<Integer> nextList = new ArrayList<>();
File file = new File("list.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text;
while ((text = reader.readLine()) != null) {// read the list of number from file
if(!text.isEmpty()) {
try {
if (text.contains(",")) {
for (String str : text.split(",")) {
list.add(Integer.parseInt(str));
}
}
else if(text.matches("[+-]?[0-9]+")) {
list.add(Integer.parseInt(text));
}
else {
System.out.println("this is not a number : " + text);
}
} catch (NumberFormatException e){
System.out.println("this is not a number : "+ text);
}
}
}
for (int i = 0; i < list.size(); i++) {// loop through each number
int num = list.get(i);
int max = Integer.MAX_VALUE;// get the next max value of each number
for (int j = 0; j < list.size(); j++) {
if (num < list.get(j) && list.get(j) < max) {
max = list.get(j);
}
}
nextList.add(max);
}
for (int i = 0; i < list.size(); i++) {// print the numbers
System.out.println(list.get(i) + " : " + nextList.get(i));
}
}
catch (FileNotFoundException e) {// if file not found
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {// close the file at the end
try {
if (reader != null) {
reader.close();
}
}
catch (IOException e) {
}
}
}
I saw some similar questions, but mine is a little different.
I define a
Map<Integer, ArrayList<Double>> fl;
My input .txt file:
1 0.56 0.57 0.73 ..
2 2.3 3.50 ...
9 4.98 0.99 ..
How to read the file into the map fl?
Thanks!
Use a Scanner and first call Scanner.readInt() that will give you the first integer.
Then call Scanner.readLine() that will give you all the remaining double in the line as a String. Split it and parse everything to double.
Repeat the same till end of file.
Here's a try.
I've compiled and run the code.
Make sure the input file is in the same directory as your project if you use an IDE.-- This only applies if you do not modify the path below.
package fileread;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FileRead {
private static HashMap<Integer, ArrayList<Double>> map = new HashMap<>();
private static BufferedReader reader;
public static void main(String[] args) {
try
{
reader = new BufferedReader(new FileReader("input"));
//or reader = new BufferedReader(new FileReader("C:\\full-path-to-your-file));
String line;
while((line = reader.readLine()) != null)
{
String[] tokens = line.split(" ");
Integer i;
Double d;
ArrayList<Double> list = new ArrayList<>();
i = Integer.valueOf(tokens[0]);
for(int j = 1; j < tokens.length; j++)
list.add(Double.valueOf(tokens[j]));
map.put(i, list);
}
}catch(IOException ex)
{
//break execution
}finally
{
if(reader != null)
try
{
reader.close();
}catch (IOException ex) {
//don't break :)
}
}
for(Integer i : map.keySet())
{
ArrayList<Double> l = map.get(i);
System.out.print("Line " + i + ": ");
for(Double d: l)
System.out.print(d + " ");
System.out.println();
}
}
}
The code for parsing the file and populating the map should be like below
try {
BufferedReader bReader = new BufferedReader(new FileReader(new File("c:/input .txt")));
String line = "";
Map<Integer, ArrayList<Double>> fl = new HashMap<Integer, ArrayList<Double>>();
while ((line = bReader.readLine()) != null) {
String[] strArray = line.split(" ");
for (int i=0;i<strArray.length;i++) {
ArrayList<Double> value = new ArrayList<Double>();
int key=0;
if(i==0){
key =Integer.valueOf(strArray[0]);
}
else{
value.add(Double.valueOf(strArray[i]));
}
fl.put(key, value);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}