variable may not have been initialized... how to increase scope? [duplicate] - java

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

Related

why wont my while loop break [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I can not figure out why my while loop won't break and it just keeps running I have tries making Lc 10 and I tried return but nothing will end the loop.
import java.util.Scanner;
public class BirthdayReminder
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String[] BDay = new String[10];
String[] friend = new String[10];
int Lc = 0;
String i;
while(Lc < 10) {
System.out.println("enter a friends name or zzz to quit");
i = input.nextLine();
if(i == "zzz") {
break;
}
else if(i != "zzz"){
friend[Lc] = i;
System.out.println("enter their birthday.");
i = input.nextLine();
BDay[Lc] = i;
Lc++;
return;
}
}
System.out.println("hi");
}
}
You need to check string equality using equals(), not ==. Neither block of code inside the if is getting entered, so Lc is never incremented.

Why are all the numbers print out when I want only the largest?

I want to display only the largest number (price) from a text file. Every time it shows me the whole numbers instead of the highest value. I've been using a lot of methods like the for loop and others. But I think the problem is about something else.
package practice;
import java.util.Scanner;
import java.io.*;
public class Practice {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String fileName = "C:\\Users\\Work\\Desktop\\Prices.txt";
File inFile = new File(fileName);
Scanner inPut = new Scanner(inFile);
String line = inPut.nextLine();
while(inPut.hasNext()){
String[] Company = new String[3];
int[] Price = new int[3];
int[] Quality = new int[3];
int count = 0;
count++;
Company[count] = inPut.next();
Price[count] = inPut.nextInt();
Quality[count] = inPut.nextInt();
int HighestPrice = Price[0];
int counter = 1;
while(counter<Price.length-1){
if(Price[counter]>HighestPrice){
HighestPrice = Price[counter];
int hi = counter;
}
counter++;
}
System.out.println(HighestPrice);
}
}
}
Close the loop body after taking input in the arrays.
You should create your arrays outside the loop as their reference gets lost each time you recreate them.
String line = inPut.nextLine();
String[] Company = new String[3];
int[] Price = new int[3];
int[] Quality = new int[3];
int count = 0;
while(inPut.hasNext()){
Company[count] = inPut.next();
Price[count] = inPut.nextInt();
Quality[count] = inPut.nextInt();
count++;
}
You put the code to find the largest number inside the while(inPut.hasNext()){ Block. because of that the while(counter<Price.length-1){ loop gets executed on every line and therefore only has one value to handle, which of course is everytime the largest.
Skip the second loop and only execute the code inside, put the System.out.println(HighestPrice); outside the outer loop and it should work.

Reading a file and storing names and numbers in two arrays

I'm working on a program that reads a file and stores the names and scores in two separate arrays, but I'm struggling. This is what I have so far.
I created an array for names called names, but I'm confused how I would copy the names into each index of the array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFileSplit {
public static void main(String[] args) {
File file = new File("NamesScore.txt");
String[] names = new String[100];
int[] scores = new int[100];
int i;
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] words = line.split("\t");
for (String word: words) {
System.out.println(word);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
My text file is:
John James 60
Kim Parker 80
Peter Dull 70
Bruce Time 20
Steve Dam 90
First, you will want to initialize i to 0 when you declare it:
int i = 0;
Then, after splitting the line you can pull the data out of the String[] and put it in your names and scores arrays:
String [] words = line.split("\t");
// The first element in 'words' is the name
names[i] = words[0];
// The second element in 'words' is a score, but it is a String so we have
// to convert it to an integer before storing it
scores[i] = Integer.parseInt(words[1], 10);
// Increment 'i' before moving on to the next line in our file
i++;
Don't forget to increment i as shown above.
There is some error checking that I have glossed over. You will probably want to check that words has a length of 2 after your call to split(). Also keep in mind that Integer.parseInt() can throw a NumberFormatException if it is not able to parse the data in the scores column as an integer.
I have tried to correct your code and provided inline comments where I felt you have went wrong. Actually you were close to the solution. Try to figure out what you are getting as an output after a line of code like
String[] words = line.split("\t");
This line will give two String(as it will split the line in your file which has only one tab separated name and score). And you can try to debug by yourself. Like simply printing the value. for example
System.out.println(words[0]);
This will help you progress further.
Hope this helps.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TwoArrays {
public static void main(String[] args) {
File file = new File("C:\\test\\textTest.txt");
String[] names = new String[100];
int[] scores = new int[100];
int i = 0;
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] words = line.split("\t");
names[i] = words[0]; // storing value in the first array
scores[i] = Integer.parseInt(words[1]); // storing value in the
// second array
i++;
}
/*
* This piece of code will give unnecessary values as you have
* selected an array of size greater than the values in the file for
*
* for(String name: names) {
* System.out.println("Name:- "+name);
* }
* for(int score: scores) {
* System.out.println("Score:- "+score);
* }
*/
// Better use the below way, here i am restricting the iteration till i
// i is actually the count of lines your file have.
for (int j = 0; j < i; j++) {
System.out.println("Name:- " + names[j] + "\t" + "Score:- " + scores[j]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
what about
int l = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] words = line.split("\t");
names[l] = words[0];
scores[l] = Integer.parseInt(words[1]);
System.out.println(l + " - name: " + names[l] + ", score: " + scores[l]);
l++;
}

Arrays in Java, getting 'array required, but arrayList<string> found' [duplicate]

This question already has answers here:
Get specific ArrayList item
(8 answers)
Closed 7 years ago.
The code is trying to take String entries, add them to an array and then stop when no text is written (user just presses enter). Then it is meant to display all of the String items in the array thus far on new lines.
The error in my title is coming up on my if query, and I'm additionally getting error's reading the value 'x' in the for loop as a variable (cannot find symbol).
Can anyone help me out
import java.util.Scanner;
import java.util.ArrayList;
public class FirstPart {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty[i].isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
}
}
The error message is telling you exactly what is wrong. You've got an ArrayList and are trying to treat it as if it were an array. It isn't, and you can't use array indices, [i] on it. Instead use the get(...) method as any tutorial will tell you (and which I strongly recommend that you read -- Google can help you find one).
Your tillEmpty is not an array but an arraylist...you have to use tillEmpty.get(i).isEmpty instead of tillEmpty[i]
You missed int in your for loop:
for (int x = 0; x < tillEmpty.size; x++){
System.out.println(tillEmpty.get(x));
}
You are accessing list as Array, use below code, this should work:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> tillEmpty = new ArrayList<String>();
int i = 0;
while (true) {
System.out.print("Type a word: ");
tillEmpty.add(reader.nextLine());
if (tillEmpty.isEmpty()) {
break;
} else {
i++;
}
}
System.out.println("You typed the following words: ");
for (int x = 0; x < tillEmpty.size(); x++){
System.out.println(tillEmpty.get(x));
}
}

Error: The local variable jars may not have been initialized

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?

Categories

Resources