I'm on my winter break and trying to get my Java skills back up to snuff so I am working on some random projects I've found on codeeval. I'm having trouble opening a file in java doing the fizzbuzz program. I have the actual fizzbuzz logic part down and working just fine, but opening the file is proving problematic.
So presumably, a file is going to be opened as an argument to the main method; said file will contain at least 1 line; each line contains 3 numbers separated by a space.
public static void main(String[] args) throws IOException {
int a, b, c;
String file_path = args[0];
// how to open and read the file into a,b,c here?
buzzTheFizz(a, b, c);
}
You can use the Scanner like so;
Scanner sc = new Scanner(new File(args[0]));
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
By default scanner uses whitespace and newline as seperators, just what you want.
try {
Scanner scanner = new Scanner(new File(file_path));
while( scanner.hasNextInt() ){
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
buzzTheFizz( a, b, c);
}
} catch( IOException ioe ){
// error message
}
Using a loop it reads the whole file, have fun:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
int c = 0;
String file_path = args[0];
Scanner sc = null;
try {
sc = new Scanner(new File(file_path));
while (sc.hasNext()) {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
System.out.println("a: " + a + ", b: " + b + ", c: " + c);
}
} catch (FileNotFoundException e) {
System.err.println(e);
}
}
}
Related
I am working on a MabLibs project that is supposed to iterate through a file, prompt you with anything contained in a <> block and allow you to write over to a new file.
I cannot figure out how to use a Scanner to read a file and turn that into a string so I can use the .length() method to iterate a for loop through the file to find these <> blocks.
I can only use Scanner and can't use array lists, so unfortunately the for loop is the only way I can do this.
Here's the code:
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args)
throws FileNotFoundException {
intro();
madLib();
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
System.out.println();
}
public static void madLib() throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String r = input.next();
while (!(r.equalsIgnoreCase("c") || r.equalsIgnoreCase("v")
|| r.equalsIgnoreCase("q"))) {
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
}
if (r.equalsIgnoreCase("v")) {
viewFile();
}
else if (r.equalsIgnoreCase("c")) {
createWord();
}
}
public static void createWord() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
String input2 = input1;
PrintStream output = new PrintStream(new File(toRead));
while (input1.hasNext()) {
String input = input1.next();
for (int i = 0; i < input2.length(); i++) {
if (input.startsWith("<") && input.endsWith(">")) {
String token = input.substring(1, input.length() - 1);
System.out.println("Please input a: " + token);
Scanner scan = new Scanner(System.in);
String replacement = scan.nextLine();
token = token.replace(token, replacement);
output.print(token);
}
}
}
}
public static void viewFile() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
System.out.println();
while (input1.hasNextLine()) {
System.out.println(input1.nextLine());
}
}
}
Any help is greatly appreciated.
Program to count how many times a particular character, letter or number occur in a sentence.
However I keep getting message:
Resource leak: 'sc' is never closed
I am using Java and Eclipse. What should I do?
import java.util.Scanner;
class Number-count {
public static void number - count(String args[]) {
String s;
char ch;
int count = 0;
Scanner SC = new Scanner(System. in );
System.out.println("Enter a sentence");
String str = sc.nextLine();
System.out.println("Enter a character to be searched for occurence");
s = sc.nextLine();
char c = s.charAt(0);
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (ch == c) {
count++;
}
}
System.out.println("Character " + c + " occur " + count + " times");
}
}
Scanner objects need to be closed after one is done using them. So, after you're done with it you should call the following before the end of your main method
SC.close();
after your scanner work completed put: sc.close();
It is working 100%
Try this code
public static void number - count(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
try{
//your code
}
finally {
sc.close();
}
}
If you want to use the scanner globally in a class(which is the case sometimes)
try this:
static Scanner sc = new Scanner(System.in);
/* Making it easy for beginners, when we use Scanner sc it is required to be close once we have taken all inputs from user, to close use sc.close(); */
package basicjava;
import java.util.*;
public class sumbyuser {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your numbers for summation : ");
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a+b;
System.out.println("Summation is : "+sum);
}
}
Try sc.close();
After the using the scanner inputs :
import java.util.*;
public class Func1 {
public static void CalculateSum() {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
sc.close();
int sum = a + b;
System.out.println("The sum is " + sum);
}
public static void main(String[] args) {
CalculateSum();
}
}
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
Scanner sv=new Scanner(System.in);
b=sv.nextInt();
Scanner st=new Scanner(System.in);
n=st.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
}
I tried using scanner class but it is not executed by eclipse as it only shows sc,sv and st objects of scanner class is resource leaked and never closed.
Well, it appears you have some configs that keep your program from compiling and running based on the resource leaking (not an Eclipse user). Your code compiles and runs with Intellij on my machine so you have a few choices.
Change your configuration to ignore the warning/error. (not recommended)
Close the one Scanner you need. (scanner.close()) You can get more than one value from the single scanner. So, ditch the other ones.
To accomplish (2) another way you could use try-with-resources block and it will be closed automatically at the end of the try.
try (Scanner sc = new Scanner(System.in)) {
// put your code to get input here
} catch (IOException ioe) { ... }
In addition to the scanner issues you're asking about, you have a significant error in your code that will make it impossible to get any meaningful/accurate output. Consider...
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
int result = a + c;
System.out.print(result + " ");
}
c is made anew on each loop and assigned a value of 0 and so c = 2 * c * b; will equal 0 always; and a + c will then always just equal a.
Dont need to create a new Scanner Object...
just do:
int a, b, n;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
final int result = a + c;
System.out.print(result + " ");
}
I was typing this out when #Xoce was posting his answer, so it's exactly the same as his :)
The only other thing that I'd like to add is that if you're using IntelliJ, try pressing control-alt-i to auto-indent your code.
public static void main(String[] args) {
//Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
n=sc.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
i tried reading a string from a file and it worked just fine but it won't work with an integer. i can't seem to find the problem
public static void main(String[] args) throws FileNotFoundException {
File in = new File ("FCITsamba.in.rtf");
Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
File outFile = new File("FCITsamba.txt");// the out file
PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file
int maxAccounts = 0;//maximum number of accounts that can be in the bank
int maxTransactions = 0;//maximum number of transactions in a given day
int accNum = 0;
int transNum = 0;
int d = 0;
int k = 0;
int dayNo = 1;
if (!in.exists()) {
System.out.println("Input file, " + in + ", does not exist.");
System.exit(0);
}
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
it gives me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1
i tried putting an inputMismatchException but it didn't work i also tried putting it in an if statement as shown below:
if(scanner.hasNextInt()){
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
}
but it didn't work as well
this is the input File :
200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...
When you read from a file, it won't recognize whether it is reading numbers or strings, hence everything will be treated as strings including what is shown in your data file (200, 10000, 2, 11).
Instead of writing:
d = scanner.nextInt();
Try this:
d = Integer.parseInt(scanner.nextLine());
Scanner reads 1 value at a time, so if the next value you are trying to read is not an int it will throw an error.
I used your data and the following worked for me:
public static void main(String[] args) {
//Replace FILE_PATH with your file path.
try {
Scanner reader = new Scanner(new File("FILE_PATH/fromFile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/toFile.txt"));
int maxAccounts = reader.nextInt();
int maxTransactions = reader.nextInt();
int d = reader.nextInt();
int k = reader.nextInt();
writer.println("maxAccounts: " + maxAccounts);
writer.println("maxTransactions: " + maxTransactions);
writer.println("d: " + d);
writer.println("k: " + k);
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
So here's my code.
https://ideone.com/ok42QZ
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int z = sc.nextInt();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
The main problem is that I cant get past System.out.println("setcaculatorinput") as it crashes right after that line.
Let me format your code...
first:
if ("+".equals(z))
; // it's an empty condition!
{ // this is an init block
System.out.println(c);
}
All your code "formated":
public static void main(String[] args) throws java.lang.Exception {
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int z = sc.nextInt();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
int b = sc.nextInt();
int c, d, e, f;
c = (a + b);
d = (a - b);
e = (a * b);
f = (a / b);
if ("+".equals(z))
;
if ("-".equals(z))
;
if ("*".equals(z))
;
if ("/".equals(z))
;
{ // init block
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
}
System.exit(0);
}
The error is shown because you try to read an non integer character, read the Javadoc of new Scanner("").nextInt(); and you'll see that it throws: "InputMismatchException - if the next token does not match the Integer regular expression, or is out of range".
I give you a short solution, but I don't recommend it since no checks are performed on the inputs..
public static void main(String[] args) {
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int result = 0;
System.out.println("setvalueA=");
int a = sc.nextInt();
System.out.println("setOperator=");
String op = sc.next();
System.out.println("setvalueB=");
int b = sc.nextInt();
if ("+".equals(op))
result = a + b;
else if ("-".equals(op))
result = a - b;
else if ("*".equals(op))
result = a * b;
else if ("/".equals(op))
result = a / b;
System.out.println("The result is=" + result);
System.exit(0);
}
1) for starter change your line 17 to String z = sc.next();
you are reading integer, passing character, and further treat it as string
2) after your each if statement, you have ; so each block after will be executed anyway
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
int z = Integer.parseInt(sc.nextLine());
System.out.println("setvalueA");
int a = Integer.parseInt( sc.nextLine());
System.out.println("setvalueB");
Basically what is happenning is , While you are reading double as sc.nextInt(), you are reading only the int, however there would be ENDLINE character when you hit enter on the stream that is not read by sc.nextInt().
The problem is with trying to parse the input + as an integer in line 13 of your code (along with your first input on stdin). You can switch the call from .nextInt() to .nextLine() and change the type of z to a String
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
//switch z out for a String instead of an int, and use .nextLine()
String z = sc.nextLine();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
int b = sc.nextInt();
...
}
This code will work :
import java.util.Scanner;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("setcaculatorinput");
Scanner sc = new Scanner(System.in);
String z = sc.next();
System.out.println("setvalueA");
int a = sc.nextInt();
System.out.println("setvalueB");
int b = sc.nextInt();
int c;
int d;
int e;
int f;
c = ( a + b );
d = ( a - b );
e = ( a * b );
f = ( a / b );
if("+".equals(z))
{
System.out.println(c);
}
if("-".equals(z))
{
System.out.println(d);
}
if("*".equals(z))
{
System.out.println(e);
}
if("/".equals(z))
{
System.out.println(f);
}
System.exit(0);
}
}
Thank you