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
Related
I need a lit help here. So I want my first method to read the file "./data/textfiles/zahlen01.txt" (there are some numbers i want to add together, this works). And I want my second method to do the same but with a string in the method. So how do i name the method in the main method?
public static double countSumOf(Scanner in) {
PrintWriter out = new PrintWriter(System.out);
double sum = 0;
while (in.hasNext()) {
double b = in.nextDouble();
sum = sum + b;
}
out.println(sum);
out.flush();
return sum;
}
public static double countSumOf(String filename) {
DirtyFileReader dfr = new DirtyFileReader(filename);
Scanner in = new Scanner(dfr);
return countSumOf(in);
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
PrintWriter out= new PrintWriter (System.out);
DirtyFileReader dfr = new DirtyFileReader("./data/textfiles/zahlen01.txt");
Scanner in = new Scanner(dfr);
countSumOf(in);
countSumOf();
out.flush();
}
Not sure I correctly understand so I rephrase:
You want to sum up some numbers, once using a file as source that contains the numbers and once using a java string that contains the numbers?
I found this interesting piece of code:
https://github.com/alquesh/PR1PRAXIS/blob/master/PR1PRAXIS/src/pr1/a04/FirstInput.java
To sum it up: Scanner can take a String as an argument to the constructor to scan that string instead so where you have Scanner in = new Scanner(dfr); you can instead use Scanner in = new Scanner(meineZeichenkette);
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");
}
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.
I am new here so please show some patience. I am trying to read the data from an external file and store the info in 2 arrays.
The file looks like this:
0069 723.50
0085 1500.00
0091 8237.31
I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok.
My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. For that reason I read it as a String. The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same.
My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. I have tried several ways (all commented) but all fail. Please help and thanks.
Here is my code:
import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;
public class Bank {
static final int MAX_NUMBER_OF_ACCOUNTS = 50;
PrintStream out;
Bank(){
UserInterfaceFactory.enableLowResolution(true);
out = new PrintStream(System.out);
}
void readFiles(){
Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(balanceFile.hasNextLine()){
String balance_Line = balanceFile.nextLine();
Scanner accountsFile = new Scanner(balance_Line);
int account = accountsFile.nextInt(); //works
out.printf("%04d ",account);
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //does not store the values properly
int account = accountsFile.nextInt();
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = account;
}*/
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //java.util.InputMismatchException
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = accountsFile.nextInt();
//out.printf("%04d \n",accounts_array[j]);
}*/
String balance = accountsFile.nextLine(); //problem declaring balance as a double
out.printf("%s\n",balance);
/*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS]; //java.util.NoSuchElementException
for(int j=0; j < balance_array.length; j++){
accountsFile.useDelimiter(" ");
balance_array[j] = accountsFile.next();
//out.printf("%04d \n",accounts_array[j]);
}*/
}
Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(mutationsFile.hasNext()){
String mutation_Line = mutationsFile.nextLine();
Scanner mutatedAccountsFile = new Scanner(mutation_Line);
int mutated_account = mutatedAccountsFile.nextInt();
out.printf("%04d ",mutated_account);
int action = mutatedAccountsFile.nextInt(); //deposit or withdrawal
/*if (action == 1){
}else{
}*/
out.printf(" %d ",action);
/*Double amount = mutatedAccountsFile.nextDouble();
out.printf(" %5.2f ",amount);*/
String amount = mutatedAccountsFile.nextLine();
out.printf("%s\n",amount);
}
}
void start(){
new Bank();readFiles();
}
public static void main(String[] args) {
new Bank().start();
}
}
The InputMismatchException occurs because you try to read a double using the nextInt() function. To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately.
while(mutationsFile.hasNext()){
mutation_Line = mutationsFile.next();
if(mutation_Line.indexOf(".") == -1)
//token is int
else
//token is double
}
Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array.
List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
Now replace the if statements in the first snippet with this:
if(mutation_Line.indexOf(".") == -1)
intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
doubleList.add(new Double(Double.parseDouble(mutation_Line)));
In the end, you can get them into arrays:
Object[] intArr = intList.toArray(),
doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
Double.parseDouble(doubleArr[i].toString()));
OUTPUT:
0069 723.50
0085 1500.00
0091 8237.31
First off, you don't need to use 2 scanners. The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file.
If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (e.g. parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles).
Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case.
If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop.
Here's an alternative approach with the code you posted.
public class App {
static int MAX_NUMBER_OF_ACCOUNTS = 50;
static PrintStream out;
static void readFiles() {
Scanner balanceFile = null;
try {
balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (balanceFile == null)
return;
int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
int currentIndex = 0;
while (balanceFile.hasNextLine()) {
int account = balanceFile.nextInt();
double balance = balanceFile.nextDouble();
System.out.print("acc = " + account + " ");
System.out.println("bal = " + balance);
//out.printf("%04d ", account);
accounts_array[currentIndex] = account;
//out.printf("%s\n", balance);
balance_array[currentIndex] = balance;
currentIndex++;
}
balanceFile.close();
}
static void start() {
readFiles();
}
public static void main(String[] args) {
start();
}
}
Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague.
As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. The arrays are allocated prior to the while loop (note: see #progy_rock and their use of ArrayList's - may help improve your code in the long run). And finally, note the index count to move the position along in the array to which you are inserting your lines to.
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.