add java methods to code [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I start study programming, I made a simple code in java,
is a contest, every participant make bites to an apples, so the participant that bites are more weight wins!
but!! I need add in all code with java methods, functions... you know
please run the code for you understand more
any help? really thanks!
import java.io.*;
class reality_show_methods{
public static void main(String[] args)throws java.io.IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintStream out = System.out;
// VARIABLES
int counterParticipants = 1, numPart, numBoc;
double weightBoc, weightBocTotalMayor = 0;
String namePart, nameParticipantWinner = "";
// SETUP
out.print("Number of Participants ......................... ");
numPart = Integer.parseInt(in.readLine());
out.print("Number of Participants Bites: ....... ");
numBoc = Integer.parseInt(in.readLine());
// START
while (counterParticipants <= numPart) {
out.print("\nParticipant Name #" + counterParticipants + " ...................... ");
namePart = in.readLine();
int countBoc = 1;
double weightBocTotal = 0;
while (countBoc <= numBoc) {
out.print("Bite weight #" + countBoc + " of the Participant " + namePart + ": ");
weightBoc = Double.parseDouble(in.readLine());
weightBocTotal = weightBocTotal + weightBoc;
countBoc++;
}
if (weightBocTotalMayor < weightBocTotal) {
weightBocTotalMayor = weightBocTotal;
nameParticipantWinner = namePart;
}
counterParticipants++;
}
// SHOW WINNER
out.println("\nParticipant Winner: ................... " + nameParticipantWinner + " with Total Weight: " + weightBocTotalMayor);
}
}

Do you mean:
public static void myFunction()
{
// blah blah
}

I guess this would help you.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class BiteContest {
private class Participant{
private String name;
private double biteWeight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBiteWeight() {
return biteWeight;
}
public void setBiteWeight(double biteWeight) {
this.biteWeight = biteWeight;
}
}
ArrayList<Participant> participants = new ArrayList<Participant>();
int numBoc;
BufferedReader in;
PrintStream out;
BiteContest(){
in = new BufferedReader(new InputStreamReader(System.in));
out = System.out;
}
void addParticepents() throws IOException
{
boolean noMoreParticipants = false;
while( !noMoreParticipants )
{
out.print("Participant Name : ");
String name = in.readLine();
Participant participant = new Participant();
participant.setName(name);
participant.setBiteWeight(0);
participants.add( participant );
out.print("Want to add more participants [Y/N]: ");
String input = in.readLine();
//Get first character.
input = input.substring(0,1);
noMoreParticipants = "y".equalsIgnoreCase(input)?false:true;
}
}
void takeBiteCount() throws NumberFormatException, IOException {
out.print("\nNumber of Participants Bites : ");
numBoc = Integer.parseInt(in.readLine());
}
void contest() throws NumberFormatException, IOException
{
out.print( "\n\n------CONTEST STARTS------" );
for( Participant participant : participants )
{
out.print( "\n\n------------" );
out.print( "\nTaking Bites for " + participant.getName() + "\n" );
for( int i = 0; i < numBoc; i++ )
{
out.print("Bite weight #" + (i+1) + " of the Participant " + participant.getName() + " : ");
double weightBoc = Double.parseDouble(in.readLine());
participant.setBiteWeight( participant.getBiteWeight() + weightBoc );
}
}
}
String getTheWinner(){
Collections.sort( participants, new Comparator<Participant>() {
public int compare(Participant o1, Participant o2) {
return (int)(o2.getBiteWeight() - o1.getBiteWeight());
}
} );
// Client at the top will be the winner.
return participants.get(0).getName();
}
public static void main(String[] args) {
BiteContest contest = new BiteContest();
try {
contest.addParticepents();
contest.takeBiteCount();
contest.contest();
String winner = contest.getTheWinner();
System.out.println( "\n\n-------------------------\n" +
"The winner is : " + winner );
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}

Related

How to store file data lines and pass it method to calculate into letters and print letter grades in another file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
class.txt
Reena Sam, 100, 90, 80, 100,
Donna D. Bartolome, 90, 90, 100, 100,
Chris Tui, 100, 90, 100, 70,
I'm new to java and I'm trying to figure out
how to store file data lines to calculate into letters and print letter grades in another file?
I'm trying to look into storing into multiple objects or ArrayLists…
like this:
Reena Sam: A
Donna D. Bartolome: B
Chris Tui: C
Below is my current progress towards this, but I got stuck in trying to store the data. pls help...
...
class gradeMaker{
private Scanner readFile;
private String[] argument;
private ArrayList<String> list;
private String finalGrade ="";
gradeMaker(String [] arg) {
argument = arg;
}
void readStudentScores() {
File file = new File(argument[0]);
if (!file.exists()) {
System.out.println("Input file" + argument[0] + "does not exist");
System.exit(2);
}
try{ // Create a Scanner for the file
readFile = new Scanner(file);
ArrayList<Student> list = new ArrayList<>();
// Read data from a file
System.out.println("Read data from a file");
while (readFile.hasNextLine()) {
String temp = readFile.nextLine();
//list.add(new Student ()); //Stores Student student1 = new Student(Name2, 20, 28, 60,)
//Stores Student student2 = new Student(Name2, 20, 28, 60,)
System.out.println(temp);
//String[] studentInfo = line.split(",");
}
Collections.sort(list);
for (int i = list.size(); i >= 0; i++)
System.out.print(list.get(i) + " ");
System.out.println(list.toString());
// System.out.println();
}catch (IOException e) {
System.out.println("Error Reading from file:" + file + e.getMessage());
}
}
void computeGrade() {
int Q1 = quiz1;
int Q2 = quiz2;
int M1 = mid;
int FN = finals;
int finalScore = (Q1 * .20 + Q2 * .20 + M1 * .25 + FN * .35);
if (finalScore >= .9)
finalGrade = "A";
else if (finalScore >= .8 && finalScore <= .89 )
finalGrade = "B";
else if (finalScore >= .7 && finalScore <= .79 )
finalGrade = "C";
else if (finalScore >= .6 && finalScore <= .69 )
finalGrade = "D";
else if (finalScore <= .59 )
finalGrade = "F";
//}
}
void Grades() {
File outputFile = new File(argument[1]);
try {
PrintWriter output = new PrintWriter(outputFile);
while (readFile.hasNextLine()) {
output.println(finalGrade);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
A couple things here. First, I see you have a System print set to catch unknown errors on your collections sort. printStackTrace will be more useful there.
Also your PrintWriter is returning just a grade. To get the output you want, you really want to return a constructor with a concatenated string. You can do this by making an object of your class that handles the arguments you need to return. Something like:
String finalGrade = f.toString();
public gradeMarker(String name, String finalGrade) {
this.name = name;
this.finalGrade = finalGrade;
}
You have final grade as an integer (f), but personally I find it easier to read/write data as strings. You can follow this up with your getter and setter methods, and then put a final method that returns the output you want. Something like
public String toString() {
return name + "," + finalGrade;
}
You can then put your results in a list and write it to the file using a for each loop
List<gradeMaker> grade = FileReader(//your file)
PrintWriter output = new PrintWriter(//your file)
for (gradeMaker x : grade) {
output.println(x);
}
That'll print each line, and since it's for each will only go long as an object exists to print. Hope all of that helps!
Here is fully working example as starting point. If you are using Java 7 or above you can improve it by using java.nio.file, which is a way to work with files up todays standards, instead of java.io.File. You could also consider using java 8 streams to make mapping a line to an object cleaner and more readable.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MarksToGrades {
public static void main(String[] args){
String inputFile = "C:\\Users\\Eritrean\\Desktop\\marks.txt";
List<Student> students = readFileAndGetStudents(inputFile);
String outputFile = "C:\\Users\\Eritrean\\Desktop\\grades.txt";
writeStudentsDataToFile(students,outputFile);
}
static List<Student> readFileAndGetStudents(String inputFileName){
List<Student> students = new ArrayList<>();
try(FileReader fr = new FileReader(new File(inputFileName));
BufferedReader reader = new BufferedReader(fr);){
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
students.add(new Student(line));
}
}
catch(IOException e){
e.printStackTrace();
}
return students;
}
static void writeStudentsDataToFile(List<Student> students, String outputFileName){
try (FileWriter writer = new FileWriter(outputFileName);
BufferedWriter bw = new BufferedWriter(writer)) {
for(Student stud : students){
System.out.println(stud.toString());
bw.write(stud.toString());
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class Student{
String name;
int quiz1;
int quiz2;
int mid1;;
int finals;
double total;
char grade;
// getter & setter omitted as they are not important for this task. if necessary, you can add them
public Student(String line) {
String[] data = line.split(",");
this.name = data[0];
this.quiz1 = Integer.parseInt(data[1].trim());
this.quiz2 = Integer.parseInt(data[2].trim());
this.mid1 = Integer.parseInt(data[3].trim());
this.finals = Integer.parseInt(data[4].trim());
this.total = calculateTotal (quiz1,quiz2,mid1,finals);
this.grade = getGrade(total);
}
private double calculateTotal(int quiz1, int quiz2, int mid1, int finals) {
return quiz1 * .20 + quiz2 * .20 + mid1 * .25 + finals * .35;
}
private char getGrade(double total) {
if (total >= 90)
return 'A';
else if (total >= 80)
return 'B';
else if (total >= 70)
return 'C';
else if (total >= 60)
return 'D';
else
return 'F';
}
#Override
public String toString() {
return name + ": " + grade ;
}
}
}

Is it possible to use other class variable in other class at #Override Java

I was wondering is there a way to use other class variable in #Override?
Here is my first class. I've tried to use setters & getters, but still receiving an error:
public class Darbuotojas {
String dVardas;
String dPavarde;
int dAmzius;
int dPatirtis;
Programuotojas programuotojas = new Programuotojas();
String check = programuotojas.getDarboKalba();
Darbuotojas() { }
public Darbuotojas(String dVardas, String dPavarde, int dAmzius, int dPatirtis) {
this.dVardas = dVardas;
this.dPavarde = dPavarde;
this.dAmzius = dAmzius;
this.dPatirtis = dPatirtis;
}
#Override
public String toString() {
return dVardas + " " + dPavarde + " " + dAmzius + " " + dPatirtis + " " + check;
}}
And here is my another class:
public class Programuotojas extends Darbuotojas {
Programuotojas(){}
public String getDarboKalba() {
return darboKalba;
}
public void setDarboKalba(String darboKalba) {
this.darboKalba = darboKalba;
}
public String darboKalba;
public Programuotojas(String dVardas, String dPavarde, int dAmzius, int dPatirtis, String darboKalba) {
super(dVardas, dPavarde, dAmzius, dPatirtis);
this.darboKalba = darboKalba;
}
As I see I formulated bad and not understandable question for you guys. I will try to explain. I have father class Darbuotojas with 4 parameters, in subclass Programuotojas I add one more parameter - darboKalba. So what I want from Override to return these 4 paremeters from Darbuotojas + one from Programuotojas.
// Darbuotoju valdymas prasideda //
public void darbuotojuVald() {
System.out.println("---- Darbuotoju valdymas ----");
System.out.println("[1] Prideti nauja darbuotoja");
System.out.println("[2] Pasalinti darbuotoja");
System.out.println("[3] Atnaujinti darbuotoja");
System.out.println("[4] Pamatyti darbuotoju sarasa");
System.out.println("[5] Gauti informacija apie pasirinkta darbuotoja");
Scanner SI = new Scanner(System.in);
int vartotojoIvestis = Integer.parseInt(SI.nextLine());
if (vartotojoIvestis == 1) {
System.out.println("---- Prideti nauja darbuotoja ----");
System.out.println("[1] Programuotoja");
System.out.println("[2] kita");
int vartotojoIvestis2 = Integer.parseInt(SI.nextLine());
if (vartotojoIvestis2 == 1) {
pridetiDarbuotojaProgramuotoja();
} else {
System.out.println("In progress....");
}
} else if (vartotojoIvestis == 4) {
bendrasDarbuotojuSarasas();
}
}
// Programuotojo pridejimas prasideda //
private void pridetiDarbuotojaProgramuotoja() {
System.out.println("---- Pridedamas naujas programuotojas ----");
System.out.println("Iveskite:");
System.out.println("Varda, pavarde, amziu, patirti, programavimo kalba");
Scanner SI = new Scanner(System.in);
String[] iveda = SI.nextLine().split(" ");
programuotojas.add(new Programuotojas(iveda[0], iveda[1], Integer.parseInt(iveda[2]), Integer.parseInt(iveda[3]), iveda[4]));
System.out.println("---- Sekmingai pridetas naujas darbuotojas ----");
System.out.println("Vardas: " + iveda[0]
+ ",pavarde: " + iveda[1]
+ ",amzius: " + iveda[2]
+ ",patirtis: " + iveda[3]
+ ",programavimo kalba: " + iveda[4]);
darbuotojuSarasas.clear();
darbuotojuSarasas.addAll(programuotojas);
darbuotojuVald();
}
private void bendrasDarbuotojuSarasas() {
System.out.println("---- Visas darbuotoju sarasas ----");
for(int i = 0; i < darbuotojuSarasas.size(); i++) {
System.out.println("ID " + i + " " + darbuotojuSarasas.get(i));
}
darbuotojuVald();
}
Reflection can be tricky, and I can't guarantee it'll work for all circumstances. This worked well enough for me.
package quicktest;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Brenden
*/
public class FieldDumpTest {
public static void main( String[] args ) {
System.out.println( new FieldDump3() );
}
public final String topTestString = "This is a test.";
protected int topInt = 11;
float topFloat = 123.456f;
private short topShort = Short.MAX_VALUE;
#Override
public String toString() {
StringBuilder str = new StringBuilder();
Class<?> type = this.getClass();
do {
str.append( type.getName() );
str.append( " {" );
Field[] fields = type.getDeclaredFields();
for( int i = 0; i < fields.length; i++ ) {
Field field = fields[i];
str.append( field.getName() );
str.append( ":" );
try {
str.append( field.get( this ) );
} catch( IllegalAccessException | IllegalArgumentException ex ) {
str.append( "<NO ACCESS>" );
}
str.append( ", " );
}
str.append( "} " );
type = type.getSuperclass();
} while( type != null );
return str.toString();
}
}
class FieldDump2 extends FieldDumpTest {
private String test = "testtest";
}
class FieldDump3 extends FieldDump2 {
int ten = 10;
protected double fortytwo = 42.0;
}
Output:
run:
quicktest.FieldDump3 {ten:10, fortytwo:42.0, } quicktest.FieldDump2 {test:<NO ACCESS>, } quicktest.FieldDumpTest {topTestString:This is a test., topInt:11, topFloat:123.456, topShort:32767, } java.lang.Object {}
BUILD SUCCESSFUL (total time: 0 seconds)

failed to pop the top of stack

I try to create a stack that will be interactive to the user. It will give a choice to pop a data one by one or all of the data. My problem is, when I try to pop just a data, it gives me empty string.
Here's my code :
package Tugas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
public class myStack {
private static Stack<Integer> stack;
private static int size;
public static void main(String[] args) {
System.out.println("Enter amount numbers : ");
size = inputData();
createStack(size);
readData();
Scanner scanner = new Scanner(System.in);
System.out.println("Take it All (y) or one by one (n)");
String input = scanner.next();
if (input.equals("y")) {
writeData();
} else {
popData();
writeData();
String confirm;
Scanner scanner2 = new Scanner(System.in);
System.out.println("Take again ? ");
confirm = scanner2.next();
if (confirm.equals("y")) {
popData();
writeData();
}
}
}
private static void createStack(int size) {
stack = new Stack<>();
}
private static void writeData() {
int dataStack;
System.out.println(" The contains of data: ");
for (int i = 0; i < size; i++) {
try {
dataStack = stack.pop();
System.out.println("Value of stack at " + (i + 1) + " : " + dataStack);
} catch (EmptyStackException e) {
}
}
}
private static void readData() {
int data;
System.out.println("===== all data =====");
for (int i = 0; i < size; i++) {
System.out.print("The data at : " + (i + 1) + " : ");
data = inputData();
stack.push(data);
}
}
private static void popData() {
int dataStack;
System.out.println("=== Pop a data : ===");
dataStack = stack.pop();
}
private static Integer inputData() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = br.readLine();
} catch (IOException ex) {
Logger.getLogger(Tumpukan.class.getName()).log(Level.SEVERE, null, ex);
}
int data = Integer.parseInt(input);
return data;
}
}
Thanks for the help ...
You pop data twice :
Once in :
popData();
And then in a loop in :
writeData();
This means writeData will be one element short, since it was already popped by popData.

How to sort a file by grade?

This is a complete program that sorts the file by ID. However, I would like to sort it by grade. I modified it several times but it doesn't seem to work. Could someone please direct me where to change the ID to grade. Also, do you think this code can be simplified or are there any other code simpler than this code.
Sorry for the bad indentation, this source code can also be found here.
student.txt file:
4 A 87 A
5 B 99 A+
1 C 75 A
2 D 55 C
3 E 68 B
source:
import java.io.*;
import java.util.*;
class ShowData implements Comparable {
int id;
String name;
int marks;
String grade;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getMarks() {
return marks;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getGrade() {
return grade;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowData))
throw new ClassCastException("Error");
int ide = ((ShowData) Student).getId();
return this.id - ide;
}
}
public class SortFile {
SortFile() {
int j = 0;
ShowData data[] = new ShowData[5];
try {
FileInputStream fstream = new FileInputStream("C:/student.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
ArrayList list = new ArrayList();
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split(" ");
String id = "", name = "", marks = "", grade = "";
for (int i = 0; i < splitSt.length; i++) {
id = splitSt[0];
name = splitSt[1];
marks = splitSt[2];
grade = splitSt[3];
}
data[j] = new ShowData();
data[j].setId(Integer.parseInt(id));
data[j].setName(name);
data[j].setMarks(Integer.parseInt(marks));
data[j].setGrade(grade);
j++;
}
Arrays.sort(data);
File file = new File("C:/new.txt");
FileWriter fw = new FileWriter(file, true);
BufferedWriter out = new BufferedWriter(fw);
System.out.println("********Sorted by id********");
String strVal = "";
for (int i = 0; i < 5; i++) {
ShowData show = data[i];
int no = show.getId();
String name = show.getName();
int marks = show.getMarks();
String grade = show.getGrade();
System.out.println(no + " " + name + " " + marks + " " + grade);
String d = no + " " + name + " " + marks + " " + grade;
ArrayList al = new ArrayList();
al.add(d + "\n");
Iterator itr1 = al.iterator();
while (itr1.hasNext()) {
out.write(itr1.next().toString());
out.newLine();
}
}
out.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
SortFile data = new SortFile();
}
}
The compareTo() method is currently comparing the IDs, not the grades. Try compare the
marks instead.

I'm getting a NullPointerException error in Eclipse

I'm getting a NullPointerException error in Eclipse. Code as it stands right now:
Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System. * ;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib() {}
public MadLib(String fileName) {
//load stuff
try {
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e) {
out.println("Houston we have a problem!");
}
}
public void loadNouns() {
nouns = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("nouns.dat");
while (chopper.hasNext()) {
nouns.add(chopper.next());
}
chopper.close();
out.println(nouns);
}
catch(Exception e) {
out.println("Will");
}
}
public void loadVerbs() {
verbs = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("verbs.dat");
while (chopper.hasNext()) {
verbs.add(chopper.next());
}
chopper.close();
}
catch(Exception e) {
out.println("run");
}
}
public void loadAdjectives() {
adjectives = new ArrayList < String > ();
try {
Scanner chopper = new Scanner("adjectives.dat");
while (chopper.hasNext()) {
adjectives.add(chopper.next());
}
chopper.close();
}
catch(Exception e) {}
}
public String getRandomVerb() {
String verb = "";
int num = 0;
num = (int)(Math.random() * verbs.size());
verb = verbs.get(num);
return verb;
}
public String getRandomNoun() {
String noun = "";
int num = 0;
num = (int)(Math.random() * nouns.size());
noun = nouns.get(num);
return noun;
}
public String getRandomAdjective() {
String adj = "";
int num = 0;
num = (int)(Math.random() * adjectives.size());
adj = adjectives.get(num);
return adj;
}
public String toString() {
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
Eclipse is pointing to the issue occurring at the linenum = (int)(Math.random()*nouns.size()); but this seems to not make much sense to me.
I have the private ArrayList<String> initialized at the method loadNouns. I origianlly had ArrayList<String> nouns initialized at getRandomNoun(), but that threw a different error, so I was advised to move the initialization statement to the loadNouns method.
Runner Class:
import static java.lang.System.*;
public class Lab16d
public static void main( String args[] ) {
//make a new MadLib
MadLib fun = new MadLib();
out.println(fun);
}
Update:
The real issue appears to be that ArrayList<String> nouns never is "loaded up" with the separate strings which are supposed to be scanned in from the nouns.dat file
Update 2:
Java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System. * ;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib() {
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName) {
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try {
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e) {
out.println("Houston we have a problem!");
}
}
public void loadNouns() {
nouns = new ArrayList < String > ();
try {
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File("nouns.dat"));
//chopper.nextLine();
while (chopper.hasNext()) {
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e) {
out.println("Will");
}
}
public void loadVerbs() {
verbs = new ArrayList < String > ();
try {
Scanner chopper = new Scanner(new File("verbs.dat"));
while (chopper.hasNext()) {
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e) {
out.println("run");
}
}
public void loadAdjectives() {
adjectives = new ArrayList < String > ();
try {
Scanner chopper = new Scanner(new File("adjectives.dat"));
while (chopper.hasNext()) {
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e) {}
}
public String getRandomVerb() {
String verb = "";
int num = 0;
num = (int)(Math.random() * (verbs.size() - 1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun() {
String noun = "";
int num = 0;
if (nouns == null) {
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size() - 1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective() {
String adj = "";
int num = 0;
num = (int)(Math.random() * (adjectives.size() - 1));
adj = adjectives.get(num);
return adj;
}
public String toString() {
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
You are creating an instance of MadLib, then printing the object in a println in your Runner class...
//make a new MadLib
MadLib fun = new MadLib();
out.println(fun);
The out.println calls the toString() method you overrode in MadLib...
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
Your MadLib object has 3 ArrayLists you never initialized, so they are null...
private ArrayList<String> verbs;
private ArrayList<String> nouns;
private ArrayList<String> adjectives
The easiest way to fix the NullPointerException is to initialize the variables....
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
However, what I really think you want to do is load all the nouns, verbs and adjectives when your object is constructed so your toString actually prints something useful. I'd add this to your constructor as well...
public MadLib() {
loadNouns();
loadVerbs();
loadAdjectives();
}
Edit: Your getRandom methods need to check if the list is empty to avoid the IndexOutOfBounds exception as well...
public String getRandomVerb() {
String verb = "";
if (!verbs.isEmpty()) {
int num = (int) (Math.random() * verbs.size() - 1);
verb = verbs.get(num);
}
return verb;
}
public String getRandomNoun() {
String noun = "";
if (!nouns.isEmpty()) {
int num = (int) (Math.random() * nouns.size() - 1);
noun = nouns.get(num);
}
return noun;
}
public String getRandomAdjective() {
String adj = "";
if (!adjectives.isEmpty()) {
int num = (int) (Math.random() * adjectives.size());
adj = adjectives.get(num);
}
return adj;
}
Hope that helps

Categories