I am trying to read data from a text file named Marathon_Data.txt and when I run, this error shows up:
"Exception in thread "main" java.util.InputMismatchException"
We had not yet learned how to handle exceptions, so thus far have only been using throws IOException. Would this be causing the issue?
Thanks
import java.io.*;
import java.util.Scanner;
public class Marathon
{
final static int SIZE = 5;
public static void main(String[] args) throws IOException
{
int miles[][] = new int[SIZE][7];
String names[] = new String[SIZE];
//variables
int i=0, j=0;
int totalWeek = 0;
double average = 0.0;
//opening file
File file = new File("Marathon_Data.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
j=0;
names[i]=inputFile.next();
while(inputFile.hasNext())
{
miles[i][j]=inputFile.nextInt();
j++;
}
i++;
}
//Display total miles ran in each week by each runner and their average
System.out.println("Name Total Miles Average");
for(i=0;i<miles.length;i++)
{
System.out.print(names[i]);
for(j=0;j<miles[0].length;j++)
{
totalWeek +=miles[i][j];
}
average = (double)totalWeek / miles[0].length;
System.out.printf("%d\t\t%.2f\n", totalWeek, average);
totalWeek = 0;
}
}//end main method
}//end class
Related
I keep running into the same complier error in my program. Any ideas on what is stopping the program from compiling. The error I recieve is ----jGRASP wedge2: exit code for process is 1.
import java.util.Scanner;
public class CheckerboardV1
{
static Scanner keyboard = new Scanner(System.in);
static final char FULL_CHAR = '*';
static final char EMPTY_CHAR = '-';
public static void main(String[] args)
{
System.out.println("Checkerboard Version 1 ...");
System.out.print("Enter size:>");
int size = keyboard.nextInt();
row(size);
}
public static int row(int size)
{
for(int i=0;i<size;i++) //How Deep
{
for(int n=0;n<4;n++) //Fills one line
{
for(int m=0;m<size;m++) //Empty Characters
{
System.out.print(EMPTY_CHAR);
}
for(int m=0;m<size;m++)
{
System.out.print(FULL_CHAR); //Full Characters
}
}
System.out.println(); //Starts new Line
return size;
}
}
}
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 am in desperate need of more help this week. My professor is sub par and makes no effort to clear things up.
The Problem:
import a file and search for a specific piece of data that is requested by a user.
The output must return something similar to:
Sequential found ID number 77470, and its price is $49.55.
or
Sequential did not find ID number 77777.
I have no idea where to go from here, or even if this is correct....
public class MainClass
{
public static void main(String[] args)
{
Payroll acmePay = new Payroll();
Scanner myScanner = new Scanner(System.in);
int target;
acmePay.loadEmpNums();
System.out.println("Enter the product number you would like to search: ");
target = myScanner.nextInt();
System.out.print(acmePay.seqSearch(target));
myScanner.close();
}//END main
}//END class MainClass
Payroll Class:
public class Payroll
{
private int[] empNums = new int[1000];
private int empCount = 0;
Payroll(){} //Currently nothing done in constructor
public void loadEmpNums()
{
String name;
double salary;
empCount = 0; //Just to make sure!
try
{
String filename = "employees.dat";
Scanner infile = new Scanner (new FileInputStream(filename));
while (infile.hasNext())
{
//Read a complete record
empNums[empCount] = infile.nextInt();
name = infile.nextLine();
salary = infile.nextDouble();
//Increment the count of elements
++empCount;
}
infile.close();
}
catch (IOException ex)
{
//If file has problems, set the count to -1
empCount = -1;
ex.printStackTrace();
}
}//END loadEmpNums
public int seqSearch (int target)
{
int ind = 0;
int found = -1;
while (ind < empCount) {
if(target==empNums[ind])
{
found = ind;
ind = empCount;
}
else
{
++ind;
}
}
return found;
}
}//END class Payroll
Are you reading in from a txt file or are they entering the data in when you run the program?
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.
I've been working on an assignment for quite sometime now. The program compiles fine, but when ran, the driver class does not produce any results. The program I'm writing extends another class and is used to find the average word length of a text file as well as how often words with one letter, two letters, three letters, etc appear (any word that is 15 or greater letters is grouped).
Here is the class of which mine extends:
public abstract class FileAccessor{
String fileName;
Scanner scan;
public FileAccessor(String f) throws IOException{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
public void processFile() {
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
protected abstract void processLine(String line);
public void writeToFile(String data, String fileName) throws IOException{
PrintWriter pw = new PrintWriter(fileName);
pw.print(data);
pw.close();
}
}
Here is my work:
import java.util.Scanner;
import java.io.*;
public class WordPercentages extends FileAccessor{
int[] length1 = new int[15];
double[] percentages = new double[15];
int totalWords = 0;
double average = 0.0;
public WordPercentages(String s)throws IOException{
super(s);
}
public void processLine(String file){
super.fileName=file;
while(super.scan.hasNext()){
totalWords+=1;
String s = super.scan.next();
if (s.length() < 15){
length1[s.length()]+=1;
}
else if(s.length() >= 15){
length1[15]+=1;
}
}
}
public double[] getWordPercentages(){
for(int j = 1; j < percentages.length; j++){
percentages[j] += length1[j];
percentages[j]=(percentages[j]/totalWords)*100;
}
return percentages;
}
public double getAvgWordLength(){
for(int j = 1; j<(percentages.length); j++){
average+=((j*(percentages[j])/totalWords));
}
return average;
}
}
And here is the driver class:
import java.util.Scanner;
import java.io.IOException;
public class WordPercentagesDriver{
public static void main(String[] args) throws IOException{
try{
String fileName;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a text file name to analyze:");
fileName = scan.nextLine();
System.out.println("Analyzed text: " + fileName);
WordPercentages wp = new WordPercentages(fileName);
wp.processFile();
double [] results = wp.getWordPercentages();
printWordSizePercentages(results);
System.out.printf("average word length: %4.2f",wp.getAvgWordLength());
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void printWordSizePercentages(double[] data){
for(int i = 1; i < data.length; i++)
if (i==data.length-1)
System.out.printf("words of length " + (i) + " or greater: %4.2f%%\n",data[i]);
else
System.out.printf("words of length " + (i) + ": %4.2f%%\n",data[i]);
}
}
I've tried placing a text file with known results in the same folder, everything complies, I then type in the name of the text file (including the .txt) and unfortunately nothing happens. Any help would be greatly appreciated.
NOTE: The FileAccessor Class and the Driver class were both provided by my instructor, so any source of error would come from the WordPercentage class.
Just ran the code, It looks like your code is throwing a "FileNotFoundExeption". What you have to do to fix this is place the file that you are looking for into the workspace you are working in. You can either save the txt file into your workspace or specify where the txt file is located. Example: C:Programs/documents/Alice...
good luck!