Java Initializing Variable Error - java

I have an error that says I haven't initialized my firstline, secondLine, and thirdLine variables in the buffer.write(variable); lines with variable being firstLine, secondLine & thirdLine. This error didn't appear until I added while(number == null || number.equals("")) around the variable == JOptionPane.showInputDialog("Enter name"); lines in my code. Is there any way to handle this error while keeping my added code in?
import java.awt.Graphics;
import javax.swing.JOptionPane;
import java.io.*;
import java.io.FileWriter;
public class CreateData {
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null,
"this program writes payroll data",
"Welcome", JOptionPane.PLAIN_MESSAGE);
Write();
}
static void Write()
{
try {
String firstLine, secondLine, thirdLine, number = " ";
File check = new File("payroll.txt");
FileWriter file;
if(check.exists())
file = new FileWriter("payroll.txt", true);
else
file = new FileWriter("payroll.txt");
BufferedWriter buffer = new BufferedWriter(file);
int size, count = 1;
while(number == null || number.equals(""))
{
number = JOptionPane.showInputDialog("how many records?");
}
size = Integer.parseInt(number);
do {
while(number == null || number.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
while(number == null || number.equals(""))
{
secondLine = JOptionPane.showInputDialog("Enter hours");
}
while(number == null || number.equals(""))
{
thirdLine = JOptionPane.showInputDialog("Enter wage");
}
buffer.write(firstLine);//write firstLine variable to payroll.txt file
buffer.newLine();
buffer.write(secondLine);
buffer.newLine();
buffer.write(thirdLine);
buffer.newLine();
count++;
}while(count <= size);
buffer.close();//closes the data writing stream to payroll.txt file
JOptionPane.showMessageDialog(null, "data processed",
"Result", JOptionPane.PLAIN_MESSAGE );//display message "data processed"
System.exit(1);
}
catch (IOException e) { System.out.println(e); }
}
}

This line
String firstLine, secondLine, thirdLine, number = " ";
equals to
String firstLine;
String secondLine;
String thirdLine;
String number = " ";
So you need to initialize your firstLine, secondLine, thirdLine:
String firstLine = "";
String secondLine = "";
String thirdLine = "";
String number = " ";

Adding the while loop around the place where you set the variable means that if the condition is never met, the variables will not receive a value.
But those while loops are wrong as they are. In general, while loops should not have a condition that waits for something that is not changed inside them. Since number is a local variable, there is no other thread that will change it, and it doesn't change inside the loop itself:
while(number == null || number.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
I'm pretty sure you wanted to actually make this condition:
while(firstLine == null || firstLine.equals(""))
{
firstLine = JOptionPane.showInputDialog("Enter name");// prompts for input and displays "Enter Name"
}
So you should correct that. Nevertheless, the compiler may still not be happy with that, so you should, indeed, supply a default value when you declare the variable, and as the other answer told you, the declaration:
String firstLine, secondLine, thirdLine, number = " ";
Does not set all the variables to " " - only the number variable. You need to assign to each of them separately.
The value that you set should not be " " (a space). Because that doesn't meet either of the conditions (it's not null and it's not empty) so it will not go inside the loops, and you'll wonder why you're just getting spaces. You should set it to either null or an empty string.

Let me answer your question with a similar problem:
int x;
while(false) {
x = 10;
}
System.out.println(x);
Because there is no guarantee that you enter the while loop, there is therefore no guarantee that x is initialized.
The same problem occurs in your code. Even if you are logically convinced that you will enter the while loop, the compiler needs to be certain.
As such, please initialize your variables. This doesn't initialize them the way you think it does. It, infact, only initializes the last variable.
String firstLine, secondLine, thirdLine, number = " ";
Try this:
String firstLine, secondLine, thirdLine, number;
number = " ";
firstLine = null;
secondLine = null;
thirdLine = null;
You can also do this:
String firstLine, secondLine, thirdLine, number;
number = " ";
firstLine = secondLine = thirdLine = null;
Note that you don't have to initialize your variables to null: you could initialize them to any other String as well.

Just initialize the three variables to null..
String firstLine=null, secondLine=null, thirdLine=null;

Related

Best way to read CSV file and store (array, 2darray?) and print to screen in tabular format?

The thing i'm hoping to do is read a csv file with 6 rows and 6 columns in it using Java. I then need to print out each row and allow the user to select 1 option. Here is what I have, I know my code chooses 1 and prints it, but I don't know how to change it from printing one random row, to printing all 6 rows. Probably in an ArrayList or 2dArray?
package theContest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
public class theContest {
// The main() method
public static void main(String[] args) throws FileNotFoundException {
//
String fileName = "contest.csv";
File file = new File(fileName);
if (!file.isFile()) {
System.err.println("Cannot open file: " + fileName + ".");
System.exit(0);
}
//
int numContest = 0;
Scanner input = new Scanner(file);
while (input.hasNext()) {
input.nextLine();
numContest++;
}
input.close();
System.out.println("Total of " + numContest + " contestants.");
//
int winner = 0;
Random random = new Random();
winner = random.nextInt(numContest) + 1;
System.out.println("The winner is contestant number " + winner + ".");
//
String winnerDetails = "";
input = new Scanner(file);
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
input.close();
System.out.println("Winner is: " + winnerDetails);
//
String id = "";
String name = "";
String seats = "";
String trans = "";
String rate = "";
String price = "";
input = new Scanner(winnerDetails);
input.useDelimiter(",");
id = input.next();
name = input.next();
seats = input.next();
trans = input.next();
rate = input.next();
price = input.next();
input.close();
System.out.println("Details are:");
System.out.printf("%-5s : %s\n", "ID", id);
System.out.printf("%-5s : %s\n", "Name", name);
System.out.printf("%-5s : %s\n", "Seating", seats};
System.out.printf("%-5s : %s\n", "Transfer", trans};
System.out.printf("%-5s : %s\n", "Rate", rate};
System.out.printf("%-5s : %s\n", "Price", price};
}
}
Here:
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
Your file has N rows. The above code iterates all lines, and stores the result in a single variable. In each iteration, you overwrite what you put there before. So, what your code does is: it reads N lines, and throws away everything prior the last row.
In other words: if you have 6 lines, and you want to print all of them ... then that all your processing needs to be "part" of a loop, too.
For example, you could turn winnerDetails into an array of String, and then put each line in its own slot. Then you loop over the array, and print each slot.
And as you already know about ArrayList, best use that then. That also means: you need to read the file only once. Open the file, read each line, and push that into an ArrayList. Afterwards, you can do whatever you want with that list.
And note: that is actually the point you should start with. Dont solve your whole problem at once. Slice it into smaller parts. Like: reading data from CSV ... has nothing to do with later processing the lines and printing those. You can write code that just takes an ArrayList, processes those and prints stuff. Which you can ... test on its own, as you can hardcode such lists in your code.

Java while loop skips first iteration for user input

I am making a game and currently I need to set the names for the 'heroes'! This requires the player to enter a name for the heroes.
The thing is, when it asks for the name of hero 1 in the console, it just skips over and goes straight to hero 2.
If I use .next() instead of .nextLine(), it works, but it interpreted any names with a space in them as two different names!
Here is the code, I hope that make sense! Thanks all in advance :)
public void heroNames() //sets the name of heroes
{
int count = 1;
while (count <= numHeroes)
{
System.out.println("Enter a name for hero number " + count);
String name = scanner.nextLine();
if(heroNames.contains(name)) //bug needs to be fixed here - does not wait for user input for first hero name
{
System.out.println("You already have a hero with this name. Please choose another name!");
}
else
{
heroNames.add(name);
count++; //increases count by 1 to move to next hero
}
}
}
If you read numHeroes with Scanner.nextInt a newline character remains in its buffer and thus an empty string is returned by the following Scanner.nextLine, effectively resulting in a sequence of two consecutive Scanner.nextLine() to get the first hero name.
In the following code I suggest you read the number of heroes with Integer.parseInt(scanner.nextLine) and, as a matter of style, don't use a local variable count since it's implicitely bound to the size of the heroNames collection:
Scanner scanner = new Scanner(System.in);
List<String> heroNames = new ArrayList<>();
int numHeroes;
System.out.println("How many heroes do you want to play with?");
while (true) {
try {
numHeroes = Integer.parseInt(scanner.nextLine());
break;
} catch (NumberFormatException e) {
// continue
}
}
while (heroNames.size() < numHeroes) {
System.out.println("Type hero name ("
+ (numHeroes - heroNames.size()) + "/" + numHeroes + " missing):");
String name = scanner.nextLine();
if (heroNames.contains(name)) {
System.out.println(name + " already given. Type a different one:");
} else if (name != null && !name.isEmpty()) {
heroNames.add(name);
}
}
System.out.println("Hero names: " + heroNames);

Current If statement involving String

Essentially my assignment is supposed to take 2 words, calculate the smallest of the two which I have done, but now I need to reference the smallest word itself instead of the number. Which I believe requires an If statement, but I cannot get my String to initialize and the console gets picky when I end the program with the system.out.println command.
Scanner scan = new Scanner(system.In);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
Int pass1l = pass1.length();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
Int pass2l = pass2.length();
Int spassl = Math.min(pass1l,pass2l);
// problematic part here.
String spass;
If (pass1l > pass2l){ spass = pass2}
else if (pass1l < pass2l) {spass = pass1}
else if (pass1l == pass2l) {spass = null;};
Also the Else if statements come up as not statements and the first is an illegal start of an expression.
Then if I fix those I call spass with system.out and it says it's not initialized. I just started learning basic Java, I've used processing before but not for String related if statements, only integers.
You are almost there. the variable spass needs to be initialized as you are using if blocks without final else. Either you give spass="" or change final else if to else as below.
Scanner scan = new Scanner(System.in);
System.out.println(" Input first password ");
String pass1 = scan.nextLine();
System.out.println(" input second password ");
String pass2 = scan.nextLine();
// problematic part here.
String spass;
if (pass1.length() > pass2.length()) {
spass = pass2;
} else if (pass1.length() < pass2.length()) {
spass = pass1;
} else {
spass = null;
}
System.out.println("result: " + spass);
your problem is just a formating problem, if statements are formatet like this:
if(condition){
do_something;
}else if( second_condition ){
do_something_else;
}else{
alternative;
}
In your case it seems that you dont know where to set semicolons ;
You have to set semicolons inside the if block like this:
String spass;
If (pass1l > pass2l){
//Here semicolon
spass = pass2;
} else if (pass1l < pass2l) {
//Here semicolon
spass = pass1;
}else if (pass1l == pass2l) {
//Here semicolon
spass = null;
}
//No semicolon at the end of the if-else-statement

fName.substring out of bounds

public class Registration {
public static void main(String[] args) {
final String MY_DELIMITER = "','";
boolean tryAgain = true;
String fName = "";
String A = fName.substring(0,2);
String lName = "";
int lNameLength = lName.length();
String B = lName.substring(lNameLength-4,lNameLength);
String address = "";
String zip = "";
String C = zip.substring(0,5);
String age = "";
String D = age.substring(0,1);
String gender = "";
String race = "";
String regList = "";
Scanner myScanner = new Scanner(System.in);
boolean showList = false;
// Get input from the user until they type "q"
// For each input check for "q"
// if not q, append the input
// to the existing String + the delimiter
while(tryAgain)
{
System.out.println("Name: (q to quit)");
fName = myScanner.nextLine();
System.out.println("Last Name: (q to quit)");
lName = myScanner.nextLine();
System.out.println("Addess: ");
address = myScanner.nextLine();
System.out.println("Age: ");
age = myScanner.nextLine();
System.out.println("Gender: ");
gender = myScanner.nextLine();
System.out.println("Race: ");
race = myScanner.nextLine();
if(fName.equals("q"))
{
tryAgain = false;
}
else
{
// Append new name to the list using a delimiter
regList = fName + lName + "\n" + address + "\n" + age + "\n" + gender + "\n" + race + MY_DELIMITER;
}
} // end of while( )
System.out.println("Here is your registration:" + regList);
// Convert the String into an array, using the same delimiter
String[ ] regArray = regList.split(MY_DELIMITER);
// Ask the user if they want to display the contents of the array
// If "y" then display the list using a foreach loop
System.out.println("Would you like to see the registration from the Array? [y-n]");
fName = myScanner.nextLine( );
myScanner.close();
fName = fName.toLowerCase( );
showList = fName.equals("y")?true:false;
if(showList)
{
// Display the results using for each
System.out.println("Here is your registration from the array: ");
// Use a for each statement instead of the more complex for( ) loop
// for(int counter=0; counter < employeeArray.length; counter++)
for(String thisReg:regArray)
{
System.out.println(thisReg);
System.out.printf("USER ID: ", A + "-" + B + "-" + C + "-" + D);
}
} // end of if(showList)
}
}
I am trying to extract out the first 3 letters of the fName input, so I figured I could use fName.substring to do that, but it gives me this error.
Sorry I didn't add all of my code, to save time. Apparently it looked confusing. Any way so the fName input is the name of the user. Can it not be in that order?
Erm...your sequence of operations is suspect. Everywhere, actually.
Look at the following interaction:
String fName = "";
String A = fName.substring(0,2);
You declare an empty string, then immediately take the substring of it. Where are you getting the data for the substring from? There's nothing to substring here - the empty string has a length of zero.
You should be certain that you're putting data into your string before taking a substring of it. Using a Scanner would go a long way here.
Or better yet, moving your instance of myScanner at the top of main would make it much clearer as to where that's supposed to go, and how it's supposed to work.
Always check the length of string before substring anything. Especially when a user is giving you this variable.
You are trying to get a substring of an empty string.
String fName = "";
String A = fName.substring(0,2); // here fName is empty!!!
Change fName into some actual String and also check for length of the String before calling substring to make sure substring of the size you want exists.
String fName = "somestring";
if(fName.length() >= 2) {
String A = fName.substring(0,2);
System.out.println(A); // prints out "so"
}
That is the case with all of your other Strings as well.

Java input keeps being empty?

This is a simple question selection, and then answer program:
import java.util.Scanner;
public class Mains {
static Scanner console = new Scanner(System.in);
static Tof tof = new Tof();
static int Ievel = 0;
static int Input = 0;
static boolean GAME = true;
static boolean AT_START = true;
static boolean IN_QUESTION = false;
public static void main (String[] args) {
while (GAME) {
String InputS = "";
if (AT_START) {
System.out.println("Welcome to the game! Please select a number from 1 to 10.");
AT_START = false;
}
if (!IN_QUESTION)
Input = console.nextInt();
if (Input == -1) {
GAME = false;
console.close();
} else {
String question = tof.getQuestion(Input);
String answer = tof.getAnswer(Input);
System.out.println(question);
IN_QUESTION = true;
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS != console.nextLine()) {
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
}
}
}
}
}
Problem:
When entering the IN_QUESTION loop, and writing a answer, it will always be incorrect.
That's because the InputS variable is ALWAYS empty, no matter what, while it has console.nextLine() set on it.
Why is it empty? How do I fix this?
In-case you need the other class Tof: http://pastebin.com/Fn5HEpL2
nextInt doesn't get the line terminator after the integer and you're reading from the console twice (the second time being in the if-statement).
So if you enter:
123
apple
The following happens:
Input gets assigned a value of 123
InputS gets assigned an empty string
InputS gets compared against apple and it is not equal (from InputS != console.nextLine() - I'm not sure why it's there)
You can fix it by:
Putting a console.nextLine(); after console.nextInt();
OR
Use Input = Integer.parseInt(console.nextLine()) instead of nextInt
Removing this - if (InputS != console.nextLine())
You're reading from the console twice. This should work:
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
The problem is that the new line character was not read by the nextInt() method so it remain in the scanner buffer and when the next time you called nextLine() that character was printed first.
This is how to fix the issue:
//empty the newline character from the scanner
console.nextLine();
while (IN_QUESTION) {
InputS= console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
You call console.nextLine twice. This means that you read a line that you'll check, and another you won't. This is probably not what you are after. Also note that your initial call of nextInt will not consume the newline you pressed after entering the number. You need a nextLine right after that, but before the main loop.
Some general remarks:
uppercase names are only for constants, so your variables should be lowercase;
you should really be using local variables instead of static ones. Right now this isn't hurting you, but it soon could.

Categories

Resources