I just started with this project and tried to check whether I was going the right way. I run this code but got one "FileNotFound exception must be caught or thrown" error. What do I do now? Am I going the right way?
package com.company;
import java.util.Scanner;
import java.io.File;
public class Main
{
public static void main(String[] args)
{
Game game = new Game();
String s = game.OpenFile();
System.out.println(s);
}
}
class Game
{
public Game(){
moviename = " ";
}
private String moviename;
public String OpenFile()
{
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
return moviename;
}
Yes you are going in the right way. What this warning is saying is that you must handle the FileNotFound exception. You have two options: Throw it or surround the code in a try-catch block:
Throwing the exception:
public String OpenFile() throws FileNotFoundException
{
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
return moviename;
}
Try-Catch:
public String OpenFile()
{
try {
File file = new File("movienames.txt");
Scanner ip = new Scanner(file);
int rnum = (int)(Math.random()*10)+1;
int count = 0;
while(ip.hasNextLine())
{
moviename = ip.nextLine();
count++;
if(count==rnum)
{
break;
}
}
}catch(Exception e) {
e.printStackTrace();
}
return moviename;
Some good readings:
Difference between try-catch and throw in java
https://beginnersbook.com/2013/04/try-catch-in-java/
Related
I'm trying to create a class that sorts an array list in descending order of marks. As all my methods are static, I want to write a constructor to prevent class instantiation but am not sure how to go about doing it. I read that a private constructor can be used but unsure how to go about coding it.
Here's my code:
import java.util.*;
import java.io.*;
public class ProcessDegreeMark{
public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
ArrayList<Finalist> finalists = new ArrayList<Finalist>();
String id;
double mark;
Scanner in = null;
try
{
in = new Scanner(new FileReader(s));
try
{
while(in.hasNextLine())
{
id =in.nextLine();
mark = Double.parseDouble(in.nextLine());
finalists.add(new Finalist(id,mark));
}
}
finally
{
in.close();
}
}
catch(IOException e)
{
System.out.println(s+" not found");
}
return finalists;
}
public static void displayFinalists(ArrayList<Finalist> finalists){
for (int i = 0; i < finalists.size(); i++)
{
System.out.println(finalists.get(i));
}
}
public static void findFinalistID(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getId().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with ID number "+s);
}
}
public static void findFinalistClass(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
sortedFinalists.addAll(a);
Collections.sort(sortedFinalists, new FinalistComparator());
return sortedFinalists;
}
public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
PrintStream out = null;
try
{
out = new PrintStream(new FileOutputStream(s));
try
{
for(int i = 0; i < finalists.size(); i++)
{
out.println(finalists.get(i));
}
}
finally
{
out.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
searchFinalists.add(a.get(i));
finalistsToFile2(searchFinalists,"testSorted.txt");
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static void main(String[] args) throws Exception{
System.out.println("/****************************************************/");
System.out.println("/*******finalistsInList with invalid file name*******/");
System.out.println();
ArrayList<Finalist> testList = finalistsInList("file***.txt");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/********finalistsInList with valid file name********/");
System.out.println("/********display to check arraylist populated********/");
System.out.println();
ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
displayFinalists(finalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*testing findFinalistID with valid and invalid data*/");
System.out.println();
findFinalistID(finalists, "75021");
findFinalistID(finalists, "21050");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findFinalistClass with valid and invalid data*/");
System.out.println();
findFinalistClass(finalists, "FIRST");
findFinalistClass(finalists, "THIRD");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****run sortedFinalists then test with display*****/");
System.out.println();
ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
displayFinalists(sortedFinalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
System.out.println("/**************check file testSorted.txt**************/");
System.out.println();
finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
System.out.println();
findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
System.out.println();
System.out.println("/*********************THE END************************/");
}
}
Static methods belong to the class. I don't really understand why are you worrying about having/not having class instantiation. whether they create one instance or multiple instance the callers will have the same copy of static method.Having said that, You can still limit instantation outside the class by adding a default private constructor like below
private ProcessDegreeMark(){}
Just add private modifier before constructor.
public class ProcessDegreeMark{
private ProcessDegreeMark(){}
}
This is a continuance of my previous post but on a different main topic. I don't know why my program reads the file and returns my error value of -460. There are 100 ints in my text file and 99 of them get returned as -460 and the last number in the file gets read correctly. I don't know what is going on! please help! Thank you!
import java.io.*;
import java.util.*;
public class projectFour
{
public static int [] global_numbers;
public static void main (String[] args)
{
read_file();
print_numbers(global_numbers);
}
public static void read_file()
{
try
{
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared? where is its value coming from?!?
{
try {
return Integer.parseInt(numbers);
} catch(NumberFormatException n) {
return -460;
}
}
public static void print_numbers(int [] numbers) // passing in an array called numbers but how does this array have values associated to it!?!
{
int max = numbers.length;
for(int i = 0; i < max; i++)
System.out.println(numbers[i]);
}
}
import java.io.*;
import java.util.*;
public class projectFour
{
public static int [] global_numbers;
public static void main (String[] args)
{
read_file();
print_numbers(global_numbers);
}
public static void read_file()
{
try
{
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine());
global_numbers = new int[amountOfNumbersInFile];
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers)
{
try {
return Integer.parseInt(numbers.trim());
} catch(NumberFormatException n) {
return -460;
}
}
public static void print_numbers(int [] numbers)
{
for(int i = 0; i < numbers.length; i++)
System.out.println(numbers[i]);
}
}
I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:
import java.io.*;
public class Instruction {
public String[] instructionList;
public String[] readFile() throws IOException {
FileInputStream in = new FileInputStream("directions.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
}
The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.
import java.util.Arrays;
public class RoverCommand {
public static void main(String[] args) throws Exception {
Instruction directions = new Instruction();
directions.readFile();
String[] directionsArray;
directionsArray = directions.returnsInstructionList();
System.out.println(Arrays.toString(directionsArray));
}
}
What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?
You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.
// Client.java
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
InstructionList il = new InstructionList();
il.readFile("C:\\testing\\ints.txt", 5);
int[] integers = il.getInstructionsAsIntegers();
if (integers != null) {
for (int i : integers) {
System.out.println(i);
}
}
} catch (IOException e) {
// handle
}
}
}
// InstructionList.java
import java.io.*;
public class InstructionList {
private String[] instructions;
public void readFile(String path, int lineLimit) throws IOException {
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
instructions = new String[lineLimit];
for (int i = 0; i < lineLimit; i++) {
instructions[i] = br.readLine();
}
in.close();
}
public String[] getInstructionsAsStrings() {
return instructions; // will return null if uninitialized
}
public int[] getInstructionsAsIntegers() {
if (this.instructions == null) {
return null;
}
int[] instructions = new int[this.instructions.length];
try {
for (int i = 0; i < instructions.length; i++) {
instructions[i] = new Integer(this.instructions[i]);
}
} catch (NumberFormatException e) {
return null; // data integrity fail, return null
}
return instructions;
}
}
check instructionList is null or not. if it is null, call readFile method.
public String[] returnsInstructionList() {
if (instructionList== null){
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
because of readFile can throw exception, it would be good to use one extra variable. like:
private boolean fileReaded = false;
public String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
and if readFile can be run concurrently, easiest way to make function synchronized, like
private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
.
.
.
}
public synchronized String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.
I would :
public String[] getContentsFromFile(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.
Eg
public class Foo {
public ReturnForFoo returnAStringOrIntger(boolean val) {
if(val){
return new ReturnForFoo("String", ValueType.STRING) ;
}
return new ReturnForFoo(10, ValueType.INTEGER); //int
}
}
public class ReturnForFoo {
Object value;
ValueType type;
public ReturnForFoo(Object value, ValueType type) {
this.value=value;
this.type=type
}
// Asume you have getters for both value and value type
public static ENUM ValueType {
STRING,
INTEGER,
UNKNOWN
}
}
This code is in your main.
Foo foo = new Foo();
String value;
int val;
ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
// NOTE you can use switch instead of if's and else if's. It will be better
if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
val = (int) returnForFoo.getValue();
} else if(returnForFoo.getValueType().equals(ValueType.STRING)){
value = (String) returnForFoo.getValue();
} else {
// UNKOWN Case
}
I have a program that is supposed to load a text file and display/sort the data, however the data is not being displayed at all. Any ideas as to what I'm doing wrong? I have to stick with 1.4.2 Java only.
Here is the code:
import java.io.*;
import java.util.StringTokenizer;
class NewClass {
private static int quantity;
private static String[] name;
public static void main(String args[]) throws Exception {
InputStreamReader kb = new InputStreamReader(System.in);
BufferedReader in;
in = new BufferedReader(kb);
String buffer;
char choice;
boolean fileread=false;
int[]number=new int[quantity];
String[]name=new String[quantity];
String sorttype="";
do
{ //Setup Menu
choice=menu(in);
if(choice=='E')
{
if(fileread)
System.out.println("Data already has been entered");
else
{
fileread=true;
getdata(number,name);
}
}
else if(choice=='D')
{
if(fileread)
display(number,name,in);
else
System.out.println("Must enter data before it is displayed");
}
else if(choice=='S')
{
if(fileread)
sorttype=sort(number,name,in);
else
System.out.println("Must enter data before it is sorted");
}
} while(choice!='X');
}
//Sort Data
public static void sortint(int[] number, String[] name)
{
int i,j;
for(i=0;i<quantity-1;i++)
for(j=i+1;j<quantity;j++)
if(number[i]>number[j])
{
swap(number,i,j);
swap(name,i,j);
}
}
public static void sortstring(String[] name, int[] number)
{
int i,j;
for(i=0;i<quantity-1;i++)
for(j=i+1;j<quantity;j++)
if(name[i].compareToIgnoreCase(name[j])>0)
{
swap(number,i,j);
swap(name,i,j);
}
}
public static void swap(int[] a,int i,int j)
{
int t;
t=a[i];
a[i]=a[j];
a[j]=t;
}
public static void swap(String[] a,int i,int j)
{
String t;
t=a[i];
a[i]=a[j];
a[j]=t;
}
public static String sort(int[] number, String[] name, BufferedReader kb)throws Exception
{
String buffer;
do
{
//Allow user to sort the phone book
System.out.println("What do you want to sort by?");
System.out.println("Number");
System.out.println("Name");
System.out.print("Enter>>");
buffer=kb.readLine();
if(buffer.equalsIgnoreCase("number"))
{
sortint(number,name);
print(name, number,kb);
return buffer;
}
else if(buffer.equalsIgnoreCase("name"))
{
sortstring(name,number);
print(name,number,kb);
return buffer;
}
System.out.println("Invalid entry");
} while(true);
}
public static void print(String[] name, int[] number, BufferedReader kb)throws Exception
{
System.out.println("Sorted data");
System.out.println("Number\tName");
for(int i=0;i<quantity;i++)
System.out.println(number[i]+"\t"+name[i]);
}
public static void display(int[] number, String[] name, BufferedReader kb)throws Exception
{
System.out.println("Number Name");
for(int i=0;i<quantity;i++)
System.out.println(number[i]+" "+name[i]);
}
public static void getdata(int number[],String name[])throws Exception
{
FileReader file = new FileReader("phoneData.txt");
try (BufferedReader input = new BufferedReader(file)) {
int i;
String buffer;
for( i=0;i<quantity;i++)
{
buffer=input.readLine();
StringTokenizer st = new StringTokenizer(buffer, ",");
name[i]=st.nextToken();
number[i]=Integer.parseInt((st.nextToken()).trim());
}
}
}
public static char menu(BufferedReader kb)throws Exception
{
String buffer;
char input;
do
{
System.out.println("\nWhat would you like to do?");
System.out.println("E-Enter phone book data");
System.out.println("D-Display phone book data");
System.out.println("X-Exit program");
System.out.println("S-Sort list");
System.out.print("Enter E, D, X, S>>");
buffer=kb.readLine();
input=(buffer.toUpperCase()).charAt(0);
if(input=='E'||input=='D'||input=='X'||input=='S')
return input;
System.out.println("Invalid entry");
} while(true);
}
}
And here is what it is returning:
What would you like to do?
E-Enter phone book data
D-Display phone book data
X-Exit program
S-Sort list
Enter E, D, X, S>>D
Number Name
What would you like to do?
E-Enter phone book data
D-Display phone book data
X-Exit program
S-Sort list
Enter E, D, X, S>>
Any help is much appreciated.
You might want to initialize quantity
private static int quantity = 1;
instead of just
private static int quantity;
so that the code inside the the loop
for( i=0;i<quantity;i++)
can get a chance....
And as stated in my first comment, you should add some Exception handling and return value checking to your code.
Also you might just delete this line
private static String[] name;
since you have name declared locally in main.
EDIT
public static void getdata(int number[],String name[])throws Exception
{
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("phoneData.txt"));
int i;
String buffer;
for( i=0;i<quantity;i++)
{
// readLinde returns null when EOF is reached
buffer=input.readLine();
if(buffer != null) {
StringTokenizer st = new StringTokenizer(buffer, ",");
name[i]=st.nextToken();
number[i]=Integer.parseInt((st.nextToken()).trim());
} else {
break; // since nothing left to read
// remaining buckets in the arrays are left empty
}
}
} catch (Exception e) {
// catch exceptions to where know your program fails
System.out.println(e.toString());
} finally {
if(input != null) {
// close the input stream when you are done
input.close();
}
}
}
Also you should consider using List instead of arrays
public static void getdata(List number,List name) {
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader("phoneData.txt"));
String buffer;
while(null != (buffer = input.readLine())) {
StringTokenizer st = new StringTokenizer(buffer, ",");
name.add(st.nextToken());
number.add(Integer.valueOf(Integer.parseInt((st.nextToken()).trim())));
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if(input != null) {
try {
input.close();
} catch (IOException e) {
// ignore
}
}
}
}
The method reads the data for the First class and second Class using scanner and then it stores them in the ArrayList the tow class. First and Second are inherited From Main Class. The problem I have is the duplication I created to objects.
How can I only create one and use it for both.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Auto {
private ArrayList<Main> lists;
public Auto() {
lists = new ArrayList<Main>();
}
public void storeData(Main main) {
list.add(main);
}
public void readFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
Scanner input = new Scanner(file);
String dataToBe;
while (input.hasNext()) {
String lines = input.nextLine().trim();
Scanner scanner = new Scanner(lines).useDelimiter("\n[ ]*,");
if (lines.startsWith("Data")) {
if (lines.startsWith("FirstData")) {
dataToBe = "first";
} else if (lines.startsWith("SecondData")) {
dataToBe = "second";
}
} else if (dataToBe.equals("first")) {
Main main = new First();
main.readData(scanner);
storeData(main);
} else if (dataToBe.equals("second")) {
Main main = new Second();
main.readData(scanner);
storeData(main);
}
}
}
}
Okay, you might think its longwinded, but it's probably how I would do it under your restrictions.
public void readFile(String filePath) throws FileNotFoundException {
final Pattern pattern = Pattern.compile("\n[ ]*,");
final Scanner fileInput = new Scanner(new File(filePath));
while (fileInput.hasNextLine()) {
final String line = fileInput.nextLine().trim();
final Matcher matcher = pattern.matcher(line);
final StringBuilder builder = new StringBuilder();
byte flag = 0;
while (matcher.find()) {
final String match = matcher.group();
if(match.startsWith("FirstData")){ flag = 1;}
else if(match.startsWith("SecondData")){flag = 2;}
builder.append(line).append(",");
}
Main mainObj = (flag == 1) ? (new First()) : (flag == 2) ? (new Second()) : null;
if(null != mainObj){
mainObj.readData(builder.toString());
}
}
}
The approach above does require you to accept a String instead of a Scanner in the parameter, but the CSV format passed to each method lets the behaviour of each class handle the work.