Read data from text file print to terminal and new text file - java

I want to read data from a text file and print the output to both the terminal and a text file. I have a loop that reads for numbers and one that reads for non-numerical characters, but nothing is printing out to the terminal. i am new to programming.
I am transforming an old project to a new one by the way.
package studenttester;
public class Student
{
private String name;
double quizScore;
double quizAverage;
private int numQuizzes;
String grade;
/**
* Returns the name of a student
*
* #return the name of the student
*/
public Student (String inName)
{
name = inName;
quizAverage = 0;
quizScore = 0;
numQuizzes = 0;
}
public String getName()
{
return name;
}
/**
* Adds a quiz score to the total quiz score of the student
*
* #param score the score of a quiz
*/
void addQuiz(int score)
{
numQuizzes += 1;
quizScore += score;
}
/**
* Returns the total score of all the quizzes combined that student took
*
* #return the value of score
*/
double getTotalScore()
{
return quizScore;
}
/**
* Returns the average score of all the quizzes a student took
*
* #return
*/
double getAverageScore()
{
return quizScore / numQuizzes;
}
}
package studenttester;
import java.io.*;
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Student Name Number of Quizzes Average");
Scanner reader = new Scanner(new File("quizScores.txt"));
String studentName = "", first="", last="";
while (!reader.hasNext("-10"))
{
}
while (reader.hasNextDouble())
{
first = first+reader.next();
studentName = last + first;
}
Student newStudent = new Student(studentName);
while (reader.hasNextDouble() && !reader.hasNext("-10"))
{
System.out.printf("");
}
{
// writer.close;
}
}
}

The "red underline" means an compiler error, I guess.
Have a look to your while loop, it seems to be wrong.
Try ...
while (reader.hasNextDouble() && (!reader.hasNext("-10")))
System.out.printf("");
}
reader.close();
instead.

Related

Creating transcripts in java using array

so im very new to programming so sorry if is an inane question
But i have been given a homework where i have to create a transcript with java using array,
first i have to enter the students name and code, then the peogram should tell me to enter each lesson’s grade individually
And the result should display the student’s name,code and the grades i have entered for each lecture
I know how to enter make the program prompt me with each lecture and grade entry but showing all the grades i have entered next to thier lecture is what im stuck on
I would highly appreciate it if i get an answer.
Thanks
Take a look at this code, if there is something obscure, ask for clarification.
MainClass.java class
public class MainClass {
static boolean flag = true;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
//create new student
Student student = new Student();
//print out enter name of a student
System.out.println("Enter name of student: ");
//read students name from next line
student.setNameOfStudent(keyboard.nextLine());
//print out enter code of a student
System.out.println("Enter code of student: ");
//read students password from a next line
student.setPasswordOfStudent(keyboard.nextLine());
//create a list of lectures to add them to a student
List<Lecture> lectures = new ArrayList<>();
//do adding lectures and grades for them while N is not pressed
do {
// enter new lecture name
System.out.println("Add a lecture? Y or N ");
//take answer for adding a lecture from a next input
String answerForAddingLecture = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answerForAddingLecture)) {
// print enter a name of a lecture
System.out.println("Enter a name of a lecture? ");
//take a lecture name from next input
String lectureName = keyboard.next();
// create a lecture
Lecture lecture = new Lecture();
// set lecture name from lectureName variable
lecture.setNameOfLecture(lectureName);
//create a list of grades
List<Grade> listOfGrades = new ArrayList<>();
//do inside brackets while flag is set to true
do {
//print Add a grade for this lecture? Y or N
System.out.println("Add a grade for this lecture? Y or N ");
//set an answer variable from the next input
String answer = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answer)) {
//print what grade is it going to be?
System.out.println("What grade is it going to be?");
//create new grade object
Grade grade = new Grade();
//set temp variable to next int input
int temp = keyboard.nextInt();
//set grade value to the value of temp variable
grade.setGrade(temp);
// add this grade to a list of grades
listOfGrades.add(grade);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answer)) {
//set flag to false
flag = false;
}
}
//do above as long as flag is set to true
while (flag);
//reset flag to true again for keep adding new lectures
flag = true;
//set a list of grades to a lecture grades list
lecture.setGradesOfLecture(listOfGrades);
//set a lecture to a list of lectures
lectures.add(lecture);
//set a list of lectures to a students lecture list
student.setLecturesOfStudent(lectures);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answerForAddingLecture)) {
flag = false;
}
} while (flag);
//print a student with all lectures and grades
System.out.println(student.toString());
}
}
Student.java class
public class Student {
private String nameOfStudent;
private String passwordOfStudent;
private List<Lecture> lecturesOfStudent;
public Student() {
}
public Student(String nameOfStudent, String passwordOfStudent, List<Lecture> lecturesOfStudent) {
this.nameOfStudent = nameOfStudent;
this.passwordOfStudent = passwordOfStudent;
this.lecturesOfStudent = lecturesOfStudent;
}
/**
* #return the nameOfStudent
*/
public String getNameOfStudent() {
return nameOfStudent;
}
/**
* #param nameOfStudent the nameOfStudent to set
*/
public void setNameOfStudent(String nameOfStudent) {
this.nameOfStudent = nameOfStudent;
}
/**
* #return the passwordOfStudent
*/
public String getPasswordOfStudent() {
return passwordOfStudent;
}
/**
* #param passwordOfStudent the passwordOfStudent to set
*/
public void setPasswordOfStudent(String passwordOfStudent) {
this.passwordOfStudent = passwordOfStudent;
}
/**
* #return the lecturesOfStudent
*/
public List<Lecture> getLecturesOfStudent() {
return lecturesOfStudent;
}
/**
* #param lecturesOfStudent the lecturesOfStudent to set
*/
public void setLecturesOfStudent(List<Lecture> lecturesOfStudent) {
this.lecturesOfStudent = lecturesOfStudent;
}
public String getLecturesWithGrades() {
String temp = "\nLectures:";
for (Lecture l : getLecturesOfStudent()) {
temp += "\n" + l.getNameOfLecture();
temp += "\nGrades:\n";
for (Grade g : l.getGradesOfLecture()) {
temp += g.getGrade() + " ";
}
}
return temp;
}
#Override
public String toString() {
return "Student: " + getNameOfStudent() + " with a code: " + getPasswordOfStudent() + getLecturesWithGrades();
}
}
Lecture.java class
public class Lecture {
private String nameOfLecture;
private List<Grade> gradesOfLecture;
public Lecture() {
}
public Lecture(String nameOfLecture, List<Grade> gradesOfLecture) {
this.nameOfLecture = nameOfLecture;
this.gradesOfLecture = gradesOfLecture;
}
public String getNameOfLecture() {
return nameOfLecture;
}
public List<Grade> getGradesOfLecture() {
return gradesOfLecture;
}
public void setNameOfLecture(String nameOfLecture) {
this.nameOfLecture = nameOfLecture;
}
public void setGradesOfLecture(List<Grade> gradesOfLecture) {
this.gradesOfLecture = gradesOfLecture;
}
#Override
public String toString() {
return getNameOfLecture() + " " + getGradesOfLecture();
}
}
Grade.java class
/**
* Might add remarks on grades or any other properties some time later, therefore new
* object is created called Grade.
* #author
*/
public class Grade {
int grade;
public Grade() {
}
public Grade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
#Override
public String toString() {
return getGrade() + " ";
}
}

Java menu displaying twice after input

Hey guys I have been working on this program for class the past couple hours and just cant seem to get these last 2 issues resolved. Its basically a slightly modified CashRegister class with basic functions through a menu. The problems I am having are:
1) After the user makes a menu selection for the first time, every subsequent time the menu shows up in console twice and I cant seem to find a fix for this.
2) Also whenever I choose to display the content of my CashRegister, the first line is always output as 0.00 no matter the input.
Here is my CashRegister class followed by my tester:
import java.util.ArrayList;
/**
*
*/
/**
* #author Cole
*
*/
public class CashRegister {
private double dailyTotal;
private double totalPrice;
ArrayList<Double> items;
/**
Constructs a cash register with cleared item count and total.
*/
public CashRegister()
{
items = new ArrayList<Double>();
dailyTotal = 0;
totalPrice= 0;
}
/**
Adds an item to this cash register.
#param price the price of this item
*/
public void addItem(double price)
{
items.add(price);
dailyTotal = dailyTotal + price;
}
/**
Gets the price of all items in the current sale.
#return the total amount
*/
public double getTotal()
{
for(int x=0; x<items.size(); x++){
totalPrice = totalPrice + items.get(x);
}
return totalPrice;
}
/**
Gets the number of items in the current sale.
#return the item count
*/
public int getCount()
{
return items.size();
}
/**
Clears the item count and the total.
*/
public void clear()
{
items.clear();
totalPrice = 0;
}
public void display(){
for(int x=0; x<items.size(); x++){
System.out.printf("%10.2f%n", items.get(x));
}
System.out.println("------------------------------");
}
public double getDailyTotal(){
dailyTotal = dailyTotal + totalPrice;
return dailyTotal;
}
}
import java.util.ArrayList;
import java.util.Scanner;
/**
*
*/
/**
* #author Cole
*
*/
public class Prog2 {
/**
* #param args
*/
public static final String MENU = "******************************************\n" +
"* Enter \"n\" to start a new Cash Register. *\n" +
"* Enter \"a\" to add an item to the current Cash Register. *\n" +
"* Enter \"d\" to display the total of the current Cash Register. *\n" +
"* Enter \"e\" to exit the program. *\n" +
"******************************************";
public static final String NEW_CUSTOMER = "n";
public static final String ADD_ITEM = "a";
public static final String DISPLAY = "d";
public static final String EXIT = "e";
public static void main(String[] args) {
// TODO Auto-generated method stub
CashRegister register = new CashRegister();
Scanner keyboard = new Scanner(System.in);
String input;
double userInput = 0;
do {
input = printMenu(keyboard);
if(input.equals(NEW_CUSTOMER)){
register.getDailyTotal();
register.clear();
}
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
register.addItem(userInput);
userInput = keyboard.nextDouble();
}
else if(input.equalsIgnoreCase(DISPLAY)){
register.display();
System.out.println("Total: " + register.getTotal());
System.out.println("Item Count: " +register.getCount());
}
else if(input.equalsIgnoreCase(EXIT)){
System.out.printf("Daily Sales Total: " + "%.2f%n",register.getDailyTotal());
System.out.println("Program Ended...");
break;
}
}while(input != EXIT);
}
public static String printMenu(Scanner input){ //this method displays the menu for the user
String response = "no reponse yet";
System.out.println(MENU);
response = input.nextLine();
return response; //response returned based on the users input
}
}
You need to get input from the user before you add the item, that's why you are getting a 0 for your first item. Since your value for userInput is set to 0 at the beginning and your statements are switched you will always initialy create an item with 0.0 for it's value and all the other values will be one step behind the actual inputs.
else if(input.equals(ADD_ITEM)){
System.out.println("Please enter the price of the item: ");
userInput = keyboard.nextDouble();
register.addItem(userInput);
}

Java - object can't store data

My dad and I narrowed it down to the object can't store the data. also, I'm new to java. The code is supposed to print in the console the first name, last name, grade, and grade average. I think the problem is in public double getCalcGraeAverage() but correct me if wrong, please.
import java.util.Scanner;
/**
* Write a description of class Student here.
*
* #author XXXX
* #version XXXX
*/
public class Student
{
String firstName;
String lastName;
int gradeLevel;
double gradeAverage;
int totalAssignments;
double totalPoints;
/**
* Create a new student with student's name, grade, and average
*/
public Student(String newFirstName, String newLastName, int newGradeLevel, double newGradeAverage)
{
firstName = newFirstName;
lastName = newLastName;
gradeLevel = newGradeLevel;
gradeAverage = newGradeAverage = 0.0;
}
/**
* Return the student's first name.
*/
public String getFirstName()
{
return firstName;
}
/**
* Return the student's last name.
*/
public String getLastName()
{
return lastName;
}
/**
* Return the grade level of the student.
*/
public int getGradeLevel()
{
return gradeLevel;
}
/**
* Calculates grade average.
*/
public double getCalcGradeAverage()
{
double gradeAverage = totalAssignments / totalPoints;
return gradeAverage;
}
public static void main (String[] args)
{
Student student1 = new Student ("XXXX", "XXXX", 11, 0.0);
System.out.println("The student's first name is: " + student1.getFirstName());
System.out.println("The student's last name is: " + student1.getLastName());
System.out.println("The student's grade level is: " + student1.getGradeLevel());
System.out.println("Please enter the total assignment points the student has earned: ");
Scanner input = new Scanner(System.in);
Double totalAssignments = input.nextDouble();
System.out.println("Please enter the number of assignments given: ");
double totalpoints = input.nextDouble();
System.out.println(student1.getFirstName() + " " + student1.getLastName() + " average grade is" + student1.getCalcGradeAverage());
}
}
In your code you are :
creating a Student student1 object
reading totalAssignments, totalpoints from System.in
calling student1.getCalcGradeAverage()
between steps 2 and 3 you have to set the fields totalAssignments, totalpoints of student to the values you read or they will retain their default values of zero. E.g.
student1.totalAssignments = totalAssignments;
student1.totalpoints = totalpoints;
Also, since totalAssignments is of type int, you probably want to read it as:
int totalAssignments = input.nextInt();
When writing your code, you declare variables for the student class with class scope.
int totalAssignments;
double totalPoints;
those class scope variable are used in the method :getCalcGradeAverage()
totalAssignments of Student and totalPoints of student are used in this method
When you create a new Student those variable are equals to zero because not affected by a value in your constructor.
in the main method when you writes :
Double totalAssignments =
you declare a new variable named "totalAssignments" with a method scope.When the method ends, the variable reference goes away and there is no way to access that variable any longer.
you can consider that the variable decalred is not the same that the student variable: student.totalAssignments is always equals to zero because no value affected to him.
Then assuming that you can do that :
student1.totalAssignments = input.nextInt();
student1.totalPoints = input.nextDouble();

Formatting an output

having trouble with my output. It prints in the correct format as long as the last digit isn't a zero. In other words, it will output $1.75 but for $1.50 I get $1.5. I know the "%.2f" is supposed to format it but I can't figure out where to put it in my code. Thanks!
/**
This Class is designed to work with an application program for a Vending Machine.
*/
public class VendingMachine
{
private double money;
private double amountDue;
private double change;
private String selection;
/**
Constructor for the Class.
*/
public VendingMachine()
{
money = 0.00;
amountDue = 0.00;
change = 0.00;
selection = "";
}
/**
Explicit Constructor for the class that gives variables more specific values.
*/
public VendingMachine(double money, double change, double amountDue, String selection)
{
this.money = money;
this.amountDue = amountDue;
this.change = change;
this.selection = selection;
}
/**
Accesssor method for the selection.
#return the selection of the user.
*/
public String getSelection()
{
return selection;
}
/**
Accessor method to get the amount of money the user puts in the machine.
#return the amount of money.
*/
public double getMoney()
{
return money;
}
/**
Accessor method for the amount due.
#return the amount due.
*/
public double getAmountDue()
{
return amountDue;
}
/**
Accessor method for getting the user's change.
#return the user's change.
*/
public double getChange()
{
return change;
}
/**
Mutator method for the selection.
#param the selection of the user.
*/
public void setSelection(String selection)
{
this.selection = selection;
}
/**
Mutator method for money.
#param the money put into machine.
*/
public void setMoney(double money)
{
this.money = money;
}
/**
Mutator method for amount due.
#param the selection of the user.
*/
public double setAmountDue(String selection)
{
if (selection.equals("A1") || selection.equals("A2") || selection.equals("A3"))
{
amountDue = 1.25;
}
else if (selection.equals("B1") || selection.equals("B2") || selection.equals("B3"))
{
amountDue = 1.00;
}
else if (selection.equals("C1") || selection.equals("C2") || selection.equals("C3"))
{
amountDue = 1.50;
}
return amountDue;
}
/**
Mutator method for the change.
#param the money put into machine.
*/
public void setChange(double money)
{
change = money - amountDue;
this.change = change;
}
/**
Method for converting all variables into a String statement.
#return a String of the total transaction.
*/
public String toString()
{
return ("Your selection: " + selection + "\nYour amount due: " + amountDue + "\nYour change: " + change);
}
}
import java.util.*;
/**
This program runs a Vending Machine and interacts with the user.
*/
public class VendingMachineTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input;
String[] choices = {"A1~~SNICKERS~~~~~~~~$1.25", "A2~~MILKY WAY~~~~~~~$1.25" , "A3~~TWIX~~~~~~~~~~~~$1.25",
"B1~~ORIGINAL CHIPS~~$1.00", "B2~~BBQ CHIPS~~~~~~~$1.00" , "B3~~PRETZELS~~~~~~~~$1.00",
"C1~~COKE~~~~~~~~~~~~$1.50", "C2~~SPRITE~~~~~~~~~~$1.50", "C3~~DR. PEPPER~~~~~~$1.50",
};
displayItems(choices);
VendingMachine user = new VendingMachine();
do
{
System.out.print("Please make your selection: ");
input = in.nextLine();
}
while (!(input.equals("A1") || input.equals("A2") || input.equals("A3") ||
(input.equals("B1") || input.equals("B2") || input.equals("B3") ||
(input.equals("C1") || input.equals("C2") || input.equals("C3")))));
user.setSelection(input);
user.setAmountDue(input);
System.out.print("Enter the amount you put in the machine: ");
double amount = in.nextDouble();
user.setMoney(amount);
user.setChange(amount);
System.out.println(user);
System.out.print("Thank You for your purchase!");
}
/**
A method for displaying all of the options in the machine.
#param an array of choices
#return an array of choices.
*/
public static void displayItems(String[] choices)
{
for (int i = 0; i < choices.length; i++)
{
System.out.print(choices[i]);
System.out.println();
}
return;
}
}
This should do the trick:
public String toString() {
return String.format( "Your selection: %s: \nYour amount due: %.2f \nYour change: %.2f",
selection,
amountDue,
change);
}

Why does this array go out of bounds inconsistently?

This is a Student class I have which creates a student that has a name, grade, and ID number. The Student is used as the key in a TreeMap, while the student's grade is used as the value. I wrote compareTo as I am implementing Comparable, but this error pops up upon entering in the first student:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Student.<init>(Student.java:25)
at Main.main(Main.java:50)
Java Result: 1
I think it is coming from the splitting of the student's name into a String[], but I've tested those lines that call the first and last names, as well as the line that splits the name and they all seem to work as intended, except for when they are called in compareTo.
Any help would be much appreciated.
public class Student implements Comparable<Student>{
private String name, grade, first, last;
private String[] stuName;
private int id;
/**
* Constructs a new Student with a name, ID Number, and a grade.
* #param n name
* #param i ID Number
* #param g grade
*/
public Student(String n, int i, String g){
name = n;
id = i;
grade = g;
stuName = n.split(" ");
first = stuName[0];
last = stuName[1];
}
/**
* Compares Students. First by last name, then by first if the last names
* are the same. If the first names are also the same, the students are
* compared by their ID Numbers.
* #return the value upon comparing the proper property of the Student
*/
#Override
public int compareTo(Student other){
if (last.equals(other.getLast())){
if (first.equals(other.getFirst())){
return id - other.getID();
}else
return first.compareTo(other.getFirst());
}
return last.compareTo(other.getLast());
}
/**
* Changes the student's current grade.
* #param g new grade
*/
public void changeGrade(String g){
grade = g;
}
/**
* Returns student's name.
* #return name
*/
public String getName(){
return name;
}
/**
* Returns student's first name.
* #return first name
*/
public String getFirst(){
return first;
}
/**
* Returns student's last name.
* #return last name
*/
public String getLast(){
return last;
}
/**
* Returns the student's grade.
* #return grade
*/
public String getGrade(){
return grade;
}
/**
* Returns the student's ID Number
* #return id number
*/
public int getID(){
return id;
}
Tester:
public class Main {
public static void main(String[] args) throws InterruptedException{
Map<Student, String> students = new TreeMap();
Scanner in = new Scanner(System.in);
System.out.println("How many students do you want to add?");
int numStudents = in.nextInt();
String name, grade;
int id;
for (int i = 1; i < numStudents; i++){
System.out.println("Name of student " + i + "?");
name = in.nextLine();
in.nextLine();
System.out.println("Grade of " + i + "?");
grade = in.nextLine();
System.out.println("ID Number of " + i + "?");
id = in.nextInt();
Student s = new Student(name, id, grade);
students.put(s, s.getGrade());
}
System.out.println("How many students do want to remove");
int remStudents = in.nextInt();
for (int i = 0; i < remStudents; i++){
System.out.println("ID?");
int remID = in.nextInt();
for (Student s : students.keySet()){
if (s.getID() == remID){
students.remove(s);
}
}
}
System.out.println("How many grades do you want to change?");
int changeGrades = in.nextInt();
for (int i = 0; i < changeGrades; i++){
System.out.println("ID?");
int foo = in.nextInt();
System.out.println("New grade?");
String newGrade = in.nextLine();
for (Student s : students.keySet()){
if (s.getID() == foo){
s.changeGrade(newGrade);
}
}
}
String printout = "";
for (Student s : students.keySet()){
printout += s.getLast() + ", " + s.getFirst() + " (" + s.getID() + "): " + s.getGrade() + "\n";
}
System.out.println(printout);
}
}
Probably because you have two different loops, with different indices:
in your one loop, you start from 1, and thus you are 1 student short:
for (int i = 1; i < numStudents; i++){
in the delete loop you have a 0-based index:
for (int i = 0; i < remStudents; i++){
I suspect that, you think you add 2 studends, but really you have just one (at index 0), and thus your indexout-of-bounds exception.
EDIT, OP has added a 'full' stack for the exception, and the above answer is not related to the OP's problem.....
Answer 2: Based on your revised stack/exception edit, the only possible answer is that there are no spaces in the student's name..... your assertion that there is always a space is simply not true ....
you may want to add a count qualifiewr to the split so that you will get an empty string on any invalid input:
stuName = n.split(" ", 2);

Categories