"Cannot Find Symbol - method hasNextLine()" error in Java - java

I am trying to write a program that uses file I/O to score personality tests. However, when I get to this code:
while (f.hasNextLine()) {
I get the error described in the title. Here is the code in its entirety. I import all of the necessary I/O and utilities prior and I think I am declaring the file variable correctly. I know that this method exists, but what is the problem?
import java.io.*;
import java.util.*;
public class PersonalityTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String input = input();
String output = output();
results(input, output);
System.out.println("Your results are located in the file you requested.");
}
public static String input() throws IOException {
System.out.print("Input file name: ");
String file = input.nextLine();
File f = new File(file);
System.out.println();
while (!f.exists()) {
System.out.print("File not found. Try again: ");
file = input.nextLine();
f = new File(file);
System.out.println();
}
return file;
}
public static String output() {
System.out.print("Output file name: ");
String output = input.nextLine();
return output;
}
public static void results(String input, String output) throws IOException {
PrintStream write = new PrintStream(new File(output));
File f = new File(input);
while (f.hasNextLine()) {
String name = f.nextLine();
String type = "ESTJ";
String answers = f.nextLine();
char[] choices = new char[70];
for (int i = 0; i <= 69; i++) {
choices[i] = answers.charAt(i);
}
int aCount = 0;
int bCount = 0;
for (int i = 0; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount+=1;
}
}
int pct1 = (int)Math.round((bCount/(aCount+bCount))*100);
if (pct1 > 50) {
type.replace('E','I');
}
if (pct1 == 50) {
type.replace('E','X');
}
int aCount2 = 0;
int bCount2 = 0;
for (int i = 2; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount2+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount2+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount2+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount2+=1;
}
}
int pct2 = (int)Math.round((bCount2/(aCount2+bCount2))*100);
if (pct2 > 50) {
type.replace('S','N');
}
if (pct2 == 50) {
type.replace('S','X');
}
int aCount3 = 0;
int bCount3 = 0;
for (int i = 4; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount3+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount3+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount3+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount3+=1;
}
}
int pct3 = (int)Math.round((bCount3/(aCount3+bCount3))*100);
if (pct3 > 50) {
type.replace('T','F');
}
if (pct3 == 50) {
type.replace('T','X');
}
int aCount4 = 0;
int bCount4 = 0;
for (int i = 6; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount4+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount4+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount4+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount4+=1;
}
}
int pct4 = (int)Math.round((bCount4/(aCount4+bCount4))*100);
if (pct4 > 50) {
type.replace('J','P');
}
if (pct4 == 50) {
type.replace('J','X');
}
write.println(name + ": [" + pct1 + ", " + pct2 + ", " + pct3 + ", " + pct4 + "] = " + type);
write.close();
}
}
}

java.io.File does not have a hasNextLine() method. That's a method that exists in java.util.Scanner. Scanner has a constructor that takes a File object as an argument and allows it to use the specified file for input - you should probably try using that one:
Scanner s = new Scanner(new File(input));
EDIT:
That said, Scanner can be a bit of a performance killer (a bit?). It is often faster to use a BufferedReader and its readLine() method to read a single line into a String object and then parse the String manually. You can get a BufferedReader from a File with a bit of trickery:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

instead of using hasNextLine() method, which is non-existent in a File object, an alternative would be to access your file using an inputstream class like FileInputStream and wrapped inside a decorator class like BufferedReader, which would allow you to read its contents per line, using readLine() method....

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

Accessing indexes that may not exist Java [duplicate]

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

Reading file line by line and print

I'm trying to write a program that takes the file name from the user (for example: English), then opens this file and prints (9 questions) divided on (3 levels, each level has 3 questions), then opens another file (EnglishC) that contains the answers and then compares it with the correct answer. if correct grade++.
Output:
enter your choice:
1.English
2.Math
3.Science
java.io.FileNotFoundException: English.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at Generater.createQuestions(Generater.java:50)
at Generater.choose_subject_And_Level(Generater.java:41)
at Generater.main(Generater.java:139)
Source:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Generater {
static int levelNo = 1;
static int subjectName;
static int grade;
static String fileName;
static String fileNameCorrect;
static String ans;
static String correctAns;
public static void choose_subject_And_Level() {
// here the main will call this method to ask the user what subject to be tested in?
Scanner input = new Scanner(System.in);
System.out.println("enter your choice:\n 1.English\n2.Math\n3.Science ");
subjectName = input.nextInt();
switch (subjectName) {
case 1:
fileName = "English.txt";
fileNameCorrect = "EnglishC.txt";
break;
case 2:
fileName = "Math.txt";
fileNameCorrect = "MathC.txt";
break;
case 3:
fileName = "Science.txt";
fileNameCorrect = "SienceC.txt";
break;
}
createQuestions(fileName, fileNameCorrect, levelNo);
}
public static void createQuestions(String fileName, String fileNameCorrect,
int levelNo) {
Scanner input, input2;
try {
input = new Scanner(new File(fileName));
input2 = new Scanner(new File(fileNameCorrect));
input.useDelimiter("*");
FileInputStream fs = new FileInputStream(fileName);
FileInputStream fs2 = new FileInputStream(fileNameCorrect);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
BufferedReader br2 = new BufferedReader(new InputStreamReader(fs2));!
while (input.hasNext()) {
switch (levelNo) {
case 1:
for (int i = 1,k=1; i <= 3 ; i++,k++) {
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
correctAns = input2.next();
if (ans == correctAns) {
grade++;
}
}
break;
case 2:
for (int i = 4, k = 1; i <= 6; i++, k++) {
try {
for (int j = 1; j <= 3; j++) {
br.readLine();
correctAns = br2.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
if (ans == correctAns) {
grade++;
}
}
break;
case 3:
for (int i = 7, k = 1; i <= 9; i++, k++) {
try {
for (int j = 1; j <= 6 ; j++){
br.readLine();
correctAns = br2.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.printf("\nQ#\f: " + input.next() + "\n" , k);
ans = input.next();
correctAns = input2.next();
if (ans == correctAns) {
grade++;
}
}
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// the main
public static void main(String[] args) {
choose_subject_And_Level();
}
}
When java.io.FileNotFoundException is thrown it means the file that is supposed to be read/written is not present at the location specified. Look where you have the file on the filesystem and confirm that the file in question (English.txt) is present.
More info here: https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

Scanner will take user input but will not find the file

This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.

I desperately need help for file input/output in java

I need help about inputting using file (file name is inp2.dat) and outputting using file (file name is out2.dat) in the SAME PROGRAM. Do I use FileInputStream and FileOutputStream in the same class? Please help. Its outputting File Not Found.
import java.io.*;
class MBF
{
static String fileinp="inp2.dat";
public void main()
{
boolean EOF=false;
try
{
FileInputStream fr=new FileInputStream(fileinp);
DataInputStream dr=new DataInputStream(fr);
while(!EOF)
{
try
{
System.out.println("Enter no. of inputs:");
int n=dr.readInt();
int max=0;
for(int a=1;a<=n;a++)
{
System.out.println("Enter:");
int p=dr.readInt();
String str=dr.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i=0;i<p-2;i++)
{
char f=str.charAt(i);
char s=str.charAt(i+1);
char t=str.charAt(i+2);
if((f==s)&&(f==t))
max=max+1;
else
if(((f==s)&&(f!=t))||((s==t)&&(f!=t))||((f==t)&&(t!=s)))
max=max+2;
else
max=max+3;
}
max=0;
}
}
catch(EOFException el)
{
System.out.println("end of file");
EOF=true;
}
catch(IOException e)
{
System.err.println(e);
}
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
}
}
There are a few problems throughout. I've made some changes with comments:
class MBF
{
static String fileinp = "C:\\inp2.dat";
public static void main(String[] args) // main method signature was wrong
{
// this line doesn't need to be outside of main, and you aren't using your fileinp string
Scanner in = new Scanner(new File(fileinp));
// added your writer
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\out2.dat"));
System.out.println("Enter no. of inputs:");
int n = in.readInt();
//in.close(); I don't think you meant to do this here.
int max=0;
for(int a = 1; a <= n; a++)
{
System.out.println("Enter:");
// these were originally dr.read... dr is not a variable in scope here. I think you meant in
int p = in.readInt();
String str = in.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i = 0; i < p - 2; i++)
{
char f = str.charAt(i);
char s = str.charAt(i + 1);
char t = str.charAt(i + 2);
if ((f == s) && (f == t))
max=max+1;
else if (((f == s) && (f != t)) || ((s == t) && (f != t)) || ((f == t) && (t != s)))
max=max+2;
else
max=max+3;
}
out.write(max + "\n");
max=0;
}
in.close();
out.close();
}
}
Should do what you want.

Categories

Resources