Java - Array outputing null - java

My program is supposed to output labels. All of the input works when I run it but the output is wrong and all that it outputs is null, for every part of the label except for the box number.
import javax.swing.JOptionPane;
public class MailOrderpractice {
static String nameAddressArray[] = new String[7];
public static void main(String[] args) {
// declare variables
String nameAddressArray[] = new String[7];
String numBoxesInput;
int numBoxes;
String enterAnother = "Y";
int counter;
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
// begin outer loop logic that determines when user is finished entering mail orders
while (enterAnother.equalsIgnoreCase("Y")) {
counter = 1;
// begin the inner loop to display a label and increment the counter
while (counter <= numBoxes) {
System.out.println(nameAddressArray[0] + " " + nameAddressArray[1] + " " + nameAddressArray[2]);
System.out.println(nameAddressArray[3]);
System.out.println(nameAddressArray[4] + ", " + nameAddressArray[5] + " " + nameAddressArray[6]);
System.out.println("Box " + counter + " of " + numBoxes);
System.out.println();
counter = counter + 1;
}
enterAnother = " "; // initialize the variable to something other than "Y" before sending the prompt
enterAnother = JOptionPane.showInputDialog("Do you want to produce more labels? Y or N");
while (!enterAnother.equalsIgnoreCase("Y") && !enterAnother.equalsIgnoreCase("N")) {
enterAnother = JOptionPane.showInputDialog(null, "Invalid Response. Please enter Y or N.",
"DATA ENTRY ERROR", JOptionPane.ERROR_MESSAGE);
} // end while
if (enterAnother.equalsIgnoreCase("Y")) {
getLabelData();
numBoxesInput = JOptionPane.showInputDialog("Enter number of boxes in the order:");
numBoxes = Integer.parseInt(numBoxesInput);
} // end if
} // end while
System.exit(0);
}
public static void getLabelData() {
nameAddressArray[0] = JOptionPane.showInputDialog("Enter title (Mr., Ms., Dr., etc.): ");
nameAddressArray[1] = JOptionPane.showInputDialog("Enter first name: ");
nameAddressArray[2] = JOptionPane.showInputDialog("Enter lastname: ");
nameAddressArray[3] = JOptionPane.showInputDialog("Enter street address: ");
nameAddressArray[4] = JOptionPane.showInputDialog("Enter city: ");
nameAddressArray[5] = JOptionPane.showInputDialog("Enter state (IL, MO, etc.): ");
nameAddressArray[6] = JOptionPane.showInputDialog("Enter zip (e.g., 62025): ");
}

The array nameAddressArray is declared twice. You have a static field
static String nameAddressArray[] = new String[7];
You also have a local variable with the same name in the main method.
String nameAddressArray[] = new String[7];
Your main method is putting values into the second array, whereas your getLabelData method is using the values from the static field, and these are all the initial value (null).
One way to solve this problem is to just get rid of the local variable. Then both parts of the code will use the same array.
Alternatively, you could get rid of the static field, and pass the array as a parameter to the getLabelData method. This is probably a better solution, as mutable static fields are generally not a good idea.

you just need to comment this line into Main method(),
// String nameAddressArray[] = new String[7];

Related

Errors in Java check integer is inputted

I know that the question has been asked but I tried to apply what I saw here and got an error.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
boolean is_int = false;
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) {
// If the input isn't an int, the loop is supposed to run
// until an int is input.
get_input.hasNextInt();
year_of_birth = get_input.nextInt();
}
//year_of_birth = get_input.nextInt();
System.out.println("Enter the current year");
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();
}
}
Without the loop, everything works fine. What is wrong in my code? To be clear, I'm trying to ask for an input until the input can be validated as an integer.
Thanks a lot in advance.
If you would like to skip invalid non-int values, your loop should look like this:
while (!get_input.hasNextInt()) {
// skip invalid input
get_input.next();
}
// here scanner contains good int value
year_of_birth = get_input.nextInt();
This works for me if i understood you correctly. You need to keep checking what value has the scanner, so you need to keep advancind through the scanner while the value is not an integer:
Scanner get_input = new Scanner(System.in);
System.out.println("Enter your name ");
String name = get_input.nextLine();
int year_of_birth = 0;
System.out.println("Enter your year of birth");
while (!get_input.hasNextInt()) { //check if it is not integer
System.out.println("Enter your year of birth"); // ask again
get_input.next(); //advance through the buffer
}
year_of_birth = get_input.nextInt(); //here you get an integer value
int current_year=get_input.nextInt();
int age = current_year-year_of_birth;
System.out.println("Your name is " + name + " and you are " + age + " year old.");
get_input.close();

User Input from Class to Main Class in Java

I'm trying to create a program that (1) prompts for a user's full name and then generates a username; (2) prompts for a number and then determines if the number is odd or even. I wrote out the code for the username and odd/even classes and would like to call them from the main class. However, when called from the main class, the username method prompts the user twice before generating the username and the odd/even method doesn't actually determine if the number the user inputted is odd/even. When I remove the scanner object from the username class, I get a out of bounds compilation error so I'm forced to put it back in just so the program will run. Should I be using return statements?
Username
/**
* Class to generate the username based on user's first name and randomly generated numbers
*/
public void username()
{
Scanner inputReader = new Scanner(System.in);
String fullName = inputReader.nextLine();
// create random object and variable to store it in
Random randomizer = new Random();
int randomNumber = randomizer.nextInt(1000);
// create variable to store lowercase username
String lowercase = (fullName.toLowerCase());
// create string variable to format username to first three characters in lowercase
String firstThreeLetters = (lowercase.substring(0, 3));
// concatenate lowercase characters and random number
String usernameFinal = (firstThreeLetters + randomNumber);
// print out final username
System.out.println("Your username is " + usernameFinal);
}
Odd/even
/**
* Class to determine if a user inputted value is odd or even
*/
public void OddEven1()
{
Scanner inputReader = new Scanner(System.in);
int userInteger = 0;
// if/else to determine if number is odd or even
if (userInteger % 2 == 0)
{
System.out.println(userInteger + " is an even number.");
}
else
{
System.out.println(userInteger + " is an odd number.");
}
}
Main method
{
/**
* This class holds the main method through which all other classes are run.
*/
public static void main(String[] args)
{
// create objects
Username usernameGenerator = new Username();
OddEven oddeven = new OddEven();
Scanner inputReader = new Scanner(System.in);
// prompt for real name and print username
System.out.print("Name: ");
String fullName = inputReader.nextLine();
usernameGenerator.username();
// prompt for number
System.out.print("Give me a number: ");
// variable to store value
int userInteger = inputReader.nextInt();
oddeven.OddEven1();
}
Output:
1 - You request user's name twice, one in here
String fullName = inputReader.nextLine();
And one in here
Scanner inputReader = new Scanner(System.in);
String fullName = inputReader.nextLine();
I would recommend keeping the first method and pass fullName to the username() function. As an example:
/**
* Class to generate the username based on user's first name and
randomly generated numbers
*/
public void username(fullName)
{
// create random object and variable to store it in
Random randomizer = new Random();
int randomNumber = randomizer.nextInt(1000);
// create variable to store lowercase username
String lowercase = (fullName.toLowerCase());
// create string variable to format username to first three characters in lowercase
String firstThreeLetters = (lowercase.substring(0, 3));
// concatenate lowercase characters and random number
String usernameFinal = (firstThreeLetters + randomNumber);
// print out final username
System.out.println("Your username is " + usernameFinal);
}
2 - You do the same in the second function OddEven1() . I would recommend passing a parameter to it too. As an exmaple:
public void OddEven1(number)
{
int userInteger = number;
// if/else to determine if number is odd or even
if (userInteger % 2 == 0)
{
System.out.println(userInteger + " is an even number.");
}
else
{
System.out.println(userInteger + " is an odd number.");
}
}
3 - So your main function becomes:
public static void main(String[] args)
{
// create objects
Username usernameGenerator = new Username();
OddEven oddeven = new OddEven();
Scanner inputReader = new Scanner(System.in);
// prompt for real name and print username
System.out.print("Name: ");
String fullName = inputReader.nextLine();
usernameGenerator.username(fullName);
// prompt for number
System.out.print("Give me a number: ");
// variable to store value
int userInteger = inputReader.nextInt();
oddeven.OddEven1(userInteger);
}
You should change your code like below
inside main method
System.out.print("Give me a number: ");
// variable to store value
int userInteger = inputReader.nextInt();
oddeven.OddEven1(userInteger );
Odd/even
public void OddEven1(int userInteger )
{
// if/else to determine if number is odd or even
if (userInteger % 2 == 0)
{
System.out.println(userInteger + " is an even number.");
}
else
{
System.out.println(userInteger + " is an odd number.");
}
}
Now lets discuss about username. You have already captured the username from your main method. So you dont need to get it from user again.
String fullName = inputReader.nextLine();
usernameGenerator.username(fullName );
public void username(String fullName )
{
//Your logic
}

How to aggregate values stored inside an array in java

I am creating a simple games score report generator program which takes input and turns it into a .txt file. It takes a name, a game name, an achievement score and minutes played and I want to be able to tally up the amount of games input, add up the achievement score and also add up the minutes (and convert to hours).
This is an example of how my output to .txt looks at the moment -
This is an example of how I would like an output to look -
How do I aggregate data that was input into the console and stored in an array to get results that I want?
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
writer.println();
writer.close();
Source code
package JavaProject;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.nio.file.*;
public class JavaProject {
private static final int minutesPlayed = 0;
private static char[] input;
public static void main(String[] args) {
//variables
int hrs = minutesPlayed * 60;
int mins;
String gamerName, gamerReport = null;
int gameCount;
int errorCount;
//Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
int[] minutesPlayed = new int [100];
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
//formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
//User enters either their name or quit. Entering a name will move on to next part
for ( ; ; )
{
System.out.print("Enter your Name.");
System.out.println(" ");
gamerName = Scan.nextLine();
for(int b = 1; b < 99; b++ ) { //this is making the code loop 100 times
//user is given an example of input format
System.out.println(" ");
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println("FALSE DATA FORMAT WILL CAUSE ERROR");
System.out.println(" ");
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport; // an array of string
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
return;
}
splitUpReport = gamerReport.split(":");
int i = 0;
//copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
//output to file using a PrintWriter using a FileOutPutStream with append set to true within the printwriter constructor
//
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
//writer.println("Games Played : " + minutesPlayed);
writer.close();
} catch (IOException e)
{
System.err.println("You have made an error with data input");
}
}
System.out.println("You have quit!");
}
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
So I am assuming that your array data structure looks like this:
Object[] report = new Object[] {new String(), new Integer(), new Integer()}
where the first entry is the game name, the second is the score, and the third is the time played.
I would suggest that you bundle this data into its own object instead of tracking every 3 positions in an array. Try:
public class Game
{
private String name; public String getName() { return name; }
private int score; public int getScore() { return score; }
private int minutesPlayed; public int getMinutesPlayed() { return minutesPlayed; }
public Game(String name, int score, int minutesPlayed)
{
this.name = name;
this.score = score;
this.minutesPlayed = minutesPlayed
}
#Override
public String toString()
{
return "Game: " + name + ", score= " + score + ", minutes played= " + minutesPlayed);
}
}
You can then use this object to represent game data and hold and array of these objects like this:
Game[] games = new Game[]{
new Game("Game 1", 52, 89),
new Game("Game 2", 57, 58),
new Game("Game 3", 67, 86)
};
This array allows us to access each game as a single entity; for example games[0] would get the reference to the 1st game object in the array. These games can have their data accessed by calling the "getters" for the 3 fields contained in the Game object. games[0].getName() would return the name for the first Game object; likewise, games[0].getMinutesPlayed() would return the minutes played for the first game.
Since we overrode the toString method offered to all classes from java's object class to output a string of the data desired in the way your first file I/O was structured. You can call writer.println(games[i]) where i is and index in your array of games to write the data for a individual game.
To concatenate this data into the output you desired. We can do the following:
// get the number of games played
int gamesPlayed = games.length;
// get the raw data on score and time
int totalScore = 0;
int totalMinutesPlayed = 0;
for(int i = 0; i < games.length; i++)
{
totalScore += games[i].getScore();
totalMinutesPlayed += games[i].getMinutesPlayed;
}
// compile the output string
String output = "Games Played: " + gamesPlayed
+ "\n\nTotal Achievement: " + totalScore
+ "\n\nTotal Time: " + totalMinutesPlayed
+ " (" + totalMinutesPlayed / 60
+ " hours and " + totalMinutesPlayed % 60
+ " minutes).";
// write the string to the file
writer.println(output);
Suggestion:
Create a model of the data as a new simple class:
public class GameReportModel{
String gamename = null;
String username = null;
int score = 0;
int minutesplayed = 0;
}
Now you can use an ArrayList of this model to store data before generate the report:
//Declare
ArrayList<GameReportModel> myArray = new ArrayList<GameReportModel>();
//Populate (example) for each input
GameReportModel myobj = new GameReportModel();
myobj.gamename = "My Game"; //<<from input source
myobj.username = "John"; //<<from input source
myobj.score = 20; //<<from input source
myobj.minutesplayed = 45; //<<from input source
myArray.add(myobj);
// Iterate
for(GameReportModel line : myArray){
writer.println("Player : " + line.username);
... and sumarize for each Player
}
Now you can build some scripts to sort by name, game. This method turn it easy but consume more virtual machine resources (memory and steps). But you can manipulate data with another perspective.
Add and remove Array elements easy.

Java Unable to return variables

The code is fine, but when I need to take the variables out of the functions and put them into the public static void, it says the variable cannot be found. Anybody know how to solve this issue?
import java.util.*;
public class Greetings {
public static void main(String[] args) {
System.out.println("Greetings, " + String(s) + ". " +
String(j) +"!" + " You are about " + int(z) + " years old");
}
public static String fNameGenerator(String s){
Scanner scan1 = new Scanner(System.in);
System.out.println("Please enter your first name: ");
String first = scan1.next();
s = first.substring(0,1).toUpperCase();
return s;
}
public static String LastName(String j){
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter you last name: ");
String second = scan2.next();
int x = second.length();
String y = second.substring(0, x).toLowerCase();
j = y.substring(0,1).toUpperCase();
return j;
}
public static int age(int z){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
z = (2015 - third);
return z;
}
}
You are not calling any of the methods, so how do you expect them to return something?
Two things to remember:
just because you wrote return s at the end of a method, it does not mean you can access s outside of this method. There's something called scopes in java, that means that a variable exists only on the scope it's define in- in your case - inside the methods. if you want it to exist outside - take the returned value and do something with it.
declaring the methods does nothing until you actually call them
so in order to access these variables, you need to do something like this:
public static void main(String[] args) {
String s = fNameGenerator();
String j = LastName();
int z = age();
System.out.println("Greetings, " + s + ". " + j +"!" +" You are about " + z + " years old");
}
one more thing you can see that I did there- you don't need to pass anything to your methods, as you are not doing anything with the given values before re-setting them. just make sure you declare the fields inside. for example your age method should look like:
public static int age(){
Scanner scan3 = new Scanner(System.in);
System.out.println("Please enter your year of birth: ");
int third = scan3.nextInt();
int z = (2015 - third);
return z;
}
There is a compile error in your code
System.out.println("Greetings, " + String(s) + ". " + String(j) +"!" +" You are about " + int(z) + " years old");
If you're trying to call the methods then replace
String(s) --> fNameGenerator(s)
String(j) --> LastName(j)
int(z) --> age(z)
Have the s,j,z as the local variables or static members.
or remove the arguments passing to the method as you're getting input from scanner

Error: cannot find symbol compiling (elementary java)

I'm working on a programming project for my intro class. I have a code that I'm trying to compile, but I'm having a hard time getting it to work after I added the PrintWriter. All was running well until I tried to print to a text file. Can someone help me figure out how to get it to run?
(Also, if you find any errors in my logic/layout/whatever, try to contain it! I still want to debug the program myself, I just can't do that until it runs :)
Attempt: (so far)
import java.util.Scanner; //import scanner
import java.util.Random; //import randomizer
import java.io.*; //needed for throws clause
public class randomLottery
{
public static void main(String[] args) throws IOException
{
String fullName;
Scanner keyboard = new Scanner( System.in );
//so we can generate random numbers
Random rand = new Random();
//declare a constant number of numbers
final int LOTTERY_NUMBERS = 5;
//Retrieve names
System.out.print("Please enter a first and last name for lottery "
+ "entry (type 'quit' to end): ");
fullName = keyboard.nextLine();
while(!fullName.contains(" "))
{
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
while(!fullName.contains("quit"))
{
//separate first/last name
String[] parts = fullName.split(" ");
String firstName = parts[0];
String lastName = parts[1];
//Open the file
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
//Print the name onto the file
outputFile.print(lastName + ", " + firstName + ": ");
int number;
for (number = 1; number <= LOTTERY_NUMBERS; number++)
{
if (number == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.println(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
//get the next name
System.out.print("Please enter BOTH a first and last name."
+ " Try Again: ");
fullName = keyboard.nextLine();
}
//Winning Lottery Numbers
outputFile.print("The winning numbers are: ");
int winning;
for (winning = 1; winning <= LOTTERY_NUMBERS; winning++)
{
if (winning == LOTTERY_NUMBERS)
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber);
}
else
{
int lotteryNumber = rand.nextInt(100) + 1;
outputFile.print(lotteryNumber + ", ");
}
}
outputFile.close();
}
}
PrintWriter outputFile = new PrintWriter("LotteryEntrants.txt");
Should be outside (before) the while loop. Having it inside the loop means it is not in the scope of your other uses of outputFile after the while loop.

Categories