Method in another Class not returning anything - java

I'm working on a project that creates a Hangman game. The GameManager Class should call the getRandomAnswer method from the AnswerBank Class, which should return a random answer of two nouns from a file called noun_noun.txt (I've placed this file in the first level of the project folder). However, whenever I try to test the code, the console produces nothing after typing "yes" when prompted. Can anyone help?
public class GameManager {
private ArrayList<String> puzzleHistory;
private int numPuzzlesSolved;
private AnswerBank bank;
public GameManager(String fn) throws IOException{
numPuzzlesSolved = 0;
puzzleHistory = new ArrayList<String>();
this.bank = new AnswerBank(fn);
}
public static void main(String[] args) throws IOException {
GameManager obj = new GameManager("noun_noun.txt");
obj.run();
}
public void run() throws FileNotFoundException{
Scanner scan = new Scanner(System.in);
System.out.println("Would you like to play Hangman? Please type 'yes' or 'no'.");
String inputAns = scan.next();
if(inputAns.equalsIgnoreCase("no")){
System.exit(0);
}
else if(inputAns.equalsIgnoreCase("yes")){
System.out.println(bank.getRandomAnswer());
}
else{
System.out.println("Invalid response!");
}
scan.close();
}
}
public class AnswerBank {
private ArrayList<String> listStrings;
private File gameFile;
public AnswerBank(String fileName) throws IOException{
File gameFile = new File(fileName);
this.gameFile = gameFile;
this.listStrings = new ArrayList<String>();
}
public String getRandomAnswer() throws FileNotFoundException{
Scanner fileScan = new Scanner(gameFile);
int totalLines = 0;
while(fileScan.hasNextLine()){
totalLines++;
}
for(int i = 0; i < totalLines; i++){
this.listStrings.add(fileScan.nextLine());
}
int randInt = (int)(Math.floor ( Math.random() * totalLines));
String randAns = listStrings.get(randInt);
fileScan.close();
return randAns;
}
}
puzzleHistory and numPuzzlesSolved will be used later, so please ignore those. Thanks in advance for any help.

The problem is at here:
while (fileScan.hasNextLine()) {
totalLines++;
}
You file scanner never move position in the file, so it will keep scan the first line, and since first line is not empty, this is an infinite loop here.
A simple fix here is to count while reading words at the same time:
public String getRandomAnswer() throws FileNotFoundException {
Scanner fileScan = new Scanner(gameFile);
int totalLines = 0;
while (fileScan.hasNext()) {
totalLines++;
this.listStrings.add(fileScan.nextLine());
}
int randInt = (int) (Math.floor(Math.random() * totalLines));
String randAns = listStrings.get(randInt);
fileScan.close();
return randAns;
}
Hope it helps.

Related

How to fix my my loadData method with my main class

I am trying to load data from a txt file and it will only read one line of the txt file. When I specify what the int I variable is in my for loop within my loadData method it will print that particular line. I am not sure why it won't just add and print all my data.
I tried using an outer for loop to see if would print and add the data that way, but no luck
import java.io.*;
import java.util.*;
public class BingoSortTest
{
static BingoPlayer [] test;
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
test = new BingoPlayer [10];
loadData();
System.out.print(Arrays.toString(test));
}
public static void loadData() throws IOException
{
Scanner S = new Scanner(new FileInputStream("players.txt"));
double houseMoney = S.nextDouble();
S.nextLine();
int player = S.nextInt();
S.nextLine();
for(int i = 0; i < test.length; i++)
{
String line = S.nextLine();
String [] combo = line.split(",");
String first = combo [0];
String last = combo [1];
double playerMoney = Double.parseDouble(combo[2]);
BingoPlayer plays = new BingoPlayer(first, last, playerMoney);
add(plays);
}
}
public static void add(BingoPlayer d)
{
int count = 0;
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
}
Here is the contents of the txt file I am using:
50.00
10
James,Smith,50.0
Michael,Smith,50.0
Robert,Smith,50.0
Maria,Garcia,50.0
David,Smith,50.0
Maria,Rodriguez,50.0
Mary,Smith,50.0
Maria,Hernandez,50.0
Maria,Martinez,50.0
James,Clapper,50.0
Every Time you put a BingoPlayer at Index 0 .
public static void add(BingoPlayer d)
{
int count = 0; // <-------------------- Here
if (count< test.length)
{
test[count] = d;
count++;
}
else
System.out.println("No room");
}
you have to define static counter variable where array of BingoPlayer is defined.
define count variable static
static BingoPlayer [] test;
static int count = 0;
and chane the add function definition like this.
public static void add(BingoPlayer d)
{
if (count< test.length) {
test[count] = d;
count++;
}
else
System.out.println("No room");
}

how to scan more than one word in ArrayList in java

public class WC {
private ArrayList<String> note;
public WC() {
note = new ArrayList<String>();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
WC w1 = new WC();
w1.note.add(input.next());
}
}
but it won't scan more than one word
what should I do?
Use Loop for taking Input and storing multiple times
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
WC w1 = new WC();
// variable amount is number of times you want to enter data
int amount = 5;
for (int i = 1; i <= amount; i++) {
w1.note.add(input.next());
}
}
try something like this :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
WC w1 = new WC();
String str;
while (!(str = input.next()).equals("quit")) {
w1.note.add(str);
}
}
This way, you can just type quit and it will stop the loop

Issue with scanner in main method vs in constructor java?

SOLVED
I'm having an issue using Scanners nextInt() method in a class constructor.
it works fine if used in a main method like the code below however when doing the same thing in a constructor I get an inputmismatchexception,
what could be the possible issues?
public class QuickTest{
public static void main(String[] args) throws Exception{
java.io.File myFile = new java.io.File("tograph.txt");
java.util.Scanner input = new java.util.Scanner(myFile);
int numberOfPoints = input.nextInt();
String[] myArray = new String[numberOfPoints];
//need to use nextLine once after reading in number of points to get to next line
input.nextLine();
int count = 0;
while(input.hasNext() == true){
myArray[count] = input.nextLine();
count++;
}
input.close();
for(int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
the class version
public class MyGraph{
//filled with strings from file
String[] points;
java.io.File file;
java.util.Scanner input;
//length of points array
int numPoints;
public MyGraph(String file){
this.file = new java.io.File(file);
this.input = new java.util.Scanner(file);
this.numPoints = this.input.nextInt();
this.points = new String[this.numPoints];
fillGraphArray();
}
//after getting the number of vertices we populate the array with every
//line after those points untill the end
private void fillGraphArray(){
//used once after reading nextInt()
this.input.nextLine();
int count = 0;
while(this.input.hasNext() == true){
points[count] = input.nextLine();
count++;
}
input.close();
}
//test method to be delted later
public String[] getPoints(){
return this.points;
}
//may need a method to close the file
}
When I use the debugger the main method version will get the number of points from the file and then fill the array with a string from each following line in the file however the class version throws the exception

Having problems finding the error mentioned below that keeps program from running

I'm having some problems running the program. Whenever, I try I get the java.util.InputMismatchException.
After searching about it, I noticed that it's when I try to get data but the next data isn't of that format ( in beginner terms ).
I've tried multiple times to find what is causing the error, but I can't seem to find it :/
And for those who find this to be sloppy, since arrays aren't used. I am not allowed to use them for this particular assignment.
import java.util.Scanner;
import java.io.*;
public class Huang_Grading
{
//Global variables
private static int holdMinStudentID;
private static int holdMinEnhStudentID;
private static int holdMaxStudentID;
private static int holdMaxEnhStudentID;
private static int holdModeStudentID;
private static int holdModeEnhStudentID;
/**Main method to pull data from*/
public static void main(String[] args) throws IOException
{
//Set up input file
File inputFile = new File("gradeInput.txt");
validateFile(inputFile);
validateData(inputFile);
printData();
}
/**Read in file location, give error message if file does not exist
Also, save valid numbers to an output file*/
/**Compute and return mean of all grades*/
public static double mean(Boolean gradeType) throws IOException
{
Scanner fileInput = new Scanner("outputs.txt");
//Declare variables
double finalMean = 000.00;
double earnedGrade;
int enhancedGrade;
double totalEnhancedGrade = 0;
double totalEarnedGrade = 0;
int studentID;
int lines = 0;
//Mean grade
while(fileInput.hasNext())
{
studentID = fileInput.nextInt();
enhancedGrade = fileInput.nextInt();
earnedGrade = fileInput.nextDouble();
if(gradeType == false)
{
totalEarnedGrade = totalEarnedGrade + earnedGrade;
}
if(gradeType == true)
{
totalEarnedGrade = totalEarnedGrade + earnedGrade;
totalEnhancedGrade = totalEnhancedGrade + enhancedGrade;
}
lines++;
if(gradeType == false)
{
finalMean = totalEarnedGrade/lines;
}
if(gradeType == true)
{
finalMean = (totalEnhancedGrade + totalEarnedGrade)/lines;
}
}
fileInput.close();
return finalMean;
}
/**Compute and return minimum/maximum of all grades*/
/**Print out results*/
public static void printData() throws IOException
{
//Declare variables
Boolean earned = false;
Boolean enhanced = true;
double meanEarnedGrade = mean(earned);
double meanEnhancedGrade = mean(enhanced);
System.out.printf("%25s%7.2f", "Mean Earned Grade:\n", meanEarnedGrade);
System.out.printf("%25s%7.2f", "Mean Enhanced Grade:\n", meanEnhancedGrade);
}
}
And the answer is
change
Scanner fileInput = new Scanner("outputs.txt");
to
Scanner fileInput = new Scanner(new File ("outputs.txt"));

Arrays of Object test but not getting any output

I would like some guidance on this particular code that I am testing but currently it is not printing out anything and on top of that I feel as if it isn't reading the text file at all. It seems to finish right away with no errors and I only get prompted that "build is successful."
The assignment is to read from a data text file that list 20 lines of student information, each line is comprised of first name, last name, and their grade all seperated by spaces. I am put to it into an array and output their information, but for now I am testing to see if it will output the first name before I proceed.
public class studentClass {
private String studentFName, studentLName;
private int testScore;
private char grade;
//constructor
public studentClass(String stuFName, String stuLName, int stuTestScore){
studentFName = stuFName;
studentLName = stuLName;
testScore = stuTestScore;
}
public String getStudentFName(){
return studentFName;
}
public String getStudentLName(){
return studentLName;
}
public int getTestScore(){
return testScore;
}
public char getGrade(){
return grade;
}
public void setStudentFName(String f){
studentFName = f;
}
public void setStudentLName(String l){
studentLName = l;
}
public void setTestScore(int t){
if (t>=0 && t<=100){
testScore = t;
}
}
public void setGrade(char g){
grade = g;
}
}
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
for(int i = 0; i>studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
public static studentClass[] readStudentData(studentClass[] studentObject)throws IOException{
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String lines = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((lines = br.readLine()) != null){
String stuArray[] = lines.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
return studentObject;
}
You need to actually call the method to read in the data. Try the following (note I didn't handle the Exception. I leave that as an exercise to you)
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
//NOTE I CHANGED THE '>' TO '<'
for(int i = 0; i < studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
//Note that I changed the return type to void
public static void readStudentData(studentClass[] studentObject)throws IOException{
//Your code here
You'll see I changed your readStudentData to return void since you're passing the array into the method you don't need to return it. You'll need to remove the return at the end of it.
You could also leave it as a method returning a studentClass[] and have no parameters. Instead, create the studentClass array inside readStudentData. I would recommend that approach because it removes the need to create and pass the array, which complicates your main method.

Categories