Further down it keeps saying the tow local variable cant be initialized when they are. Cant seem to find the problem
import java.io.*;
import java.util.Scanner; //Scanner method
public class Popcorn1 {
public static void main(String args[]) throws FileNotFoundException{
printHeader();
File file;
do {
Scanner in = new Scanner (System.in);
System.out.println("Enter the the file name");
String filename = in.next();
file = new File(filename);
} while(!file.exists());
FileReader inputFile = new FileReader (file);
Scanner inFile = new Scanner(inputFile);
System.out.println(" PopCorn Co-op");
System.out.println(" Production in Hundreds");
System.out.println(" of Pint Jars Per Acre");
System.out.println(" 1 2 3 4 5 6");
System.out.println("Farm Name ---|---|---|---|---|---|");
System.out.println();
// Printing out title and table header for reader to easily read data
String errorMSG = " ";
while (inFile.hasNextLine()) {
String inputLine = inFile.nextLine();
//System.out.print(inputLine);
int position;
String name;
int jars;
double acres;
position = inputLine.indexOf(','); //Get the Location of the comma to use as a delimiter
name = inputLine.substring(0,position); //Everything to the left of the comma is the farm name
System.out.printf("%-31s", name);
inputLine = inputLine.substring(position + 2,inputLine.length()); //rest of the string
Scanner line = new Scanner(inputLine);
if(line.hasNextDouble())
acres = line.nextDouble();
else
errorMSG += "There is missing data";
if(line.hasNextInt())
jars = line.nextInt();
else
errorMSG += "There is missing data";
int starsConversion =(int)(jars/acres/25); **<-------- problem is here**
for (int i = 1; i < starsConversion; i++) {
if( i == 20)
System.out.print("#");
else
System.out.print("*");
}
if (starsConversion < 20) {
for (int i = 1; i < (21 - starsConversion); i++) {
System.out.print(" ");
}
System.out.print("|");}
System.out.println(); //go to the next line
}
System.out.println(errorMSG);
}
}
There is an execution path where jars was never initialized, specifically, if line.hasNextInt() is false.
To use it, you must make sure jars is always initialized to something. You can initialize it to say 0 before the if.
What happens if if(line.hasNextInt()) is false on the first run?
Related
I am trying to read from a text file that have names and phone numbers that can also have other text files in it (including it self)
myBook.txt:
7
name1 123-456-7890
name2 098-765-4321
name3 135-792-4680
name4 246-801-3579
PHONEBOOK-FILE myBook2.txt
name5 147-025-8369
name6 150-263-7495
myBook2.txt:
1
Name7 000-222-3332
The first line is the number of items in the file, then it has PHONEBOOK-FILE to signify another file.
I cannot use arrays, I cannot change myBook.txt, I cannot use try / catch, and I have to use recursion
This is the code I have:
import java.util.*;
import java.io.*;
public class Phonebook
{
private boolean DEBUG = true;
private Scanner scan;
private Scanner input;
private File file;
private File holder;
private String query;
private boolean bottomOut;
private int nameCount;
private String fileNameHold;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file, 0));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName, int level)throws IOException
{
scan = new Scanner(fileName);
//Grabs item count fom begining of file
//if(!bottomOut)
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
debug("file: " +file);
debug("line: " + line);
debug("nameCount: " + nameCount);
if(line.toLowerCase().contains(query.toLowerCase()))
{
return line;
}
//Recursion is used to searth through linked files
else if(line.contains("PHONEBOOK-FILE"))
{
//System.out.println("Sanity Check");
holder = new File(line.replace("PHONEBOOK-FILE ", ""));
if(level < 2 || (level > 0 && bottomOut))
return doWork(query, holder, ++level);
else if(level >= 2 && !bottomOut)
bottomOut = true;
else
return "not found (REC)";
}
}
return "not found";
}
private void debug(String stuff)
{
if(DEBUG)
System.out.println("[[--DEBUG--]] " + stuff);
}
}
I assume the issue is in doWork but I could be wrong. What it is doing is it recurses through the file until it hits a specified bottom where if it hasn't found the name it should break out of the recursion and continue passed the PHONEBOOK-FILE line.
Currently if you search for a name passed that line if returns not found. It doesn't seem to be coming out of the recursion.
As you can probably tell I an not great with this.
Thanks for any help.
For each line in your file, you are going to compute a value. Either not found, or a line of your phonebook. If you get a line, you can break out of the loop. Either way, after the loop you return the value: either the line you got or not found;
What is trickier is how you compute a line which references another phonebook, the answer is that you just call your method with that phonebook. That's the recursion part.
import java.util.*;
import java.io.*;
public class Phonebook
{
private Scanner input;
private File file;
private String query;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName)throws IOException
{
Scanner scan = new Scanner(fileName);
int nameCount;
File recurFile;
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
String value = "Not found";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
// if the line is a file, then the value of that line
// is the result to your function applied to that new file
if(line.contains("PHONEBOOK-FILE")) {
recurFile = new File(line.replace("PHONEBOOK-FILE ", ""));
line = doWork(query, holder, ++level);
}
// the file will either return Not found or
// a line corresponding to your query
if(line.toLowerCase().contains(query.toLowerCase()))
{
// Your line is correct. The function doesn't care where it comes from
value = line;
break;
}
}
return value;
}
}
This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 8 years ago.
I keep getting an error:
error: variable aryResponse might not have been initialized
if(answers.charAt(i) == aryResponse[i].charAt(i))
I think it's because I'm initializing the variable within a while loop. However I dont' know how to fix this?
How do I increase the scope of the variable, while I need it to be initiliazed to a value given by the loop?
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class ExamAnalysis
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Exam Analysis. Let's begin ...");
System.out.println();
System.out.println();
System.out.print("Please type the correct answers to the exam questions, one right af$
String answers = in.nextLine();
int answersLength = answers.length();
System.out.println();
System.out.print("What is the name of the file containing each student's responses to$
String temp = in.nextLine();
File file = new File(temp);
Scanner in2 = new Scanner(file);
/*Code Relevant To This Question Begins Here */
int lines = 0;
String[] aryResponse;
while (in2.hasNextLine())
{
String line = in2.nextLine();
aryResponse = new String[lines];
aryResponse[lines] = line;
System.out.println("Student #" + lines + "'s responses: " + line);
lines++;
}
System.out.println("We have reached \"end of file!\"");
System.out.println();
System.out.println("Thank you for the data on " + lines + " students. Here's the ana$
int[] aryCorrect = new int[lines];
for (int i = 0; i < answersLength; i++)
{
if(answers.charAt(i) == aryResponse[i].charAt(i))
{
aryCorrect[i] ++;
}
}
}
}
Change this
String[] aryResponse;
to
String[] aryResponse = null;
And remember to test that aryResponse isn't null,
if (aryResponse != null) {
for (int i = 0; i < answersLength; i++) {
if (answers.charAt(i) == aryResponse[i].charAt(i)) { // what is this testing?
aryCorrect[i]++;
}
}
}
This is necessary because
while (in2.hasNextLine()) { // <-- might not be true
// so this doesn't happen.
}
If I understood your code, aryResponse has a number of lines, if the variable was never initialized inside the while loop it means you have 0 lines, so, it would be enough to do two things:
1- initialize aryresponse to null:
String[] aryResponse = null;
2 - add this line at the end of your while loop:
if(aryResponse == null) aryResponse = new String[0];
Just initialize it outside the loop
String[] aryResponse=null;
Now allocate memory to aryResponse inside loop
aryResponse = new String[n]; //n is the size of array
I currently have some code that can take console input, but I need to make it recognize a list of names and test scores.
Code that I currently have:
import java.io.*;
import utils.io.*;
class student
{
String name;
double sResult[];
int result;
double sum;
void getdata()
{
System.out.println("Enter name:");
Name = (string) system.in.read();
int index=0;
for (int counter=1; counter<=5; counter++)
{
System.out.println("Enter result for subject"+counter+":");
sResult[count] = (double) system.in.read();
}
}
public static void CalculateAverage()
{
sum = 0;
for (int i=1;i<=5;i++)
{
sum += sResult[i];
}
return (int) Math.round(sum/(values.length-1));
}
Public static char calculateGrade()
{
result=sum;
if (result>=0 && result <=59)
{
return ('F');
}
else
if (result >=60 && result<=69)
{
return ('E');
}
else
if (result>=0 && result<79)
{
return ('D');
}
else
if (result >=70 && result<=79)
{
return ('C');
}
else
if (result>=80 && result<=89)
{
return ('B');
}
else
if (result>=90 && result<=100)
{
return ('A');
}
}
}
and class test
public class test
{
public static void main(String[] args)
{
Student std;
do
{
std=new Student();
std.getdata();
System.out.println("Student Name:"+std.Name);
System.out.println("Average for"+std.Name+" "+"is:"+std.average());
System.out.println("Grade for"+std.Name+" "+"is:"+std.gradecal());
System.out.println("Want to continue (1-Yes,2-No");
}
while(System.in.read()==1);
}
The text document format is name score1 score2 score3 score4 score5
I only need help figuring out how to import the values, and then I can probably figure out how to rewrite the .txt using PrintWriter.
Thanks in advance for any help!
Here's how you do it with Scanner.
Scanner inputFile = new Scanner(new File("inputfile.txt"));
while(inputFile.hasNext()){ //if there is still something to read
String name = inputFile.next();
int score1 = inputFile.nextInt();
....
int score5 = inputFile.nextInt();
//Do something here with the scores
inputFile.next(); //Read the new line character and prepare for the next iteration
}
For writing back to file, you can check Davy's answer and use a Buffered Writer. Note that the write() method works just like System.out.println() but you need to print \n on your own to go to the new line.
Firstly, you should not have variable names starting with a capital, namely:
string Name;
Only class names should start with a capital.
Also, I'm not even sure if your code compiles. Everywhere you have system.out.println should be System.out.println. Notice that System is a class, so the first letter is a capital
To read data, you can use BufferedReader and to write, you can use BufferedWriter.
Usage:
BufferedReader in = new BufferedReader(new FileReader("FileName.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("OutputFileName.txt"));
in.readLine(); //This reads a single line from the text file
out.write("Your Output Text");
in.close(); // Closes the file input stream
out.close(); // Closes the file output stream
Since you are reading in the format:
name score1 score2 score3 score4 score5
you can use the some String functions to get each field.
String inputLine = in.readLine();
String [] fields = inputLine.split(" "); // Splits at the space
System.out.println(fields[0]); //prints out name
System.out.println(fields[1]); //print out score1
...
public static void main(String... args) throws IOException {
Scanner s = new Scanner(new BufferedReader(new FileReader("textfile.txt")));
while(s.hasNext()){
Student student = new Student(s.next(), s.nextDouble(), s.nextDouble(),
s.nextDouble(), s.nextDouble(), s.nextDouble() ));
// Do something with student
s.next() // consume endline
}
}
The goal of this code is to read a file and add numbers to the end of every {(curly bracket) but the file does not output each line like it does in the file but it out puts it into one entire line. where do I put a System.out.println statement. I tried every where and it keeps repeating it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
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();
}
}
where do I put a System.out.println statement
The entire output is built in a single string that is not printed until the end, so adding System.out.println statements in the line loop won't help. You can add line breaks to the string by doing:
out += "\n";
Or, at the end of the body of your line loop, print the current line, and reset the buffer for the next line:
System.out.println(out);
out = "";
Using a String for the output buffer is not efficient by the way. String is immutable, so every + statement is copying and duplicating all of the previous characters to create a new object, every time. Consider declaring out as a StringBuilder rather than a String. Then you can add to it with the .append() method and it will not copy all the text every time because a StringBuilder is mutable.
This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 3 years ago.
Currently I have an error - '.class' expected - on line 40. Any help is hugely appreciated.
import java.io.*; // For File class and FileNotFoundException
import java.util.Scanner; //For the Scanner class
import javax.swing.JOptionPane; // For the JOptionPane class
/**
* Write a description of class PartB here.
*
* #Hubble, Kieran
* #Version 0.1
*/
public class PartB
{
public static void main(String[] args) throws FileNotFoundException
{
File file; //for file input
Scanner inputFile; //for file input
String fileName; //to hold a file name
String paragraph; //to extract the letter frequencies
//get a file name from the user.
fileName = JOptionPane.showInputDialog("enter " + " the name of the file");
//attempt to open the file.
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null, "the file was found.");
// read the input file, processing data one line at a time
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println(str);
}
//create an Output file
PrintWriter outputFile = new PrintWriter("crackedcode.txt");
while(paragraph.length() > 0)
// error is occurring on the next line (line 40)
int[]; letterCount = new int[26];
for (int count = 0; count < paragraph.length; count++) {
String current = paragraph[count];
char[] letters = current.toCharArray();
}
for (int count2 = 0; count2 < letters.length; count2++) { char lett = letters[count2]; if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
// close the input file
inputFile.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "file not found.");
}
JOptionPane.showMessageDialog(null, "done.");
System.exit(0); //terminate program
}
}
Remove the semicolon
int[]; letterCount = new int[26];
should be
int[] letterCount = new int[26];
Also, You need to wrap the block of the while (from the line above it) with {}