So I created a program that loads in a file that has the format: John 55 18.27 And then passes those three variables(once split) into a newly created file.
I get an exception error for 1) Jack Turner 44 19.22 & 2) Mike 55.0 23.44
The first error is because the last name, and another for an integer like 55.0
How can I fix my code to handle these exceptions?
import java.util.*;
import java.io.File;
import java.util.Scanner;
public class methods {
private String name;
private int hours;
private double timeSpent;
private double averageGPA;
private Scanner x;
private StringTokenizer stk;
private String[] storage = new String[11];
private Formatter file;
public void openFile(){
try{
x = new Scanner(new File("students.dat"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile(){
int count = 0;
while(x.hasNext()){
storage[count] = x.nextLine();
count ++;
}
}
public void closeFile(){
x.close();
}
public void stringTokenizer(){
int count = 0;
createNewFile();
while(count < storage.length){
stk = new StringTokenizer(storage[count]);
name = stk.nextToken();
hours = Integer.parseInt(stk.nextToken());
timeSpent = Double.parseDouble(stk.nextToken());
addRecords();
count++;
}
file.close();
}
public void createNewFile(){
try{
file = new Formatter("skeleton.txt");
}
catch(Exception e){
System.out.println("There has been an error");
}
}
public void addRecords(){
file.format("%s %s %s\n", name, hours, timeSpent);
}
}
public class Lab1_a {
public static void main(String[] args) {
int creditHrs; // number of semester hours earned
double qualityPts; // number of quality points earned
double gpa; // grade point (quality point) average
String line, name = "", inputName = "students.dat";
String outputName = "warning.dat";
//Get File
methods obj1 = new methods();
//Create an Array of Strings
obj1.openFile();
obj1.readFile();
obj1.createNewFile();
obj1.stringTokenizer();
obj1.closeFile();
}
}
First, after reading name, if the next token cannot be parsed as a double, append it to name with a space in between. Continue until you find a double.
Once you've found the first double, cast that into an int and store as hours.
ParsetimeSpent as before.
Here's some (untested) code that should get you started:
name = stk.nextToken();
String next;
while (true) {
try {
next = stk.nextToken();
hours = (int)Double.parseDouble(next);
break;
} catch (NumberFormatException e) {
name = name + " " + next;
}
}
timeSpent = Double.parseDouble(stk.nextToken());
Related
I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.
in here i want to collect everything after a substring and set it as their specfic field.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
*
* class StudentReader for retrieveing data from file
*
*/
public class StudentReader {
public static Student[] readFromTextFile(String fileName) {
ArrayList<Student> result = new ArrayList<Student>();
File f = new File(filename);
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
String text = n.nextLine();
}
n.close();
String hold1[] = text.Split(",");
String hold2[] = new String[hold1.length];;
for(int i = 0; i < hold1.length(); ++i) {
hold2[i] = hold1.Split("=");
if (hold2[i].substring(0,3).equals("name")) {
}
}
return result.toArray(new Student[0]);
}
}
backing up the goal of this code is to first open and read a file where it has about 20 lines that look just like this
Student{name=Jill Gall,age=21,gpa=2.98}
I then need to split it as done above, twice first to get rid of comma and the equals, I then for each line need to collect the value of the name, age and double, parse them and then set them as a new student object and return that array they are going to be saved onto, what I am currently stuck on is that i cannot figure out what's the right code here for collecting everything after "name" "age" "gpa", as i dont know how to set specific substrings for different name
im using this link as a reference but I don't see what actually does it
How to implement discretionary use of Scanner
I think the bug is in following lines,
while (n.hasNextLine()) {
String text = n.nextLine();
}
Above code should throw compilation error at String hold1[] = text.Split(","); as text is local variable within while loop.
Actual it should be,
List<String> inputs = new ArrayList<String>()
Scanner n = new Scanner(f);
while (n.hasNextLine()) {
inputs.add(n.nextLine());
}
You can use above inputs list to manipulate your logic
By the look of it, at least by your ArrayList<> declaration, you have a class named Student which contains member variable instances of studentName, studentAge, and studentGPA. It might look something like this (the Getter/Setter methods are of course optional as is the overriden toString() method):
public class Student {
// Member Variables...
String studentName;
int studentAge = 0;
double studentGPA = 0.0d;
// Constructor 1:
public Student() { }
// Constructor 2: (used to fill instance member variables
// right away when a new instance of Student is created)
public Student(String name, int age, double gpa) {
this.studentName = name;
this.studentAge = age;
this.studentGPA = gpa;
}
// Getters & Setters...
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public double getStudentGPA() {
return studentGPA;
}
public void setStudentGPA(double studentGPA) {
this.studentGPA = studentGPA;
}
#Override
public String toString() {
return new StringBuilder("").append(studentName).append(", ")
.append(String.valueOf(studentAge)).append(", ")
.append(String.valueOf(studentGPA)).toString();
}
}
I should think the goal would be to to read in each file line from the Students text file where each file line consists of a specific student's name, the student's age, and the student's GPA score and create a Student instance for the Student on that particular file line. This is to be done until the end of file. If there are twenty students within the Students text file then, when the readFromTextFile() method has completed running there will be twenty specific instances of Student. Your StudentReader class might look something like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
*
* class StudentReader for retrieving data from file
*
*/
public class StudentReader {
private static final Scanner userInput = new Scanner(System.in);
private static Student[] studentsArray;
public static void main(String args[]) {
String underline = "=====================================================";
String dataFilePath = "StudentsFile.txt";
System.out.println("Reading in Student data from file named: " + dataFilePath);
if (args.length >= 1) {
dataFilePath = args[0].trim();
if (!new File(dataFilePath).exists()) {
System.err.println("Data File Not Found! (" + dataFilePath + ")");
return;
}
}
studentsArray = readFromTextFile(dataFilePath);
System.out.println("Displaying student data in Console Window:");
displayStudents();
System.out.println(underline);
System.out.println("Get all Student's GPA score average:");
double allGPA = getAllStudentsGPAAverage();
System.out.println("GPA score average for all Students is: --> " +
String.format("%.2f",allGPA));
System.out.println(underline);
System.out.println("Get a Student's GPA score:");
String sName = null;
while (sName == null) {
System.out.print("Enter a student's name: --> ");
sName = userInput.nextLine();
/* Validate that it is a name. Should validate in
almost any language including Hindi. From Stack-
Overflow post: https://stackoverflow.com/a/57037472/4725875 */
if (sName.matches("^[\\p{L}\\p{M}]+([\\p{L}\\p{Pd}\\p{Zs}'.]*"
+ "[\\p{L}\\p{M}])+$|^[\\p{L}\\p{M}]+$")) {
break;
}
else {
System.err.println("Invalid Name! Try again...");
System.out.println();
sName = null;
}
}
boolean haveName = isStudent(sName);
System.out.println("Do we have an instance of "+ sName +
" from data file? --> " +
(haveName ? "Yes" : "No"));
// Get Student's GPA
if (haveName) {
double sGPA = getStudentGPA(sName);
System.out.println(sName + "'s GPA score is: --> " + sGPA);
}
System.out.println(underline);
}
public static Student[] readFromTextFile(String fileName) {
List<Student> result = new ArrayList<>();
File f = new File(fileName);
try (Scanner input = new Scanner(f)) {
while (input.hasNextLine()) {
String fileLine = input.nextLine().trim();
if (fileLine.isEmpty()) {
continue;
}
String[] lineParts = fileLine.split("\\s{0,},\\s{0,}");
String studentName = "";
int studentAge = 0;
double studentGPA = 0.0d;
// Get Student Name (if it exists).
if (lineParts.length >= 1) {
studentName = lineParts[0].split("\\s{0,}\\=\\s{0,}")[1];
// Get Student Age (if it exists).
if (lineParts.length >= 2) {
String tmpStrg = lineParts[1].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("\\d+")) {
studentAge = Integer.valueOf(tmpStrg);
}
// Get Student GPA (if it exists).
if (lineParts.length >= 3) {
tmpStrg = lineParts[2].split("\\s{0,}\\=\\s{0,}")[1];
// Validate data.
if (tmpStrg.matches("-?\\d+(\\.\\d+)?")) {
studentGPA = Double.valueOf(tmpStrg);
}
}
}
}
/* Create a new Student instance and pass the student's data
into the Student Constructor then add the Student instance
to the 'result' List. */
result.add(new Student(studentName, studentAge, studentGPA));
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
return result.toArray(new Student[result.size()]);
}
public static void displayStudents() {
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return;
}
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i].toString());
}
}
public static boolean isStudent(String studentsName) {
boolean found = false;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return found;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return found;
}
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
break;
}
}
return found;
}
public static double getStudentGPA(String studentsName) {
double score = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return score;
} else if (studentsName == null || studentsName.isEmpty()) {
System.err.println("Student name can not be Null or Null-String (\"\")!");
return score;
}
boolean found = false;
for (int i = 0; i < studentsArray.length; i++) {
if (studentsArray[i].getStudentName().equalsIgnoreCase(studentsName)) {
found = true;
score = studentsArray[i].getStudentGPA();
break;
}
}
if (!found) {
System.err.println("The Student named '" + studentsName + "' could not be found!");
}
return score;
}
public static double getAllStudentsGPAAverage() {
double total = 0.0d;
if (studentsArray == null || studentsArray.length == 0) {
System.err.println("There are no Students within the supplied Students Array!");
return total;
}
for (int i = 0; i < studentsArray.length; i++) {
total += studentsArray[i].getStudentGPA();
}
return total / (double) studentsArray.length;
}
}
I've recently had a small class test in college for java and I need help.
I have an object called "Products" that takes (String, double, int) as it's parameters.
I've created an ArrayList
ArrayList<Product> products = new ArrayList<>();
What I'm trying to do is use a StringTokenizer to read from this format and
store it into individual objects and then I want to print out the object contents.
PR0001 7.99 10
PR0002 29.99 0
PR0003 5.99 25
PR0004 99.99 50
PR0005 17.99 15
PR0006 15.99 0
PR0007 19.99 35
PR0008 39.99 40
PR0009 2.99 0
PR0010 3.99 5
My main method is:
package objects;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
public class main_object_class
{
public static void main(String[] args)
{
ArrayList<Product> products = new ArrayList<>();
String fileName = "products.txt";
try
{
Scanner file = new Scanner(new File(fileName));
while(file.hasNextLine())
{
StringTokenizer strToken = new StringTokenizer(file.next(), " ");
while(strToken.hasMoreTokens())
{
String pCode = strToken.nextToken();
System.out.println("pCode Works");
double pPrice = Double.parseDouble(strToken.nextToken());
System.out.println("pPrice Works");
int pQuantity = Integer.parseInt(strToken.nextToken());
System.out.println("pQuantity Works");
products.add(new Product(pCode,pPrice,pQuantity));
System.out.println("Storing Works");
}
}
for(int i=0;i<products.size();i++)
{
System.out.println(products);
}
}catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
}
My Product method:
package objects;
public class Product
{
private String pCode = "";
private double pPrice = 0;
private int pQuantity = 0;
public Product(String c, double p, int q)
{
pCode = c;
pPrice = p;
pQuantity = q;
}
public void setCode(String c)
{
pCode = c;
}
public String getCode()
{
return pCode;
}
public void setPrice(double p)
{
pPrice = p;
}
public double getPrice()
{
return pPrice;
}
public void setQuantity(int q)
{
pQuantity = q;
}
public int getQuantity()
{
return pQuantity;
}
#Override
public String toString()
{
return "Code : " + getCode() + "\tPrice : $" + getPrice() + "\tQuantity : " + getQuantity();
}
}
My Error:
run:
pCode Works
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at objects.main_object_class.main(main_object_class.java:24)
C:\Users\Alex\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I'd really like to thank for all the input. I've tried all solutions and they all worked. Yet I'm going to go with #Jerin Joseph solution!
Read the file line by line, Scanner::nextLine() gives you one line at a time.
StringTokenizer strToken = new StringTokenizer(file.nextLine(), " ");
Remove the while(strToken.hasMoreTokens()), You need to check it for every token you parse.
Change it to ,
String pCode = "";
double pPrice = 0;
int pQuantity = 0;
if(strToken.hasMoreTokens()){
pCode = strToken.nextToken();
System.out.println("pCode Works");
}
if(strToken.hasMoreTokens()){
pPrice = Double.parseDouble(strToken.nextToken());
System.out.println("pPrice Works");
}
if(strToken.hasMoreTokens()){
pQuantity = Integer.parseInt(strToken.nextToken());
System.out.println("pQuantity Works");
}
products.add(new Product(pCode,pPrice,pQuantity));
System.out.println("Storing Works");
Your problem is that you check if there are Tokens left, and than call "nextToken()" 3 times. Where there cannot be a guranty that there will be 3 tokens left, unless you specifically check for it. Like so:
if(strToken.countTokens() >= 3)
{
\\ here you can call strToken.nextToken() safly for 3 times.
}
Your current approuch is a classic approuch for basic itteration. E.g.
while(strToken.hasMoreElements())
{
String next = strToken.nextToken();
}
But it allows only one safe call of "nextToken()" between the bracets.
I hope this helped
Okay so the program I'm working on needs to create an arrayList of change objects minimum of 1,000 and then compute the change that would be produced from that amount kind of like in a point of sale environment. I have everything working except I'm stumped on how to actually calculate the change. I have methods written in another class to do it, but I'm not sure how to pass the entire arrayList over to them in order to do so. If anyone could give me a hand with this it would be much appreciated.
Change class :
public class Change {
private double amount, remainingAmount;
private int occurences;
public Change() {
super();
this.amount = 17.87;
this.remainingAmount = (int)(amount * 100);
}
public Change(double amount, double remainingAmount) {
super();
this.amount = amount;
this.remainingAmount = remainingAmount;
}
public Change(float nextChange) {
this.amount = amount;
this.remainingAmount = remainingAmount;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getRemainingAmount() {
return remainingAmount;
}
public void incrementOccurence() {
occurences++;
}
public void setRemainingAmount(double remainingAmount) {
this.remainingAmount = remainingAmount;
}
public double numberOfOneDollars() {
int numberOfOneDollars = (int) (remainingAmount / 100);
remainingAmount = remainingAmount % 100;
return numberOfOneDollars;
}
public double numberOfQuarters() {
int numberOfQuarters = (int) (remainingAmount / 25);
remainingAmount = remainingAmount % 25;
return numberOfQuarters;
}
public double numberOfDimes() {
int numberOfDimes = (int) (remainingAmount / 10);
remainingAmount = remainingAmount % 10;
return numberOfDimes;
}
public double numberOfNickels() {
int numberOfNickels = (int) (remainingAmount / 5);
remainingAmount = remainingAmount % 5;
return numberOfNickels;
}
public int numberOfPennies() {
int numberOfPennies = (int) remainingAmount;
return numberOfPennies;
}
#Override
public String toString() {
return "Change [amount=" + amount + ", remainingAmount="
+ remainingAmount + "]\n";
}
}
Change ArrayList Class:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;
public class ChangeArrayList {
private ArrayList<Change> changeArray = new ArrayList<Change>();
private static int numOfChangeObjects = 1000;
private static String FILE_NAME = "changeData.dat";
public static void makeChangeData() {
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(FILE_NAME);
}
catch(FileNotFoundException e) {
System.out.println("Error opening the file " + FILE_NAME);
System.exit(0);
}
for (int count = 0; count < numOfChangeObjects; count++) {
//get random number between 0-1, move decimal right two places, typecast to float
//to get rid of decimals, then divide by 10.0 to get decimal left one place
//then add 3 to make sure numbers are >3
DecimalFormat df = new DecimalFormat("#.##");
double changeData = (float)(Math.random() * 100)/10.0 + 3;
double twoDecimal = Double.valueOf(df.format(changeData));
outputStream.println(twoDecimal + " ");
}
outputStream.close();
System.out.println("Those lines were written to " + FILE_NAME);
}
public void makeChangeArray(String fileName) {
changeArray = new ArrayList<Change>();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new File(FILE_NAME));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
FILE_NAME);
System.exit(0);
}
while (inputStream.hasNext())
{
//read in a change object from the file
float nextChange = inputStream.nextFloat();
//Stuck here. Can't figure out what to put in to make this work
//everything else works except this. My change keeps coming out as 0
changeArray.add(new Change(nextChange));
//Stuck here. Can't figure out what to put in to make this work
//everything else works except this. My change keeps coming out as 0
}
inputStream.close();
}
public void writeToFile() {
String fileName = "out.txt"; //The name could be read from
//the keyboard.
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(fileName);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
fileName);
System.exit(0);
}
outputStream.println(toString());
outputStream.close( );
System.out.println("Those lines were written to " +
fileName);
}
public String toString() {
String s = "";
for (int i = 0; i < changeArray.size(); i++) {
s += changeArray.get(i).toString(); }
return s;
}
public static void main(String[] args) {
ChangeArrayList.makeChangeData();
ChangeArrayList tester = new ChangeArrayList();
tester.makeChangeArray("changeData.dat");
//Something should go here to calculate change
//Not sure how to go about doing this
tester.writeToFile();
}
}
Approach 1:
You can make getter method for changeArray in ChangeArrayList. And after calling makeChangeArray() method in main method, you can call getter method and pass that returned arraylist to required method as a parameter.
Approach 2: I wll prefer this approach.
Do not declare class level changeArray, instead declare it inside your makeChangeArray() method and change return type to List instead of void and return the prepared arraylist.
I'm having trouble understanding how to parse text documents with unknown amounts of 'students'. All my solutions are coming up strange and I'm having trouble with the Scanner. Breaking down the input, the first integer represents how many classes there are, the first string is the class name, the following are students with respective dates and variables that need to be stored along with the student, with an unknown amount of students. I want to store each student along with the class they are in.
My code is extremely messy and confusing so far:
String filename = "input.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
Student[] studArr = new Student[100];
int studCounter = 0;
boolean breaker = false;
boolean firstRun = true;
int numClasses = sc.nextInt();
System.out.println(numClasses);
while(sc.hasNextLine()){
String className = sc.nextLine();
System.out.println("Name: " + className);
String test = null;
breaker = false;
sc.nextLine();
// Breaks the while loop when a new class is found
while (breaker == false){
Student temp = null;
// Boolean to tell when the first run of the loop
if (firstRun == true){
temp.name = sc.nextLine();
}
else
temp.name = test;
System.out.println(temp.name);
temp.date = sc.nextLine();
if (temp.date.isEmpty()){
System.out.println("shit is empty yo");
}
temp.timeSpent = sc.nextInt();
temp.videosWatched = sc.nextInt();
temp.className = className;
studArr[studCounter] = temp;
studCounter++;
sc.nextLine();
test = sc.nextLine();
firstRun = false;
}
}
}
}
class Student {
public String name;
public String date;
public String className;
public int timeSpent;
public int videosWatched;
}
I don't need an exact answer, but should I be looking into a different tool then Scanner? Is there a method I can research?
Thanks for any assistance.
I came up with the following solution. Scanner is a fine tool for the job. The tricky part is that you have to sort of look ahead to see if you have a blank line or a date to know if you have a student or a class.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Parser {
private static String nextLine(Scanner sc) {
String line;
while (sc.hasNext()) {
if (!(line = sc.nextLine()).isEmpty()) {
return line;
}
}
return null;
}
public static ArrayList<Student>[] parseFile(String fileName) {
File file = new File(fileName);
try (Scanner sc = new Scanner(file)) {
int numClasses = sc.nextInt();
String className = nextLine(sc);
ArrayList<Student>[] classList = new ArrayList[numClasses];
for (int i = 0; i < numClasses; i++) {
classList[i] = new ArrayList<>();
while (true) {
String studentOrClassName = nextLine(sc);
if (studentOrClassName == null) {
break;
}
String dateOrBlankLine = sc.nextLine();
if (dateOrBlankLine.isEmpty()) {
className = studentOrClassName;
break;
}
int timeSpent = sc.nextInt();
int videosWatched = sc.nextInt();
classList[i].add(new Student(className, dateOrBlankLine, studentOrClassName, timeSpent,
videosWatched));
}
}
return classList;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ArrayList[0];
}
public static void main(String[] args) {
for (ArrayList<Student> students : parseFile("classList.txt")) {
if (!students.isEmpty()) {
System.out.println(students.get(0).className);
}
for (Student student : students) {
System.out.println(student);
}
}
}
static class Student {
public String className;
public String date;
public String name;
public int timeSpent;
public int videosWatched;
public Student(String className, String date, String name, int timeSpent,
int videosWatched) {
this.className = className;
this.date = date;
this.name = name;
this.timeSpent = timeSpent;
this.videosWatched = videosWatched;
}
public String toString() {
return name + '\n' + date + '\n' + timeSpent + '\n' + videosWatched + '\n';
}
}
}
Ask yourself, what does a Student contain? A name, date, number and number. So you want to do the following (not actual code) (format written in Lua code, very understandable. This means this will not run in Lua :P)
if line is not empty then
if followingLine is date then
parseStudent() // also skips the lines etc
else
parseClass() // also skips lines
end
end