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.
Related
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");
}
This is what I have tried:
I have tried to print matrix in isDeadlock method ,output is all zeros and seems like the value that called matrix after reading file is not kept and cannot be used in method.
import java.io.*;
import java.util.*;
public class Findcycle {
static int[][] matrix = new int[10000][10000];
public static void main(String[] args) {
{
int x=0, y=0;
try
{
BufferedReader in = new BufferedReader(new FileReader("TestCase1.txt"));
String line;
while ((line = in.readLine()) != null)
{
String[] values = line.split(",");
for (String str : values)
{
int str_int = Integer.parseInt(str);
matrix[x][y]=str_int;
System.out.print(matrix[x][y] + " ");
y=y+1;
}
System.out.println("");
x=x+1;
}
in.close();
System.out.println(isDeadlock(matrix));
}catch( IOException ioException ) {}
}
}
public static class Node{
int id;
List<Node> getNodes = new ArrayList<Node>();
public Node(int id){
this.id=id;
}
}
public static String isDeadlock(int matrix[][]){
List<Node> nodes = new ArrayList<Node>();
for(int i=0;i<matrix.length;i++) {
for(int j=0;j<matrix[i].length;j++) {
System.out.println(matrix[i][j]);
}
}
...
}
What should I do to fix this problem?
I am a newbie.
Thank you so much
When you are reading the file and filling the matrix you are not resetting y for each new line. So after x=x+1; you need to add y = 0; otherwise y will just continue to grow and all consecutive line will have there data offset more and more to the right.
Not a bug but since matrix is a static variable you don't need to send it as a parameter to isDeadlock.
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"));
public class Main {
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(tex));
reader.close();
}
public static int calculateCharacters(String text, int tex){
tex = text.length();
return tex;
}
}
So I receive a string from String text, then I send it to the method to calculate it's length and return a number which should be intercepted by System.out.println(calculateCharacters(tex)); and the probram should show me the number of letters in the string that was entered, the problem is: nothing reaches System.out.println(calculateCharacters(tex)); why ? where is this return tex; returning it then ?
Well I'm not entirely sure why you've got an int texvariable, but removing it lets this work perfectly. Try rewriting your method:
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
or if you're ready to be snazzy:
public static int calculateCharacters(String text) {
return text.length();
}
Java is pass-by-value (Is Java "pass-by-reference" or "pass-by-value"?), so keeping an extra int in there that you only use to store things locally won't actually change your value of tex.
Also, you instantiate the String text, but then pass tex to calculateCharacters(). Since you haven't created a texvariable before this, your compiler doesn't know what to pass to calculateCharacters(). Try changing that to:
System.out.println(calculateCharacters(text));
instead.
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(text));
reader.close();
}
public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}
}
It works
For counting the string use below code...
public class Main {
static int stringCount;
public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
calculateCharacters(text);
System.out.println(stringCount);
reader.close();
}
public static int calculateCharacters(String text){
stringCount = text.length();
return stringCount;
}
}
I am currently trying to complete this program and I'm having trouble with this error. I've done many things trying to fix it so I can compile it but it won't work. It seems that the "String alphabet" is getting the error. Can someone help me solve this please?
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
// here is one spot that mainly the error pops up?
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
Your sort method is treating alphabet (the String) as an array. String is not a char[] but you can call String.toCharArray() like
private void sort(char toArray)
{
char[] alpha = alphabet.toLowerCase().toCharArray();
int placement=charToInt(toArray);
if (placement<0)
{
alpha[26]=1;
}
else
{
alpha[placement]=alpha[placement]+1;
}
alphabet = new String(alpha, "UTF-8");
}
But modifying a String is not possible, because they are immutable. For the same reason your raw call alphabet.toLowerCase() doesn't modify the alphabet in your other method.
The variable alphabet is defined as a String data type, but you need to define it as an array if you want to reference it using the bracket notation [] you have in your code. The error message is pretty clear in this case.
String[] example = new String[3];
example[0] = "Hello";
example[1] = "ETC...";