I'm attempting to create a list because of the ability to "add" and element as opposed to checking size then dynamically expanding an array every time a new element is input. I can't get this to compile. I've scoured stack and google and nothing I've found is helping me. Someone mentioned creating an array and using that to be added to the list, but it seems to me i should be able to do this without all that.
I'm trying to get the system to add a string to the list every time a certain result occurs.
For ease of finding the List is called "incorrect"
import java.text.DecimalFormat;
import java.util.*;
public class User{
private String wrongQuestion; //quiz question
private String userName; //store user name
private String myOutput; //store output for toString and file write
private int score; //store user current score
private float average; //store user average score
private int diffLevel; //difficulty level
private int testType; //last test type
private int numTests; //store number of tests taken
private List <String> incorrect; //declare list for incorrect answers
private FileIO uFile; //declare FileIO object
public User(String inName) throws Exception
{
//local constants
final int VARIABLE_COUNT = 5; //loop sentinel
final int TOKEN_SKIP = 4; //loop sentinel
//local variables
int index; //loop index
int count; //loop counter
String token; //store tokens from line
StringTokenizer tokenLine; //store tokenized line
//instantiate file object
uFile = new FileIO (inName);
//if user exists
if (uFile.checkUser())
{
for (count = 0; count < VARIABLE_COUNT; count++)
{
//initialize tokenized line
tokenLine = new StringTokenizer(uFile.readLine());
//try to store the variables
try
{
//get and store user average
//for the first 2 tokens, skip
for (index = 0; index < TOKEN_SKIP; index++)
{
//move to next token
token = tokenLine.nextToken();//end for
switch (count)
{
case 1:
//store number of tests taken
numTests = Integer.parseInt(token);
//end case
break;
case 2:
//store difficulty of last test taken
diffLevel = Integer.parseInt(token);
//end case
break;
case 3:
//store score of last test taken
score = Integer.parseInt(token);
//end case
break;
case 4:
//store average of tests taken
average = Integer.parseInt(token);
//end case
break;
default:
break;
}//end switch
}//end for
//store next line
token = uFile.readLine();
//while there are more lines in the file
while (token != null)
{
//instantiate list for incorrect answers
incorrect = new ArrayList<String>();
//add line to end of list
incorrect.get(token);
//store next line
token = uFile.readLine();
}//end while
}//end try
//catch input mismatch exception
catch (InputMismatchException error)
{
//output error message
System.out.println ("This file is not formatted properly." +
" Either continue as a new user or log in again");
//initialize data to 0
average = 0;
testType = 0;
diffLevel = 0;
numTests = 0;
incorrect = new ArrayList <String>();
}//end catch
}//end for
}//end if
else
{
//initialize data to 0
average = 0;
testType = 0;
diffLevel = 0;
numTests = 0;
incorrect = new ArrayList<String>();
}//end else
//close input stream
uFile.closeFileReader();
}//end constructor
public float calcAverage(int newScore)
{
//local constants
//local variables
float avg; //store temp average
/**************Begin calcAverage*********/
//recalibrate avg for new calculation
avg = 0;
//calculate new average test score
avg = ((average * numTests) + newScore )/(numTests + 1);
//return average to be stored
return avg;
}
public void updateUser(int newTestType, int newDiffLevel, int newScore)
{
//local constants
//local variables
/***************Begin updateUser************/
//update new data after test is taken
score = newScore;
average = calcAverage(newScore);
diffLevel = newDiffLevel;
testType = newTestType;
numTests = numTests + 1;
}
public void writeFile() throws Exception
{
//local constants
//local variables
String line; //current line to write to file
int index; //loop index
/*************************Begin writeFile***************/
//open output stream
uFile.openOutput(userName);
//write user name
line = "User Name:\t" + userName +"\n";
uFile.writeLine(line);
//write number of tests taken
line = "Tests Taken:\t" + numTests + "\n";
//write number of tests taken
line = "Difficulty Level:\t" + diffLevel + "\n";
uFile.writeLine(line);
//write score of last test taken
line = "Last Test:\t" + score + "\n";
uFile.writeLine(line);
//write current user average
line = "User Average:\t" + average + "\n";
uFile.writeLine(line);
//for each element in the list
for (index = 0; index < incorrect.size(); index++)
{
//store then write the string
line = incorrect.get(index);
uFile.writeLine(line);
}//end for
//close file writer
uFile.closeFileWrite();
}//end writeFile
public void storeIncorrect(String inString)
{
//local constants
//local variables
/************Begin storeIncorrect*************/
//add formatted question to the list
incorrect.add(inString);
}
public String toString()
{
//local constants
//local variables
String buildUserName;
String buildAvg;
String buildNumTests;
String buildDiffLevel;
String buildScore;
DecimalFormat fmt; //declare decimal format object
/****************Begin toString***********/
//initialize decimal format
fmt = new DecimalFormat ("0.00");
//build output strings
buildUserName = Util.setLeft(20, "User Name:") + Util.setRight(25, userName);
buildNumTests = Util.setLeft(20, "Tests Taken:") + Util.setRight(18, numTests+"");
buildDiffLevel = Util.setLeft(20, "Last Difficulty:") + Util.setRight(24, diffLevel+"");
buildScore = Util.setLeft(20, "Last Score:") + Util.setRight(24, score+"");
buildAvg = Util.setLeft(20, "Test Average:") + Util.setRight(24, fmt.format(average)+"");
myOutput = buildUserName + "\n" + buildNumTests + "\n" + buildDiffLevel + "\n" + buildScore + "\n" + buildAvg;
return myOutput;
}//Display all users info
}
Few comments that might help :
// add line to end of list
incorrect.get(token); // <- change this to incorrect.add(token)
To iterate thru list use :
for (String item : incorrect) {
System.out.printlnt(item);
}
Also, you don't need to reinitialize your list as you do multiple times by
incorrect = new ArrayList<String>();
If you'd like to clear it, you could use incorrect.clear()
As you are not interested in Random access (i.e. via index), perhaps you could use LinkedList instead of ArrayList
Related
(Its not finished yet.)
I don't know how to get the total price after asking the user for their order. Example: I ordered 5 Piatos, and I typed end to show the result or total, but it just says 20 but it should be 100 because 20+20+20+20+20 = 100. How do I sum those individual prices so it shows the correct total price without changing the way to order items? (Which is selecting only the letters provided for each item.)
import java.util.Scanner;
public class Point_Of_Sale_System_Real {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Intro();
}
public static void Intro(){
int Piatos = 20, Vcut = 20;
double itemtotal = 0, itemtotalvisible, itemlone = 0;
String Ia = "a";
String Ib = "b";
System.out.println("Enter the letter that matches the item here: ");
System.out.println("Type \"End\" to stop selecting from the menu." );
String itemselect = "";
do {
itemselect = sc.nextLine();
if (itemselect.equalsIgnoreCase(Ia)){
itemlone = 0 + Piatos;
}
else if (itemselect.equalsIgnoreCase(Ib)){
itemlone = 0 + Vcut;
}
}
while (!itemselect.equalsIgnoreCase("end"));
itemtotalvisible = itemlone + 0;
System.out.println("Total" + itemtotalvisible);
}
}
Each time you make a selection in the do-while loop, you need to update itemtotalvisible. You are merely assigning the last value of itemlone to itemtotalvisible. Hence because the last item you selected was Piatos, itemtotalvisible equals the value of one Piatos item.
The below code is not a complete answer, but hopefully enough to help you fix your code.
double itemtotalvisible = 0;
String itemselect = "";
do {
itemselect = sc.nextLine();
if (itemselect.equalsIgnoreCase(Ia)){
itemlone = 0 + Piatos;
}
else if (itemselect.equalsIgnoreCase(Ib)){
itemlone = 0 + Vcut;
}
itemtotalvisible += itemlone;
}while (!itemselect.equalsIgnoreCase("end"));
System.out.println("Total" + itemtotalvisible);
So when i i have tried to save and compile everything works fine until I run it. There seems to be an issue with my array syntax. Could someone help me find it?When I do run this program the grades()method outputs "AAA" . What I'm trying to do in this program is read text from a txt file and list each line, outputting a student name and score. Now in the grades() method I am trying to output calculate a letter grade for each of the students grades and make that go into a loop until the last score has been read.
public class ReadData
{
private static String[] names = new String[3];
private static int line;
private static int[] scores = new int[3];
private static float mean;
private static double stdDeviation;
public static void readData() throws FileNotFoundException
{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
int l = 0;
// float sum = 0 ;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] words = line.split("\t");
names[l] = words[0];
scores[l] = Integer.parseInt(words[1]);
// sum+=scores[l];
System.out.println(" name: " + names[l] + ", score: " + scores[l]);
l++;
}
// System.out.println(scores[0]+ " " + scores[1]+ " " + scores[2]);
}
public static void fndMean()
{
float mean = ((25+65+89)/3);
System.out.println(" The mean is: " + mean);
}
public static void fndStandard() throws FileNotFoundException
{
double stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
System.out.println("The Standard Deviation is: " + stdDeviation);
}
Grades method
public static void grades()
{
for(int i = 0; i < (scores.length); i++)
{
if(mean + stdDeviation <= scores[i])
{
System.out.print("A");
}
else if( (scores[i] >= mean+(stdDeviation/3)) &&
(mean +stdDeviation)> scores[i])
{
System.out.print("B");
}
else if( (scores[i] >= mean-(stdDeviation/3)) &&
(mean +(stdDeviation/3))> scores[i])
{
System.out.print("C");
}
else if( (scores[i] >= mean-(stdDeviation)) &&
(mean - (stdDeviation/3))> scores[i])
{
System.out.print("D");
}
else
{
System.out.println("F");
}
}
}
You are re-declaring your variables in methods like fndMean() and fndStandard() when you do the following
double stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
float mean = ((25+65+89)/3);
You already declare them up top and don't need to do it again, otherwise it will only set the local variables inside the methods and not inside your class. you should do
stdDeviation = Math.sqrt(((Math.pow(25-59, 2)+(Math.pow(65-59,2))+
(Math.pow(89-59, 2))))/3);
mean = ((25+65+89)/3);
Which will set those variables to what you were expecting when you call those methods BEFORE calculating the grades.
This is what fndMean and fndStandard methods print:
The mean is: 59.0
The Standard Deviation is: 26.407069760451147
Sum of mean and stdDeviation is 85.40706976045115.
Now, the condition if(mean + stdDeviation <= scores[i]) checks whether that sum is less than equal to score[i] and if yes, prints 'A'. It can be true in either of these two cases:
Values in second column (tab) in txt files are all more than 85
score array gets altered between two method calls
Printing score value before those conditions should give you some more idea.
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.
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];
I'm having a bit of trouble with this project, and would greatly appreciate some help.
Here's a link to it:
http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
The basic gist is it's "A program that reads in a text file that uses a specific input format and uses it to produce a formatted report for output."
Specifically:
"For this lab you will write a Java program that produces a simple formatted report. The program will prompt the user to enter a file name. This file must contain information in a specific format (detailed below). Each "block" of the file contains information for one player in a competition -- the name of the player followed by a number of different scores that that player achieved. The program should find each player's average score, median score and best and worst scores and display them in a line on the final summary report. The program should also determine which player has the highest average score and which player has the lowest average score."
I get the following errors when I try and compile it:
Enter an input file name: Project11.txt
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException... -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Project11.getMedian(Project11.java:68)
at Project11.main(Project11.java:27)
Sorry for not clarifying.
Line 68 is: return (inList.get(Middle - 1) + inList.get(Middle)) / 2;
Line 27 is: int median = getMedian(List);
Hope that helps.
Here's my code:
import java.io.;
import java.util.;
public class Project11 {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String input = in.nextLine();
File inputFile = new File(input);
List<Integer> List = readNextSeries(inputFile);
int median = getMedian(List);
int mean = getAverage(List);
int max = getMaximum(List);
int min = getMinimum(List);
System.out.print("Enter an output file name: ");
String out = in.nextLine();
PrintWriter outputFile = new PrintWriter(out);
System.out.println("Median = " + median);
System.out.println("Mean = " + mean);
System.out.println("Max = " + max);
System.out.println("Min = " + min);
outputFile.println(median);
outputFile.println(mean);
outputFile.println(max);
outputFile.println(min);
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a negative
// value is read from the Scanner. Store these integers in an ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(File f) {
ArrayList<Integer> List = new ArrayList<Integer>();
try {
Scanner fileScan = new Scanner(f);
while (fileScan.hasNextInt()) {
int value = Integer.parseInt(fileScan.next());
List.add(value);
}
} catch (FileNotFoundException e) {}
return List;
}
// Given a List<Integer> of integers, compute the median of the list and return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
int Middle = inList.size() / 2;
if (inList.size() % 2 == 1) {
return inList.get(Middle);
}
else {
return (inList.get(Middle - 1) + inList.get(Middle)) / 2;
}
}
// Given a List<Integer> of integers, compute the average of the list and return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int total = 0;
int average = 0;
for(int element:inList){
total += element;
}
average = total / inList.size();
return average;
}
private static int getMaximum(List<Integer> inList) {
int largest = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > largest) {
largest = inList.get(i);
}
}
return largest;
}
private static int getMinimum(List<Integer> inList) {
int smallest = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < smallest) {
smallest = inList.get(i);
}
}
return smallest;
}
}
Thank you very much for any input.
Your getMedian(...) method doesn't handle the empty list case. Say you have an empty list (list of size 0), what do you think will happen? It will hit this line:
return (inList.get(Middle - 1) + inList.get(Middle)) / 2;
This inList.get(Middle - 1) is the same as inList.get(0 - 1) if the size of the list is 0. You want to make sure you methods handle all different cases. I'd recommend adding an if statement for this specific case (throw an Exception or give output so user knows what is wrong).
NOTE: This "all cases handling" applies to all your methods.