I am having issues with my gpa program where I have to use two arrays to store a grade and it's credits and calculate the gpa. So far, everything else seems to be working except the gpa wont calculate correctly and I am not sure what I am missing (probably simple).
My code thus far is:
Gpa class:
import java.util.*;
public class Gpa{
int[] credits = new int[4];
String[] grades = new String[4];
private int numCourses;
private int maxCourses;
private int sumOfCourses;
private int sumCredits;
private int sumPoints;
int newCredits;
int totalSum = 0;
int total = 0;
public Gpa(int noCourses){
maxCourses = noCourses;
numCourses = 0;
}
public void addCourse(int _newCredits, String newGrade){
for (int i=0; i<maxCourses; i++){
newCredits = _newCredits;
credits[i] = newCredits;
}
for (int i=0; i<maxCourses; i++){
grades[i] = newGrade;
}
switch (newGrade) {
case "A":
case "a":
newGrade = "4";
break;
case "B":
case "b":
newGrade = "3";
break;
case "C":
case "c":
newGrade = "2";
break;
case "D":
case "d":
newGrade = "1";
break;
case "F":
case "f":
newGrade = "0";
break;
}
sumPoints = sumPoints + (newCredits * Integer.parseInt(newGrade));
numCourses++;
}
public double calcGPA(){
for (int i=0; i<maxCourses; i++){
sumCredits = sumCredits + newCredits;
}
double gpa = (double)sumPoints/sumCredits;
return gpa;
}
} // end class
The tester class:
import java.util.Scanner;
public class GpaTestEx2
{
public static void main (String[] args)
{
//declarations
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa myGPA = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
myGPA.addCourse(credits, grade);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", myGPA.calcGPA( ));
} //end main
}
When I enter the course credits and grade it does not calculate the gpa correctly. For example, if the user input says there are 2 courses with one class having 4 credits with a grade of A and the other having 3 credits with a grade of B. I get a gpa of around 4.17 when it should be 3.57.
Any help would be great, I may or may not be missing something simple.
It seems like you are indexing into every element in your array every time someone inserts a value. We only need to change one element when a new grade is added. GPA class:
public class Gpa {
private int[] credits;
private String[] grades;
private int currentGrade;
public Gpa(int numGrades) {
credits = new int[numGrades];
grades = new String[numGrades];
currentGrade = 0;
}
public void addGrade(String letterGrade, int credit) {
grades[currentGrade] = letterGrade;
credits[currentGrade] = credit;
currentGrade = currentGrade + 1;
}
public double getGpa() {
double totalPoints = 0;
double totalWeight = 0;
for (int i = 0; i < currentGrade; i++) {
totalPoints = totalPoints + (letterToGpa(grades[i]) * credits[i]);
totalWeight = totalWeight + credits[i];
}
return totalPoints / totalWeight;
}
private double letterToGpa(String letter) {
char first = letter.toUpperCase().charAt(0);
switch (first) {
case 'A':
return 4.0;
case 'B':
return 3.0;
case 'C':
return 2.0;
case 'D':
return 1.0;
}
return 0.0;
}
}
The test class should work fine now:
public static void main(String[] args) {
Scanner in = new Scanner(System.in); //input object
int numCourses; //number of courses - can be changed
int credits; //number of credits for a course
String grade; //grade for course
//read in number of courses
System.out.print("Enter number of courses: ");
numCourses = in.nextInt();
//create Gpa object to hold specified number of courses
Gpa t = new Gpa(numCourses);
//read in all courses and add course information to Gpa object
for (int k=0; k<numCourses; k++)
{
System.out.print("Enter credits for course " + (k+1) + ": ");
credits = in.nextInt();
System.out.print("Enter grade for course " + (k+1) + ": ");
grade = in.next();
t.addGrade(grade, credits);
}
//print results
System.out.println();
System.out.printf("GPA is %4.2f%n", t.getGpa());
}
Just want to note that this clearly isn't the best way of doing this, nor does it follow Object Oriented patterns very well, but the OP's assignment requires we only use one class, etc.
Related
I'm generally new to Java. Today i tried to make a program that has terminal menu on it, when i run my code the menu run comepletely fine for the first time but when it try to run twice i get this error
Exception in thread "main" java.util.NoSuchElementException: No line found
This is the full message:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at helloworld.displayMenu.display(displayMenu.java:17)
at helloworld.Main.main(Main.java:6)
This is my code:
package helloworld;
import java.util.Scanner;
public class displayMenu {
static void display() {
try (Scanner scanner = new Scanner(System.in)) {
int userChoice = 0;
do {
System.out.println("\t MENU");
System.out.println("1. Execute Part 1");
System.out.println("2. Execute Part 2");
System.out.println("3. Execute Part 3");
System.out.println("4. Exit");
System.out.print("Choose program you want to run (1-4): ");
userChoice = 0;
String nextIntString = scanner.nextLine(); //get the number as a single line
userChoice = Integer.parseInt(nextIntString); //convert the string to an int
switch(userChoice) { //start program corresponding to user input
case 1:
part1.run();
break;
case 2:
part2.run();
break;
case 3:
part3.run();
break;
case 4:
System.out.println("Exiting...");
break;
default: //prompt the user when they input wrong
System.out.println("Your input is wrong (1-4)");
}
}while(userChoice != 4);
}
}
}
How can this run for the first time but not the second time?
I had tried to use
while(scanner.hasnextLine()){
String nextIntString = scanner.nextLine();
userChoice = Integer.parseInt(nextIntString);
}
but it doesn't solve my problem
Here's also part 1-3 and main code if you need it!
Main:
package helloworld;
public class Main {
public static void main(String[] args) {
displayMenu.display();
}
}
Part 1:
package helloworld;
import java.util.Scanner;
public class part1 {
static void run(){
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
float avg = 0;
System.out.print("Input column: ");
int columns = scanner.nextInt();
System.out.print("Input row: ");
int rows = scanner.nextInt();
int[][] arr = new int[columns][rows];
//Loop input x y
for(int i = 0; i < columns; i++) {
for(int j = 0; j < rows; j++) {
System.out.print("Input number at ["+i+"]["+j+"]: ");
arr[i][j] = scanner.nextInt();
}
}
//Calculate Sum
for(int i = 0; i < columns; i++) {
for(int j = 0; j < rows; j++) {
sum += arr[i][j];
}
}
System.out.println("Your matrix is:");
//Calculate array
avg = (float)sum / (columns*rows);
//Display array
for(int i = 0; i < columns; i++) {
for(int j = 0; j < rows; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
//Display sum
System.out.println("Sum: "+ sum);
//Display average
System.out.printf("Average: "+ "%.2f", avg);
System.out.println("");
}
}
}
Part 2:
package helloworld;
import java.util.Scanner;
public class part2 {
static void run() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Input number 1: ");
float num1 = scanner.nextFloat();
System.out.print("Input number 2: ");
float num2 = scanner.nextFloat();
System.out.print("Input the operator (+-*/): ");
char inputChar = scanner.next().charAt(0);
switch(inputChar) {
case '+':
System.out.println("The result is: " + (num1 + num2));
break;
case '-':
System.out.println("The result is: " + (num1 - num2));
break;
case '*':
System.out.println("The result is: " + (num1 * num2));
break;
case '/':
System.out.println("The result is: " + (num1 / num2));
break;
default:
System.out.println("Invalid Input");
}
}
}
}
Part 3:
package helloworld;
import java.util.Scanner;
public class part3 {
static void run() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Input number of names you want to input: ");
int numberofStudents = scanner.nextInt();
String [] listofStudents = new String[numberofStudents];
for(int i = 0; i < numberofStudents; i++) {
System.out.print("Input the name of student number "+(i+1)+": ");
listofStudents[i] = scanner.nextLine();
scanner.nextInt();
}
for(int i = 0; i < numberofStudents; i++) {
listofStudents[i] = listofStudents[i].toUpperCase();
}
System.out.println("The complete list of student which are converted to upper case:");
for(int i = 0; i < numberofStudents; i++) {
System.out.println((i+1)+"."+listofStudents[i]);
}
}
}
}
In each of the part# classes, you are defining a new Scanner based on the standard input stream. You are using try with resources, which means the Scanner closes after the try block. This in turn also closes the input stream associated with that Scanner. In this case that is the standard input stream, shared between all Scanners in your program. Once that input stream is closed, no Scanner can read from it. See this minimal example, which causes the same exception:
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
scanner1.close();
Scanner scanner2 = new Scanner(System.in);
scanner2.nextLine();
}
To fix this, try passing the scanner along to your run methods instead of declaring a new one, and remove the try block in those methods.
I am making a program which allows the user to look at student's grades, find the average, find the highest grade, the lowest etc. For one of the methods I have, it checks for the average of the values that the user entered. I tried to do this but to no avail. Here is the specific code:
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
For some better context, here is the rest of the code:
import java.util.Scanner;
public class StudentGradeArray {
static Scanner input = new Scanner(System.in);
static String[] studentName;
static String letterGrade = " ";
static int[] studentGrade;
static int gradeMax = 0;
static int gradeMin = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("How many students are you entering into the database?");
int numOfKids = input.nextInt();
studentGrade = new int[numOfKids];
studentName = new String[numOfKids];
for (int i = 0; i < numOfKids; i++) {
System.out.println("Enter the student's name:");
studentName[i] = input.next();
System.out.println("Enter " + studentName[i] + "'s grade");
studentGrade[i] = input.nextInt();
}
do {
System.out.println("");
System.out.println("Enter a number for the following options:");
System.out.println("");
System.out.println("1. Student's letter grade");
System.out.println("2. Search for a student and their grade");
System.out.println("3. The class average");
System.out.println("4. The student with the highest grade");
System.out.println("5. The student with the lowest grade");
System.out.println("6. List of students that are failing");
System.out.println("7. Quit the program");
int options = input.nextInt();
switch(options) {
case 1:
letterGrade(options); break;
case 2:
searchStudent(); break;
case 3:
classAvg(options); break;
case 4:
markHighest(options); break;
case 5:
markLowest(options); break;
case 6:
markFailing(options); break;
case 7:
return;
default:
System.out.println("");
System.out.println("Please enter a valid option.");
System.out.println(""); break;
}
} while (!input.equals(7));
System.out.println("Program Terminated.");
}
public static void letterGrade(int numOfKids) {
System.out.println("Enter a grade: A, B, C, D, F");
letterGrade = input.next();
if (letterGrade.equalsIgnoreCase("a")) {
gradeMax = 100;
gradeMin = 80;
}
if (letterGrade.equalsIgnoreCase("b")) {
gradeMax = 79;
gradeMin = 70;
}
if (letterGrade.equalsIgnoreCase("c")) {
gradeMax = 69;
gradeMin = 60;
}
if (letterGrade.equalsIgnoreCase("d")) {
gradeMax = 59;
gradeMin = 50;
}
if (letterGrade.equalsIgnoreCase("f")) {
gradeMax = 49;
gradeMin = 0;
}
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] <= gradeMax && studentGrade[i] >= gradeMin) {
System.out.println(studentName[i] + " has a " + letterGrade);
System.out.println(letterGrade + " is equivalent to " + gradeMin + " - " + gradeMax + "%");
}
}
}
public static void searchStudent() {
}
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
public static void markHighest(int numOfKids) {
int highestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] > highestNum) {
highestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + highestNum + "%");
}
public static void markLowest(int numOfKids) {
int lowestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < lowestNum) {
lowestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + lowestNum + "%");
}
public static void markFailing(int numOfKids) {
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < 50) {
System.out.println(studentName[i] + " is failing with a mark of " + studentGrade[i] + "%");
}
}
}
}
Looks like the argument passed to the classAvg() is not the numOfKids (or size of array) but the option selected by the user from the menu. Trying passing 'numOfKids' instead of passing 'options' as an argument to the function
case 3:
classAvg(options); break;
Better still use studentGrade.length instead of passing argument.
case 3:
classAvg(options); break;
You are passing in the options, but the method wants numOfKids. In this case options will always be 3.
Try passing in numOfKids instead.
Another problem I see is that both average and numOfKids are integers, which causes chopping remainders and rounding to 0 if the denominator is greater. Perhaps change from
average = (average/numOfKids) * 100;
to
average = ((double) average)/ numOfKids * 100;
I think it is better to create a class called Student, with properties name and grade. for more OOP design.
public class Student{
int[] grades;
String name;
public Student(int[] grade, String name){
this.grade = grade;
this.name = name;
}
public double getAverage(){
return (average/(double)numOfKids) * 100;
}
...
}
And average is of type int and numOfKids too, so the division is not gonna be precise. try this average = (average/(double)numOfKids) * 100;
.split() Method is NOT Allowed
I was got some help earlier from a helpful guy! I was just wondering if anyone could help me modify this a little bit more,
The code is meant for an assignment and It is based on the input from the scanner. It has two other classes but this is the one of interest.
The code is working at the moment, however The things that have to be input are things like **U5, D10** etc. That works fine. However I need the code to be able to read multiple String off one one line whilst seperating them like they are now. Like say for example **D10 U5 L4**, all from one line for just one player out of two. The code at the moment is not recognizing it as one line and instead if assigning the second typed thing to the second player.
Any tips?
Thanks
import java.util.Scanner;
class Asgn2
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
Player me = new Player("Player1");
Player opponent = new Player("player2");
int startingLoop = 0;
String strA;
int turn =1;
System.out.print("How many turns will the game have: ");
int turnsInGame = scan.nextInt();
System.out.print("How many moves does each player have each turn: ");
int numberOfTurns = scan.nextInt();
for(int i = turnsInGame; startingLoop < i; startingLoop++)
{
System.out.print("Turn " + turn++ + "\n");
System.out.print("Player 1 what are your " + numberOfTurns + " move(s): ");
String userInput = scan.next();
System.out.print("Player 2 what are your " + numberOfTurns + " move(s): ");
String userInputOne = scan.next();
for (int j = 0; j < userInput.length() - 1; j++)
{
char letter = userInput.charAt(j);
String num = "";
for(int k= j + 1; k < userInput.length(); k++)
{
j++;
if(userInput.charAt(k)!=' ')
{
num+=userInput.charAt(k);
}
else
{
break;
}
}
int integer = Integer.parseInt(num + "");
strA = Character.toString(letter);
switch(strA) //For player oneChooses which value to add or subtract from based on what is input.
{
case "U":
me.move(moveSteps.UP , integer);
break;
case "D":
me.move(moveSteps.DOWN, integer);
break;
case "L":
me.move(moveSteps.LEFT, integer);
break;
case "R":
me.move(moveSteps.RIGHT, integer);
break;
}
//Player 2
for (int playerTwo = 0; playerTwo < userInputOne.length() - 1; playerTwo++)
{
char letterTwo = userInputOne.charAt(0);
String numTwo = "";
String strB = Character.toString(letterTwo);
for(int m= playerTwo + 1; m<userInput.length(); m++)
{
playerTwo++;
if(userInputOne.charAt(playerTwo)!=' ')
{
numTwo+=userInputOne.charAt(playerTwo);
}
else
{
break;
}
}
int stepsMoved = Integer.parseInt(numTwo + "");
switch(strB) //For player two
{
case "U":
opponent.move(moveSteps.UP , stepsMoved);
break;
case "D":
opponent.move(moveSteps.DOWN, stepsMoved);
break;
case "L":
opponent.move(moveSteps.LEFT, stepsMoved);
break;
case "R":
opponent.move(moveSteps.RIGHT, stepsMoved);
break;
}
}
}
System.out.print(me);
System.out.print(opponent);
}
}
}
Once you assign the input to a String, use the .split() method to split the string into an array. To use the .split(), put in the character you want to split it with. In this case a space. For example use this for your current project: .split(" "). Once you split it, you can access it just like any array.
Update:
first use the .nextLine() and assign it to a temporary string variable. Then
you can create another scanner and put a string in. For example:
Scanner sc = new Scanner(YOUR TEMPORARY VARIABLE);
you can now use the .next() to get individual strings.
Here is the Asgn2 class
import java.util.Scanner;
public class Asgn2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name player 1: ");
String p1name = scan.nextLine();
System.out.print("What is your name player 2: ");
String p2name = scan.nextLine();
Player p1 = new Player(p1name);
Player p2 = new Player(p2name);
System.out.print("How many turns will the game have: ");
int numTurns = scan.nextInt();
System.out.print("How many moves does each player have each turn: ");
int numMoves = scan.nextInt();
for (int turn = 1; turn <= numTurns; turn++) {
System.out.println("----------------");
System.out.println("Turn number " + turn);
System.out.println("----------------");
for (int player = 1; player <= 2; player++) {
System.out.print("Player " + player + " what are your " + numMoves + " move(s): ");
for(int move=1;move<=numMoves;move++){
String currMove = scan.next();//splits at space;
char dir = currMove.charAt(0);//gets dir
String temp="";
for(int index=1;index<currMove.length();index++){
temp+=currMove.charAt(index);
}
int dist = Integer.parseInt(temp);
if(player==1){
p1.move(dir, dist);
}else if(player==2){
p2.move(dir, dist);
}
}
System.out.println("Player 1 is at " + p1.getPos() + " and Player 2 is at " + p2.getPos());
System.out.println();
}
}
}
}
And here is the Player class
public class Player {
private String name;
private int locX = 0;
private int locY = 0;
public Player(String name) {
this.name = name;
}
public void move(char dir, int numSteps) {
switch (dir) {
case 'U':
locY += numSteps;
break;
case 'D':
locY -= numSteps;
break;
case 'L':
locX -= numSteps;
break;
case 'R':
locX += numSteps;
break;
}
}
public String getPos() {
return "(" + locX + ", " + locY + ")";
}
public String getName() {
return name;
}
}
And before anyone goes and says that posting blocks of code does not help OP, I am in a chatroom with him in which I explain this stuff, so dont hate :)
call the method .nextLine() instead of .next(). I think that should solve your problem.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm doing an assignment on modular programing and here Im getting a bracket expected error. Here is the code:
import java.util.*;
public class stlab09
{
public static void main (String args[])
{
System.out.println("\nLAB09 90 POINT VERSION\n\n");
enterData();
computeGPA();
displayData();
}
static String lGrade1;
static String lGrade2;
static String lGrade3;
static String lGrade4;
static int cHours1;
static int cHours2;
static int cHours3;
static int cHours4;
static String dummy;
public static double gpa;
public static void enterData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter course 1 Grade ===>> ");
lGrade1 = in.nextLine();
System.out.print("enter course 1 Hours ===>> ");
cHours1 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 2 Grade ===>> ");
lGrade2 = in.nextLine();
System.out.print("enter course 2 Hours ===>> ");
cHours2 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 3 Grade ===>> ");
lGrade3 = in.nextLine();
System.out.print("enter course 3 Hours ===>> ");
cHours3 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 4 Grade ===>> ");
lGrade4 = in.nextLine();
System.out.print("enter course 4 Hours ===>> ");
cHours4 = in.nextInt(); dummy = in.nextLine();
}
public static void computeGPA()
{
Grades.gradeValue();
Grades.courseValue();
Grades.getGPA();
}
public static void displayData()
{
System.out.println();
System.out.println("Course1 Grade: " + lGrade1 + " Course1 Credit Hours: " + cHours1);
System.out.println("Course2 Grade: " + lGrade2 + " Course2 Credit Hours: " + cHours2);
System.out.println("Course3 Grade: " + lGrade3 + " Course3 Credit Hours: " + cHours3);
System.out.println("Course4 Grade: " + lGrade4 + " Course4 Credit Hours: " + cHours4);
System.out.println();
System.out.println("Current GPA: " + gpa);
}
}
public class Grades() ***<<<<<<<<<<<<<<<<<< bracket expected here***
{
public static void gradeValue()
{
int value = 0;
char lg1 = lGrade1.charAt(0);
switch(lg1)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal1 = value;
char lg2 = lGrade2.charAt(0);
switch(lg2)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal2 = value;
char lg3 = lGrade3.charAt(0);
switch(lg3)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal3 = value;
char lg4 = lGrade4.charAt(0);
switch(lg4)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal4 = value;
}
public static void courseValue()
{
int cVal1 = gVal1 * cHours1;
int cVal2 = gVal2 * cHours2;
int cVal3 = gVal3 * cHours3;
int cVal4 = gVal4 * cHours4;
}
public static void getGPA()
{
double totalValue = cVal1 + cVal2 + cVal3 + cVal4;
double totalHours = cHours1 + cHours2 + cHours3 + cHours4;
double gpa = totalValue / totalHours;
}
}
So yeah I need some help figuring this out because I'm kinda going crazy about it. The expected program is supposed to use keyboard input of letter grades and course hours to compute GPA and grades. The assignment is to get that outcome but the main method must stay exactly as is, and almost every method was provided to me and i just had to organize them.
You have declared the inner class Grades as if it's a method (you added () onto the end of it), look at how the class stlab09 is declared, there aren't any ().
If anyone can see where I've gone made a mistake in my code I would be eternally grateful. I recognize that it's an obscene amount of code, but I've been pulling my hair out with it over the last few days and simply cannot fathom what to do with it. I've asked others for help in my class but they cannot see where I have gone wrong. It's to do with carriage return scanner problem.
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at PropertyMenu.runMenu(PropertyMenu.java:109)
at PropertyMenu.main(PropertyMenu.java:7)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Any thoughts would be much appreciated.
Joe.
//ROOM CLASS
import java.util.Scanner;
public class Room{
private String description;
private double length;
private double width;
public Room (String description, double length, double width) {
this.description = description;
this.length = length;
this.width = width;
}
public Room(){
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter description of room:");
description = scan.next();
System.out.println("Enter length of room:");
length = scan.nextDouble();
System.out.println("Enter width of room:");
width = scan.nextDouble();
}
public double getArea () {
return length*width;
}
#Override
public String toString() {
String result = ("***********************************\n");
result +=(" Room Viewing \n");
result +=("************************************\n");
result +=("The width of the room is " + width + "m.\n");
result +=("the length of the room is " + length + "m.\n");
result +=("the name of the room is: " + description +".\n");
return result;
}
}
//HOUSE CLASS
import java.util.*;
public class House {
private ArrayList<Room> abode;
private int idNum, numRooms;
private double totalArea;
private static int internalCount = 1;
private String address, roomInfo, houseType;
public House (String address, String houseType, int numRooms){
System.out.println("THIS IS THE START OF MY 3 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
System.out.println("THIS IS THE END OF MY 3 ARGUMENT CONSTRUCTOR");
}
public House (String address, String houseType, int numRooms, String roomInfo){
System.out.println("THIS IS THE START OF MY 4 ARGUMENT CONSTRUCTOR");
idNum = internalCount++;
this.address = address;
this.houseType = houseType;
this.numRooms = numRooms;
this.roomInfo = roomInfo;
Scanner scan = new Scanner(roomInfo);
String desc;
Double l;
Double w;
while (scan.hasNext()){
desc= scan.next();
l = Double.parseDouble(scan.next());
System.out.println("the length from here"+l);
w = Double.parseDouble(scan.next());
System.out.println("the width from here"+w);
new Room (desc,l,w);
}
System.out.println("THIS IS THE END OF MY 4 ARGUMENT CONSTRUCTOR");
}
public void addRoom (){
totalArea=0;
abode.add(new Room ());
for (int i=0; i<abode.size(); i++){
totalArea += abode.get(i).getArea();
}
}
public House () {
totalArea = 0;
abode = new ArrayList<Room>();
idNum = ++internalCount;
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\n");
System.out.println("Enter address of house:");
address = scan.next();
System.out.println("Enter number of rooms:");
numRooms = scan.nextInt();
System.out.println("Enter type of house:");
houseType = scan.next();
for (int i=1; i<=numRooms; i++){
addRoom();
}
}
int getIdNum() {
return idNum;
}
#Override
public String toString() {
String result =("************************************\n");
result +=(" House Viewing \n");
result +=("************************************\n");
result +=("The house ID is " + idNum +".\n");
result +=("The house address is " + address +".\n");
result +=("The number of rooms here is " + numRooms +".\n");
result +=("The house type is " + houseType +".\n");
result +=("The total area of the house is " + totalArea +".\n");
result +=(abode);
return result;
}
}
//DRIVER
import java.util.*;
import java.io.*;
public class PropertyMenu {
private ArrayList<House> properties =new ArrayList<House>();
public static void main (String[] args) throws IOException{
PropertyMenu menu = new PropertyMenu();
menu.runMenu();
}
public void runMenu() {
House h = null;
char selection = ' ';
Scanner s = new Scanner(System.in);
while (selection != 'e') {
System.out.println();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Welcome to my Property database");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("What do you want to do?");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("To ADD a house enter......A");
System.out.println("To VIEW a house enter.....V");
System.out.println("To DELETE a house enter...D");
System.out.println("To USE a file.............F");
System.out.println("To QUIT enter.............E");
selection = s.next().toLowerCase().charAt(0);
switch (selection) {
case 'a':
properties.add(new House());
break;
case 'v':
System.out.println("Do you want to view all houses (y/n)?");
String all = "";
all = s.next();
if (all.equalsIgnoreCase("y")){
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)));
}
}
else if(all.equalsIgnoreCase("n")){
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to view.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to view:");
int viewHouse = s.nextInt();
if (viewHouse <= properties.size() && viewHouse >= 1){
System.out.println(properties.get(viewHouse-1));
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
else{
System.out.println("Do you want to view all houses (y/n)?");
all = s.next();
}
break;
case 'd':
System.out.println(""+ properties.size() +" houses have been created, choose the id of the house you wish to delete.. (1/2/3 etc...)");
System.out.println("List of property ID's: ");
for (int i=0; i<properties.size(); i++){
System.out.println("Property ID: "+ (properties.get(i)).getIdNum());
}
System.out.println("Enter ID of the house you wish to delete:");
int deleteHouse = s.nextInt();
if (deleteHouse <= properties.size() && deleteHouse >= 1){
properties.remove(deleteHouse -1);
}
else{
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" House Not Present ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
break;
case 'e':
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Goodbye ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
break;
//*********************************THIS IS WHERE MY PROBLEM IS, FROM HERE*************
case 'f':
try{
Scanner fileScan = new Scanner (new File("property.txt"));
while (fileScan.hasNext()){
System.out.println("THIS IS A FRESH LOOP");
String a;
String ht;
String rms1;
int rms;
String yn;
String rmInfo;
a = fileScan.nextLine();
System.out.println("ADDRESS"+a);
ht = fileScan.nextLine();
System.out.println("HOUSE TYPE"+ht);
rms1 = fileScan.next();
rms = Integer.parseInt(rms1);
System.out.println("HOUSEROOMs"+rms);
yn = fileScan.next();
String overflow = fileScan.nextLine();
System.out.println("Yes/no"+yn);
if (yn.equalsIgnoreCase("Y")){
System.out.println("THIS IS THE START OF CHOICE = Y");
rmInfo = fileScan.nextLine();
properties.add(new House(a, ht, rms, rmInfo));
System.out.println("THIS IS THE END OF CHOICE = Y");
}
else{
System.out.println("THIS IS THE START OF CHOICE = N");
properties.add(new House(a, ht, rms));
System.out.println("THIS IS THE END OF CHOICE = N");
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
//******************************************TO HERE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
default:
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Try again! ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
System.out.println("Exiting program.");
}
}
This is could be a guess that you are not reading file correctly. Whatever I see from your block of file reading code and input file "property.txt" , make following changes.
In your while use following, as you are reading file line by line.
while (fileScan.hasNextLine()){
Only use nextLine() method
rms1 = fileScan.nextLine();
yn = fileScan.nextLine();
I hope these will solve your problem.