import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
public class AutoMobile {
private static String make;
private static String model;
private static String color;
private static int year;
private static int mileage;
private static int index =300;
public AutoMobile(String make, String model, String color, int year,
int mileage, int index) {
super();
this.make = make;
this.model = model;
this.color = color;
this.year = year;
this.mileage = mileage;
this.index = index;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public static int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
class Vehicle {
static ArrayList<AutoMobile> vehicleList = new ArrayList<>();
public static final String FILENAME = "F:\\CSU\\CSC320-01 Programming 1\\Week 8\\AutoMobile.txt";
//Prints to location with proper header, but returns package and no vehicles
public static void addVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Add Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter Vehicle color: ");
String color = s.nextLine();
System.out.print("Enter Vehicle year: ");
int year = s.nextInt();
System.out.print("Enter Vehicle mileage: ");
int mileage = s.nextInt();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
AutoMobile a = new AutoMobile(make, model, color, year, mileage, index);
vehicleList.add(a);
System.out.println("Vehicle Added Successfully");
System.out.println("------------------------");
}
public static void removeVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Remove Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model) &&
a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
iterator.remove();
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Removed Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void updateVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Update Vehicle-------");
System.out.print("Enter the make of Automobile: ");
String make = s.nextLine();
System.out.print("Enter the model of Automobile: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
System.out.println("-----Vehicle found-------");
System.out.print("Enter the new make of Automobile: ");
make = s.nextLine();
System.out.print("Enter the new model of Automobile: ");
model = s.nextLine();
System.out.print("Enter the new color of Automobile: ");
String color = s.nextLine();
System.out.print("Enter the new year of Automobile: ");
int year = s.nextInt();
System.out.print("Enter the new mileage of Automobile: ");
int mileage = s.nextInt();
a1.setMake(make);
a1.setModel(model);
a1.setColor(color);
a1.setYear(year);
a1.setMileage(mileage);
a1.setIndex(index);
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Updated Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void printfile() {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
String content = "ID Make Model Color Year Mileage\n";
bw.write(content);
Iterator itr=vehicleList.iterator();
while(itr.hasNext()){
bw.write(itr.next().toString()+"\n");
}
System.out.println("Done printing");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws FileNotFoundException {
do {
System.out
.println("============================VEHICLE OPTIONS============================");
System.out.println("1. Add Vehicle");
System.out.println("2. Remove Vehicle");
System.out.println("3. Update Vehicle");
System.out.println("4. Print Vehicle List");
System.out.println("5. Exit");
System.out
.println("=======================================================================");
System.out.println();
Scanner s = new Scanner(System.in);
System.out.print("Enter the choice: ");
int i = s.nextInt();
s.nextLine();
switch (i) {
case 1:
addVehicle();
break;
case 2:
removeVehicle();
break;
case 3:
updateVehicle();
break;
case 4:
printfile();
break;
case 5:
System.out.println("Good Bye!!!!!");
break;
default:
System.out.println("You entered the wrong choice!!!!");
System.out.println();
}
if(i==4)
break;
System.out.println();
} while (true);
PrintWriter pw = new PrintWriter("VehicleInventory");
String text ="Index,Make,Model,Color,Year,Mileage\n";
for(AutoMobile a : vehicleList){
text+=a.getIndex()+","+a.getMake()+","+a.getModel()+","+a.getColor()+","+a.getYear()+","+a.getMileage()+"\n";
}
pw.write(text);
pw.flush();
pw.close();
System.out.println("VehicleInventory file created succesfully");
System.out.println();
System.out.println(text);
}
}
Forgive my inexperience, but I am trying to compile a program for school that achieves the following.
private string make
private string model
private string color
private int year
private int mileage.
Your program should have appropriate methods such as:
default constructor
parameterized constructor
add a new vehicle method
list vehicle information (return string array)
remove a vehicle method
update vehicle attributes method.
All methods should include try..catch constructs. Except as noted all methods should return a success or failure message (failure message defined in catch).
Create an additional class to call your automobile class (e.g., Main or AutomobileInventory). Include a try..catch construct and print it to the console any errors.
Call automobile class with parameterized constructor (e.g., "make, model, color, year, mileage").
Then call the method to list the values. Loop through the array and print to the screen.
Call the remove vehicle method to clear the variables.
Print the return value.
Add a new vehicle.
Print the return value.
Call the list method and print the new vehicle information to the screen.
Update the vehicle.
Print the return value.
Call the listing method and print the information to the screen.
Display a message asking if the user wants to print the information to a file (Y or N).
Use a scanner to capture the response. If Y, print the file to a predefined location (e.g., C:\Temp\Autos.txt). Note: you may want to create a method to print the information in the main class.
If N, indicate that a file will not be printed.
I have the program working somewhat as i wanted, until i tried to assign index numbers to the user inputted vehicles for updating or removing at a later date. This does not return in the output, and all that is returning in the .txt file is the header, and my package listed, no vehicles. Any suggestions or help would be great!
index parameter is of primitive int data type
For int use = for comparing.
if (a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex() == index) {}
Related
I'm trying to create an array of math students, science students, and computer students based on the user input.
So basically the user should choose what student they want to add and then enter the student details.
Below I have added the code I have so far:
Main Java class:
public class Lab4 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(4,5);
s[1] = new MathStudent(5,7);
s[2] = new MathStudent(2,8);
s[3] = new MathStudent(3,6);
s[4] = new ScienceStudent(8,9);
s[5] = new ScienceStudent(3,6);
s[6] = new ScienceStudent(4,9);
s[7] = new ComputerStudent(6,12);
s[8] = new ComputerStudent(11,14);
s[9] = new ComputerStudent(13,17);
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(int age, String name){
this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender;
}
public String getSubjects(){
return this.getSubjects();
}
}
MathStudent class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
public MathStudent(float algebraGrade, float calculusGrade) {
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Algebra Grade: " + algebraGrade + " Calculus Grade: "
+ calculusGrade);
}
}
scienceStudent class:
public class ScienceStudent extends Student {
private float physicsGrade;
private float astronomyGrade;
/**
* Default constructor
*/
public ScienceStudent() {
super();
physicsGrade = 6;
astronomyGrade = 7;
}
public ScienceStudent(float physicsGrade, float astronomyGrade) {
this.physicsGrade = physicsGrade;
this.astronomyGrade = astronomyGrade;
}
// Getters
public void setPhysicsGrade(float physicsGrade){
this.physicsGrade = physicsGrade;
}
public void setAstronomyGrade(float astronomyGrade){
this.astronomyGrade = astronomyGrade;
}
// Setters
public float getPhysicsGrade() {
return this.physicsGrade;
}
public float getAstronomyGrade() {
return this.astronomyGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Physics Grade: " + physicsGrade + " Astronomy Grade: "
+ astronomyGrade);
}
}
computerStudent class:
public class ComputerStudent extends Student {
private float fortanGrade;
private float adaGrade;
/**
* Default constructor
*/
public ComputerStudent() {
super();
fortanGrade = 4;
adaGrade = 9;
}
public ComputerStudent(float fortanGrade, float adaGrade) {
this.fortanGrade = fortanGrade;
this.adaGrade = adaGrade;
}
// Getters
public void setFortanGrade(float fortanGrade){
this.fortanGrade = fortanGrade;
}
public void setAdaGrade(float adaGrade){
this.adaGrade = adaGrade;
}
// Setters
public float getFortanGrade() {
return this.fortanGrade;
}
public float getAdaGrade() {
return this.adaGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade);
}
}
How Would I go about this?
You can ask for the number of students with type on each input and dynamically create the object.
Here is an example
System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
int type = scannerObject.nextInt();
if(type == 1)
students[i] = new MathStudent();
}
Similarly, you can write for others.
For allowing user to enter his choice as input
You can do this(interpreted by your comments)
Pseudo code -
Print:
Enter 1 for math student
Enter 2 for Science student
Enter 3 for Comp student
Input choice
Now in your code use either multiple if else or better switch statement
switch(choice){
case 1: create object of math student
break;
case 2: create object of science student
break;
case 3:create object of comp student
break;
default: if not above by default do this
}
You could use an ArrayList and switch case to make your life easier. Your code should be like this:
import java.util.ArrayList;
import java.util.Scanner;
public class Students {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
switch (lesson) {
case "Math":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Algebra grade: ");
int alg = input.nextInt();
System.out.print("Give student's Calculus grade: ");
int calc = input.nextInt();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new MathStudent(alg, calc);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((MathStudent) st).getSubjects());
break;
case "Science":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Physics grade: ");
int physics = input.nextInt();
System.out.print("Give student's Astronomy grade: ");
int astronomy = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ScienceStudent(physics, astronomy);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ScienceStudent) st).getSubjects());
break;
case "Computers":
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's Fortran grade: ");
int fortran = input.nextInt();
System.out.print("Give student's Ada grade: ");
int ada = input.nextInt();
input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = new ComputerStudent(fortran, ada);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(((ComputerStudent) st).getSubjects());
break;
default:
System.out.println("Wrong lesson");
addMore = false;
break;
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.
Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).
Links:
Java ArrayList
Switch Case in Java
Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
I hope this helped you. If you have any questions or wanted something more you can do it.
UPDATE
The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.
package students;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
int age;
boolean addMore = true;
String name, gender;
Student st;
ArrayList<Class<?>> studentClasses = new ArrayList<>();
studentClasses.add(MathStudent.class);
studentClasses.add(ComputerStudent.class);
studentClasses.add(ScienceStudent.class);
while (addMore) {
System.out.print("Give lesson (Computers, Math, Science): ");
String lesson = input.nextLine();
addMore = false;
for (Class studentClass : studentClasses) {
try {
st = (Student) studentClass.newInstance();
if (st.getLessonName().equals(lesson)) {
// Read student's info
System.out.print("Give student's name: ");
name = input.nextLine();
System.out.print("Give student's gender: ");
gender = input.nextLine();
System.out.print("Give student's age: ");
age = input.nextInt();
System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
float firstSubj = input.nextFloat();
System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
float secondSubj = input.nextFloat();
input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )
// Create the student object and pass info
st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
st.setName(name);
st.setAge(age);
st.gender = gender;
students.add(st); // Adding the student in the list
System.out.println(st);
System.out.println(st.getSubjects());
addMore = true;
break;
}
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (addMore) {
System.out.println("Add another student? (y/n)");
String ans = input.nextLine();
addMore = ans.equals("y");
} else {
System.out.println("Wrong lesson. Try again.");
addMore = true;
}
}
System.out.println("Students");
for (Student student : students) {
System.out.println(student);
}
}
}
You also need to add the functions in the classes as mentioned bellow:
Student class:
public String getLessonName(){
return "";
}
public String[] getSubjectsNames(){
return new String[] {"", ""};
}
MathStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Algebra", "Calculus"};
}
#Override
public String getLessonName(){
return "Math";
}
ComputerStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Fortran", "Ada"};
}
#Override
public String getLessonName(){
return "Computers";
}
ScienceStudent class:
#Override
public String[] getSubjectsNames(){
return new String[] {"Physics", "Astronomy"};
}
#Override
public String getLessonName(){
return "Science";
}
Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.
You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.
I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
Need Help Some With This Error And I Can't Figure It Out. The program is suppose to read the input and save it. Exception in thread "main" java.util.InputMismatchException
ÏÏ§Ï at java.util.Scanner.throwFor(Scanner.java:864)
ÏÏ§Ï at java.util.Scanner.next(Scanner.java:1485)
ÏÏ§Ï at java.util.Scanner.nextDouble(Scanner.java:2413)
ÏÏ§Ï at Driver.main(Driver.java:112)
ÏϧÏ
===================================
import java.io.*;
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
//local constants
//local variables
String fileName = "items.txt";
Scanner scanner = null;
ItemsList itemsList = new ItemsList(5);
int i = 0;
int choice;
boolean repeat = true;
String itemName;
double price;
int qty;
scanner=new Scanner(System.in);
//****************************************************************************
//open the file and catch the exception if file not found
try
{
//create an instance of scanner
scanner = new Scanner(new File(fileName));
//read file items until end of file
while(scanner.hasNext())
{
itemName = scanner.next();
price = scanner.nextDouble();
qty=scanner.nextInt();
//Add the OneItem object to the itemList
itemsList.addItem(new OneItem(itemName, price, qty));
i++;
}
//close the file object
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
//Create an instance of Scanner class
scanner=new Scanner(System.in);
while(repeat)
{
//call menu
choice = menu();
switch(choice)
{
//Add an item to the itemsList
case 1:
System.out.println("Enter item name : ");
//read name
String name=scanner.nextLine();
System.out.println("Enter price : ");
//read string value and parse to double value
price = Double.parseDouble(scanner.nextLine());
System.out.println("Enter quantity : ");
qty=Integer.parseInt(scanner.nextLine());
//Add the OneItem to the itemsList
itemsList.addItem(new OneItem(name, price, qty));
break;
case 2:
//print the list
//print heading with specific formatter
System.out.printf("%-10s%-10s%-10s\n\n", "Item","Price","Quantity");
System.out.println(itemsList.toString());
break;
case 3:
//Terminate the program
System.out.println("Terminate the program.");
//set repeat to false
repeat=false;
break;
default:
System.out.println("Incorrect option is selected.");
break;
}
}
writeToFile(itemsList);
}
private static void writeToFile(ItemsList itemsList)
{
//Create a file name called items.txt
String filename="items.txt";
//Create a variable of Class PrintWriter
PrintWriter filewriter=null;
try
{
//create an instance of PrintWriter
filewriter=new PrintWriter(new File(filename));
//close the file writer
filewriter.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
private static int menu()
{
//Create an instance of Scanner class
Scanner keyboard=new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add item");
System.out.println("2. Display items");
System.out.println("3. Exit");
System.out.println("Enter your choice");
int choice=Integer.parseInt(keyboard.nextLine());
return choice;
}
}//end Driver class
==========================================
public class OneItem
{
//declare a variables
private String name;
private double price;
private int quantity;
//default constructor
public OneItem()
{
name = "";
price = 0;
quantity = 0;
}
//parameter constructor
public OneItem(String name, double price, int quantity)
{
this.name = name;
this.price = price;
this.quantity = quantity;
}
//toString
public String toString()
{
return String.format("%-10s%-10.2f%-10d\n", name,price,quantity);
}
}//end of the OneItem class
===========================
public class ItemsList
{
//declare variables
private OneItem items[];
private int size;
private int count;
//constructor to set items, size and count to zero
public ItemsList()
{
items = null;
size = 0;
count = 0;
}
//Parameter constructor
public ItemsList(int size)
{
items = new OneItem[size];
for (int i = 0; i < items.length; i++)
{
items[i] = new OneItem();
}
this.size = size;
count = 0;
}
//Add OneItem to the itemlist
public void addItem(OneItem item)
{
if(items.length == count)
{
resize();
items[count] = item;
count++;
}
else
{
items[count] = item;
count++;
}
}
//Resize
private void resize()
{
int oldsize = size;
count = oldsize;
int newsize = 2 * this.size;
size = newsize;
OneItem[] tempList = new OneItem[size];
for (int i = 0; i < oldsize; i++)
tempList[i] = items[i];
items = new OneItem[size];
items = tempList;
}
//getSize
public int getSize()
{
return count;
}
//toString
public String toString()
{
String description = "";
for (int i = 0; i <count; i++)
{
description += items[i].toString();
}
return description;
}
}
In the future, you need to be more clear with what the issue is. How it occurs. Error i get when entering string into purchase price is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "sdcf"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at stacktests.Driver.main(Driver.java:70)
Meaning you're not validating your input at all. Example would be:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt())
{
System.out.println("Enter an integer!");
sc.nextLine();
}
int num = sc.nextInt();
System.out.println("Thank you! (" + num + ")");
You need to disallow string entry into a numeric variable! Only once the input has been validated do you assign it to a variable.
Cheers mate.
Hey I have code for a project im trying to finish up and I keep getting array out of bounds exceptions at a certain part and would like to know how to fix it. My project is to create a reservation system using 3 classes Room,Reservation and a client class. I'm having trouble with my bookRoom class after asking for the number of guests for the room.Any help would be greatly appreciated. The exception occurs at line 57 in the reservation class. The line in question is in bold.
`
public class Reservation {
public void roomInitialization(Room[] room,int numberOfRooms,int numberOfSmokingRooms)
{
boolean smoking=true;
String[] guestName={null,null,null,null};
for (int i=0;i<numberOfRooms;i++)
{
if (i>=numberOfSmokingRooms)
smoking=false;
room[i]=new Room(smoking,false,guestName,null,i+1);
}
}
public void displayRoomsInfo(Room[] room,int numberOfRooms)
{
for (int i=0;i<numberOfRooms;i++)
{
System.out.println("Room " + room[i].getroomNumber() + "\t" +
(room[i].getsmoking()?"Smoking room":"Non-Smoking Room"));
if (room[i].getoccupied())
{
System.out.print("Phone: "+room[i].getguestPhone()+"\t");
for(int j=0;j<4;j++)
System.out.print(room[i].getguestName()[j]+"\t");
System.out.println();
}
}
}
public void bookRoom (Room[] room, int numberOfRooms)
{
displayRoomsInfo(room, numberOfRooms);
Scanner scan = new Scanner(System.in);
Scanner scans = new Scanner(System.in);
Scanner scand = new Scanner(System.in);
System.out.print("Enter a Room Number: ");
int roomNumber = scan.nextInt()-1;
if (roomNumber >=0 && roomNumber < 30){
room[roomNumber].setoccupied(true);
System.out.print("Enter a Phone Number: ");
String guestPhone = scans.nextLine();
room[roomNumber].setguestPhone(guestPhone);
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt()-1;
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++)
System.out.print("Enter guest names: ");
**guestName[guests] = scand.next();**
room[roomNumber].setguestName(guestName);
}
else
System.out.println("Enter a valid room number");
}
public void checkOut(Room[] room)
{
Scanner scan=new Scanner(System.in);
int roomNumber;
String[] nullguestName={null,null,null,null};
do
{
System.out.print("Enter the room number: ");
roomNumber=scan.nextInt()-1;
if (roomNumber>=0 && roomNumber<30)
break;
else
System.out.println("Enter a valid room number");
}while(true);
if (room[roomNumber].getoccupied())
{
room[roomNumber].setoccupied(false);
room[roomNumber].setguestPhone(null);
room[roomNumber].setguestName(nullguestName);
}
else
System.out.println("room "+(roomNumber+1)+" is already empty");
}
}
`
Code for the other classes
package hotel;
public class Room {
private boolean smoking;
private boolean occupied;
private String[] guestName=new String[4];
private String guestPhone;
private int roomNumber;
public Room (boolean smoking,boolean occupied,String[] guestName, String guestPhone,int roomNumber)
{
this.smoking=smoking;
this.occupied=occupied;
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
this.guestPhone=guestPhone;
this.roomNumber=roomNumber;
}
public void setoccupied(boolean occupied) {
this.occupied = occupied;
}
public void setsmoking(boolean smoking) {
this.smoking = smoking;
}
public void setroomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
public void setguestPhone(String guestPhone) {
this.guestPhone = guestPhone;
}
public void setguestName(String[] guestName)
{
for (int i=0;i<4;i++)
this.guestName[i]=guestName[i];
}
public boolean getsmoking() {
return this.smoking;
}
public boolean getoccupied(){
return this.occupied;
}
public String getguestPhone(){
return this.guestPhone;
}
public int getroomNumber() {
return this.roomNumber;
}
public String[] getguestName()
{
String[] tempguestName=new String[4];
for (int i=0;i<4;i++)
tempguestName[i]=this.guestName[i];
return tempguestName;
}
}
package hotel;
import java.util.Scanner;
public class ReservationDemo {
public static void main(String[]args)
{
final int numberOfRooms=30, numberOfSmokingRooms=5;
Room[] room=new Room[numberOfRooms];
Reservation reservation=new Reservation();
reservation.roomInitialization(room,numberOfRooms,numberOfSmokingRooms);
int userSelection;
Scanner scan=new Scanner(System.in);
do
{
System.out.println("Press: 1-Book room\t2-checkout\t3-display all rooms\t4-exit. ");
userSelection=scan.nextInt();
switch(userSelection)
{
case 1:
reservation.bookRoom(room,numberOfRooms);
break;
case 2:
reservation.checkOut(room);
break;
case 3:
reservation.displayRoomsInfo(room,numberOfRooms);
break;
case 4:
System.exit(0);
default:
break;
}
}while (true);
}
}
There are lots of mistake in your code.
First-- Use the following code instead of your version in Reservation class
System.out.print("Enter number of guests:(Max of 4 per room) ");
int guests = scand.nextInt();
String[] guestName = new String[guests];
for (int i=0;i<guestName.length;i++) {
System.out.print("Enter guest names: ");
guestName[i] = scand.next();
}
Second -- Use the following method in Room class instead of the existing one.
public void setguestName(String[] guestName)
{
for (int i=0;i<guestName.length;i++)
this.guestName[i]=guestName[i];
}
Let me know what you achieve
You are trying to index into the guests array using the variable guests which is the size of the array, you should be using the iteration counter variable i instead:
guestName[guests] = scand.next() should be guestName[i] = scand.next()
I am trying to make a simple JAVA program that will help a user select a car of his choice.
public class CarSelector {
static CarSelector start = new CarSelector();
public String BodyType(String a){
String hatchBack, SUV, MUV, compactSedan, sedan, saloon, miniVan, convertible, hybrid, coupe;
if(a.equalsIgnoreCase("a")){
hatchBack = "polo";
System.out.println("We recommend: " +hatchBack);
}
String b = "";
if(a.equalsIgnoreCase("b")){
SUV = "Fortuner";
System.out.println("We recommend: " +SUV);
}
if(a.equalsIgnoreCase("c")){
compactSedan = "Amaze";
System.out.println("We recommend: " +compactSedan);
}
if(a.equalsIgnoreCase("d")){
sedan = "Vento";
System.out.println("We recommend: " +sedan);
}
if(a.equalsIgnoreCase("e")){
saloon = "Corolla";
System.out.println("We recommend: " +saloon);
}
if(a.equalsIgnoreCase("f")){
MUV = "Innova";
System.out.println("We recommend: " +MUV);
}
else{
System.out.println("Incorrect choice.");
System.out.println(a);
//start.BodyType(a);
return null;
}
System.out.println("We recommend: " +a);
return null ;
}
public int PriceRange(){
int price5 = 5;
int price10 = 10;
int price15 = 15;
int price20 = 20;
int price25 = 25;
int price30 = 30;
return 0 ;
}
public String SegmentBest(){
//string type of the best cars within price range
return null;
}
public int OnRoadPrice(){
//return int of on road price
return 0;
}
public String Manufacturer(){
//all manufacturers with their models available
String Toyota, Volkswagen, Honda;
String i1= "Toyota";
String i2= "Volkswagen";
String i3= "Honda";
return null;
}
public int SeatingCapacity(){
//return integer seating capacity
return 0;
}
public String ReviewLink(){
return null;
}
public String LatestReleases(){
return null;
}
public String FuelType(){
return null;
}
public static void main (String[] args){
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
option = input.nextLine();
if( option.equalsIgnoreCase("a")){
System.out.println("A: Hatchback");
System.out.println("B: SUV");
System.out.println("C: MUV");
System.out.println("D: Sedan");
System.out.println("E: Saloon");
System.out.println("F: Compact Sedan");
String optionA = input.nextLine();
start.BodyType(optionA);
}
}
}
The code is simple. A walkthrough: The main class will prompt the user to make a choice of how he wants to choose a car. Given option "A" as a choice will run the first method. Here are my queries
Within the BodyType method, I would like to run the set of IF statements again if the user enters anything other than a,b,c,d,e,f
How can I hand the control back to the main class (run a specific code from MAIN method) and also start a method from another method (from BodyType to PriceRange). I hope I was clear. Thanks, Cheers!
you can play it now...
import java.util.Scanner;
public class CarSelector {
static CarSelector start = new CarSelector();
static String[] bodytypes = new String[]{"hatchBack", "SUV", "MUV", "compactSedan", "sedan",
"saloon", "miniVan", "convertible", "hybrid", "coupe"};
static String[] manufacturers = new String[]{"Toyota", "Volkswagen", "Honda"};
private String getBodyType(int bt) {
if(bt >= bodytypes.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + bodytypes[bt]);
return bodytypes[bt];
}
}
public static String getManufacturer(int mf) {
if(mf >= manufacturers.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + manufacturers[mf]);
return manufacturers[mf];
}
}
public static void main(String[] args) {
String bodyType = "";
String manufacturer = "";
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
pringSelectType();
option = input.nextLine();
while(!option.equalsIgnoreCase("o")){
if (option.equalsIgnoreCase("a")) {
for(int a = 0; a < bodytypes.length ; a++){
System.out.println(a+": "+ bodytypes[a]);
}
option = input.nextLine();
bodyType = start.getBodyType(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else if (option.equalsIgnoreCase("b")) {
for(int a = 0; a < manufacturers.length ; a++){
System.out.println(a+": "+ manufacturers[a]);
}
option = input.nextLine();
manufacturer = getManufacturer(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else{
option = input.nextLine();
System.err.println(("input a right choice"));
pringSelectType();
option = input.nextLine();
}
}
System.out.println("");
System.out.println("it's your choice below: ");
System.out.println("bodyType : "+ bodyType);
System.out.println("manufacturer : "+ manufacturer);
}
private static void pringSelectType() {
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
}
}
i delete some unused method,and change some code.
i don't make any note,cause i think it's easy enough..
if u have some problem,comment it,i will see.
PS:when u want to over the select system,input o.it will be done.