CodeEval Challenge Fizz Buzz - java

I am trying to learn Java. The other day I saw a website providing challenges to solve online. Here is the code project I choose: Fizz Buzz
This is where I am with the project:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
openFile(file);
int[] line = new int[3];
while (nextLine()) {
try{
line = readLine();
String output = getLineOutput(line);
System.out.println(output);
}catch(NoSuchElementException e) { System.out.println("No such element exception"); }
}
}
static Scanner scan;
static void openFile(File file) {
try {
scan = new Scanner((file));
} catch (FileNotFoundException e) {
System.out.println("Could not find file");
}
}
static int[] readLine() {
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int[] line;
line = new int[] { a, b, c };
return line;
}
static boolean nextLine() {
return scan.hasNextLine();
}
static String getLineOutput(int[] line) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= line[2]; i++)
if (i % line[0] == 0 && i % line[1] == 0) {
sb.append("FB ");
} else {
if (i % line[0] == 0) {
sb.append("F ");
}
if (i % line[1] == 0) {
sb.append("B ");
}
if (i % line[0] > 0 && i % line[1] > 0) {
sb.append(i + " ");
}
}
return sb.toString();
}
}
When I run the program in command prompt providing a path to a text file as the first argument my program seems to work fine. On CodeEval I get the following error:
CodeEval Error: Compilation was aborted after 10 seconds
Should I be accessing the file differently? Is there an exception I'm missing? None of my exceptions are prompting me.

In case this helps anyone in the future this code doesn't close the scanner. Unfortunately on CodeEval the code doesn't execute if this is the case.
Adding scan.close() at the end of main method (after while loop solved) the issue.
Edit: code difference
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
openFile(file);
int[] line = new int[3];
while (nextLine()) {
try{
line = readLine();
String output = getLineOutput(line);
System.out.println(output);
}catch(NoSuchElementException e) { System.out.println("No such element exception"); }
}
scan.close();
}

Related

Why my Java program works perfectly in windows but it's a disaster in linux?

I wrote a program that reads a text file, deletes the requested string and rewrites it without the string. This program takes three arguments from the terminal: 1) the input file 2) the string 3) the output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class wordfilter {
public static void main(String[] args) {
Scanner scanner = new Scanner("");
Scanner conteggio = new Scanner("");
int numel = 0;
File file = new File(args[0]); // Argomento 0: il file
try {
conteggio = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (conteggio.hasNext()) {
numel++;
conteggio.next();
}
conteggio.close();
String[] lettura = new String[numel];
int i = 0;
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File non trovato");
}
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
System.out.println("Contarighe -> " + numel);
for (i = 0; i < lettura.length; i++) {
System.out.println("Elemento " + i + " - > " + lettura[i]);
}
scanner.close();
String escludi = args[1]; // Argomento 1: il filtro
String[] filtrato = rimuovi(escludi, lettura);
if (args.length == 3) stampaSuFile(filtrato, args[2]);
}
public static String[] rimuovi(String esclusione, String[] input) {
String[] nuovoV;
String escludi = esclusione;
int dim = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi))
dim++;
}
nuovoV = new String[dim];
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!input[i].equals(escludi)) {
nuovoV[j] = input[i];
j++;
}
;
}
return nuovoV;
}
public static void stampaSuFile(String[] out, String path) {
String closingstring = "";
File destinazione = new File(path);
try {
destinazione.createNewFile();
} catch (IOException e) {
System.out.println("Errore creazione file");
}
try {
FileWriter writer = new FileWriter(destinazione);
for (int i = 0; i < out.length; i++)
writer.write(out[i] + (i == (out.length-1) ? closingstring : " "));
writer.close();
System.out.println("Scrittura eseguita correttamente");
} catch (IOException e) {
System.out.println("Errore scrittura file");
}
}
}
On Windows no problem, it works perfectly.
On Linux instead when i write something like java wordfilter in.txt word out.txt
I get
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at wordfilter.main(wordfilter.java:42)
What's the problem? It's because of some difference on linux?
You're mixing line and token based functions, :hasNextLine() and next(). If the input ends with a line feed (typical on Linux) hasNextLine returns true at the end of the file, but there is no next "item".
while (scanner.hasNextLine()) {
lettura[i] = scanner.next();
i++;
}
You should use either hasNext with next, or hasNextLine with nextLine, mixing them is confusing.
while (scanner.hasNext()) {
lettura[i] = scanner.next();
i++;
}
The input file ends in a newline on Linux. Therefore, there's another line, but it's empty. If you remove the final newline from the input, the program will start working normally.
Or, import the exception
import java.util.NoSuchElementException;
and ignore it int the code
while (scanner.hasNextLine()) {
System.out.println("" + i);
try {
lettura[i] = scanner.next();
} catch (NoSuchElementException e) {}
i++;
}

How can I make this Java read the whole last line, and not just each byte at a time?

I have a simple Java IO program which reads from a text file of numbers that looks like this :
1
2
3
4
5
6
7
8
9
17
It's supposed to simply print the lines in this text file to the console, and then tell me what the last line was. But it's printing the last line, here 17, as just 7 -
Here's my code so far :
import java.lang.*;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ParentClass3{
static int lastLine = 0;
public static void main(String[] args) {
File file = new File("C:\\Java_Scratch_\\someFile.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
try {
int i = sc.nextInt();
System.out.println(i);
} catch (Exception e) {
System.out.println (" here is the stack trace " + e.getStackTrace() );
System.out.println (" here is the stack trace " );
}
}
sc.close();
} // END big-outer-Try
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
int i = ParentClass3.countLines("C:\\Java_Scratch_\\someFile.txt");
System.out.println("There are " + i + " lines");
}
catch (IOException ioe) {
System.out.print("ioe" + ioe.getStackTrace() );
}
}
// putting the count function
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
int lastline = 0;
boolean empty = true;
while ( (readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i){
Byte b = c[i];
int xx = b.intValue();
lastLine = xx;
if (c[i] == '\n'){
++count;
empty = true;
} else {
empty = false;
}
}
}
if (!empty) {
count++;
}
int asciiVal = lastLine;
int lastLine2 = Character.getNumericValue(asciiVal);
System.out.println("the last line was " + lastLine2);
return count;
} finally {
is.close();
}
}//END method countLines
// end-count_func
}
How would I fix it, so that it says "the last line was 17" , rather just just 7 ?
the methos nextLine() should work, although I don't remember if that input would be parsed to a String, I guess that wouldn't affect, but anyway...

How do i load a text file into this program?

How do i go about loading a text file into a java program that i have posted below. I have tried but am out of luck, any help will be appreciated!
Thank you.
import java.io.*;
public class test1 {
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
try {
FileReader infile = new FileReader(args[0]);
BufferedReader inbuf = new BufferedReader(infile);
String str;
int totalwords = 0, totalchar = 0;
while ((str = inbuf.readLine()) != null) {
String words[] = str.split(" ");
totalwords += words.length;
for (int j = 0; j < words.length; j++) {
totalchar += words[j].length();
}
}
double density = (1.0 * totalchar) / totalwords;
if (totalchar > 0) {
System.out.print(args[0] + " : " + density + " : ");
if (density > 6.0)
System.out.println("heavy");
else
System.out.println("light");
} else
System.out.println("This is an error - denisty of zero.");
infile.close();
} catch (Exception ee) {
System.out.println("This is an error - execution caught.");
}
}
}
If you are running java 8 it is a breeze with the new io streams. Advantage is on large file all text is not read into memory.
public void ReadFile(String filePath){
File txtFile = new File(filePath);
if (txtFile.exists()) {
System.out.println("reading file");
try (Stream<String> filtered = Files.
lines(txtFile.toPath()).
filter(s -> s.contains("2006]"))) {//you can leave this out, but is handy to do some pre filtering
filtered.forEach(s -> handleLine(s));
}
} else {
System.out.println("file not found");
}
}
private void handleLine(String lineText) {
System.out.println(lineText);
}
First of all, there is an easier way to read files. From Java 7 the Files and Paths classes can be used like this:
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
final List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
// Do stuff...
}
// More stuff
}
Then, in order to start the program and get it to read a file that you specify you must provide an argument when starting the app. You pass that argument after the class name on the command prompt like this:
$ java Tut16_ReadText /some/path/someFile.txt
This passes "/some/path/someFile.txt" to the program and then the program will try to read that file.
Another method is to use a Scanner.
Scanner s = new Scanner(new File(args[0]));
while(s.hasNext()){..}

How to properly display an error when Commandline Argument is left blank by user?

So as you can I see i am reading from a file and displaying all the integers in the file and putting the amount in an array, What I need help with is just a trycatch block which prints out "You did not enter anything", Basically when the Commandline argument is left blank by the user.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class Print5{
public static void main(String[] commandlineArgument) {
Integer[] array = Print5.readFileReturnIntegers(commandlineArgument[0]);
Print5.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] temp = new Integer[10000];
int i = 0;
File file = new File(filename);//Connects File
Scanner inputFile = null;
try{
inputFile = new Scanner(file);
}
catch(FileNotFoundException Exception1) {
System.out.println("File not found!"); //error message when mistyped
}
//where the blank error arg will go
if (inputFile != null) {
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();
i++;
} catch (InputMismatchException Exception3) { //change this back to e if doesnt work
inputFile.next();
}
}
}
finally {
inputFile.close();
}
Integer[] array = new Integer[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new Integer[] {};
}
//Prints the array
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
System.out.println("number of integers in file \"" + filename + "\" = " + array.length);
for (int i = 0; i < array.length; i++) {
System.out.println("index = " + i + "," + " element = " + array[i]);
}
}
}
Add a check on the size of the array and exit the program after displaying an error message:
public static void main(String[] commandlineArgument) {
if(commandlineArgument.length < 1) {
System.err.println("Your error message"); // use the std error stream
System.exit(-1);
}
...
By convention, a nonzero status argument to System.exit() indicates abnormal termination.
Just check the args array length:
public static void main(String[] commandlineArgument) {
if ( commandlineArgument.length > 0 ) {
Integer[] array = Print5.readFileReturnIntegers(commandlineArgument[0]);
Print5.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
else {
System.out.println("usage - ... your message");
}
}
Try using the Apache CLI library.
http://commons.apache.org/proper/commons-cli/
It allows you to define required options and fail out if they're missing.

calling method with IOException

I had this program with which i have to check if the value the user entered is present in the text file i created in the source file. However it throws me an error everytime i try to call the method with IOException. Please help me out thanks.
import java.util.*;
import java.io.*;
public class chargeAccountModi
{
public boolean sequentialSearch ( double chargeNumber ) throws IOException
{
Scanner keyboard= new Scanner(System.in);
int index = 0;
int element = -1;
boolean found = false;
System.out.println(" Enter the Charge Account Number : " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length )
{
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for ( index = 0 ; index < tests.length ; index ++ )
{
if ( tests[index] == chargeNumber )
{
found = true;
element = index;
}
}
return found;
}
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
object1.sequentialSearch(chargeNumber);
}
catch (IOException ioe)
{
}
System.out.println(" The search result is : " + object1.sequentialSearch (chargeNumber));
}
}
After looking on your method sequentialSearch there is everythink ok. But try to change main:
But remember that in your Names.txt file you should have only numbers because you use scanner.nextInt();, so there should be only numbers or method will throw exeption InputMismatchException.
Check also path to Names.txt file you should have it on classpath because you use relative path in code File file = new File ("Names.txt"); Names.txt should be in the same folder.
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
System.out.println(" The search result is : " + object1.sequentialSearch(chargeNumber));
}
catch (IOException ioe)
{
System.out.println("Exception!!!");
ioe.printStackTrace();
}
}
Few tips and suggestions:
First of all: Don't forget to close the Scanner objects! (you left one unclosed)
Second of all: Your main method is highly inefficient, you are using two loops, in the first one you read and store variables, in the second one you check for a match, you can do both at the same time (I've written an alternative method for you)
Third little thing: The variable "element" is not used at all in your code, I've removed it in the answer.
And last but not least: The file "Names.txt" needs to be located (since you've only specificied it's name) in the root folder of your project, since you mention an IOException, I figure that's what's wrong with the app. If your project is called Accounts, then it's a folder called Accounts with it's source and whatever else is part of your project, make sure the file "Accounts/Names.txt" exists! and that it is in the desired format.
import java.util.*;
import java.io.*;
public class ChargeAccountModi {
public boolean sequentialSearch(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
int index = 0;
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length ) {
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for (index = 0 ; index < tests.length ; index ++ ) {
if (tests[index] == chargeNumber) {
found = true;
}
}
keyboard.close();
return found;
}
public boolean sequentialSearchAlternative(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int tests = 18;
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i<tests) {
if (inputFile.nextInt() == chargeNumber) {
found = true;
break;
}
i++;
}
inputFile.close();
keyboard.close();
return found;
}
public static void main(String[] args) {
double chargeNumber = 0;
ChargeAccountModi object1 = new ChargeAccountModi();
try {
System.out.println("The search result is : " + object1.sequentialSearch(chargeNumber));
} catch (Exception e) {
//Handle the exceptions here
//The most likely exceptions are:
//java.io.FileNotFoundException: Names.txt - Cannot find the file
//java.util.InputMismatchException - If you type something other than a number
e.printStackTrace();
}
}
}

Categories

Resources