Creating an ArrayList using a Scanner - java

I am working on a project to create a list of students using an Array List. I know how to create a simple array list, however, I decided that I want to use the Scanner method. Unfortunately, THAT is where my troubles begin. Here is what my origin class looks like:
import java.util.Scanner;
/**
* Used to create a single student.
*/
public class Student
{
private String Name;
private int Age;
private String Gender;
private int heightInches; //inches%maxInches
private int heightFeet; //inches/maxInches
private int Inches;
private final int maxInches = 12;
private int Weight;
private String Position;
private Scanner keybd;
/**
* Constructor
*/
public Student(){
keybd = new Scanner(System.in);
setStudent();
}
/**
* Method to create a student
*/
public void setStudent(){
System.out.println("Enter name of student:");
Name = keybd.next();
System.out.println("Enter age of student:");
Age = keybd.nextInt();
System.out.println("Enter gender of student:");
Gender = keybd.next();
System.out.println("Enter height in inches of student:");
Inches = keybd.nextInt();
if(Inches>= maxInches){
heightFeet = Inches/maxInches;
heightInches = Inches%maxInches;
}
else{
heightInches = Inches%maxInches;}
System.out.println("Enter position of user:");
Position = keybd.next();
System.out.println("Enter weight of student:");
Weight = keybd.nextInt();
}
/**
* Returns height of student
*/
public void getHeight(){
System.out.println(heightFeet + "'" + heightInches + "''");
}
/**
* Prints details of student
*/
public void printDetails(){
if((Position.equals("Doctor")) || (Position.equals("Coach"))){
System.out.println(Name + " who is a " + Age + " year old " + Gender + " weighs " + Weight + " and is ");
getHeight();}
else{System.out.println(Name + " who is a " + Age + " year old " + Gender + " is ");
getHeight();
}
}
}
Unfortunately, when I try calling the setStudent method in my new class which will be calling the Students class in order to actually make a list, I run into issues. I really wanted to have an "if" statement along with a Scanner that if the user desires to add another student it would loop, otherwise it would end, however, since I cant even create a new student using the above code, it is not even worth my time to try attempting that yet.

Each Student object is its own instance of the Student class. When you read all that data in the constructor, you work with that particular Student object. You could make a loop in the constructor, creating new Student objects, but that would be fairly confusing -- after all, a constructor's job is to create one object.
(That aside, it's bad style to have the constructor ask the user for input. It makes the class untestable in unit testing, and it ties it to a console, making it unusable in a GUI program. You'd be better off by reading all the student data elsewhere, and then passing it to the Student constructor.)
So, some code outside the Student class, e.g., your main method) should have the list of Students, collect the input, and create the Student objects.

I decided to try keeping it simple (first time in a long while that I took the simple way out)
In my new class I put this:
/**
* Method to add more students
*/
public void addStudent(){
studentList.add (new Student());
}
On the bright side, now I can try using an if-else method to add more students.

Related

Loop through the services array and ask the user which services they want for their <insert model>

Here are my instructions:
In main, ask the user what make of automobile they own. Store this data in a string.
Your first method should take the make via parameter and present the user with the following greeting: Hello! We will be happy to service your automobile today!
Write a second method named carMaintenance. It should take in the make via parameter and return the price to Main.
o Create two local arrays: services and prices.
§ One will hold these strings: Oil Change, Tire Rotation, Air Filter, Check Fluids
§ The second will hold these doubles: 39.99, 49.99, 19.99, 10.99
o Loop through the services array and ask the user which services he wants for his . Make sure you display the price along with the service. Use an accumulator to total the price for all requested services, using the prices array.
o Return the price to Main.
Write a third method name finalPrice that takes in the price from Main.
o First, tack on 30% for labor to the price.
o Then, ask if the car is an import. If the answer is yes, add another 5% to the price.
o Add 7% sales tax.
o Display the total price to the user from this method.
Method 1 is done, however method 2 I need help with the loop and I was wondering if I can get some assistance on it. Since it's only asking me the model and then greeting me.
import java.util.Scanner;
public class autoRepairShop {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner Object
String automobileMake;
Scanner input = new Scanner (System.in);
System.out.print("Input your automobile model/make: ");
String model = input.next();
System.out.println();
System.out.println("Hello! We will be happy to service your " + model + " automobile today!");
}
/** Method 2 **/
static void carMaintenance() {
String[] services = new String[3];
Scanner sc = new Scanner(System.in);
Scanner input = new Scanner (System.in);
double[] prices = new double[3];
String str;
services[0] = "Oil Change";
services[1] = "Tire Rotation";
services[2] = "Air Filter";
services[3] = "Check Fluids";
prices[0] = 39.99;
prices[1] = 49.99;
prices[2] = 19.99;
prices[3] = 10.99;
for (int i = 0; i<4; i++) {
String model = null;
System.out.println("which services do you want for your " + model);
String services1 = input.nextLine();
System.out.println("Your choices are");
for(String services + double prices = 0; );
}
};
}
A. Your arrays should be initialized to size 4 ([4]), as each array has 4 elements. As it is, you are going to get ArrayIndexOutOfBoundsException's on each arr[3] = ...; Also, it would be cleaner and safer to initialize your arrays like String services[] = ['A','B','C','D'];
B. For your loop, you want to move the printlns in the loop outside before the loop
System.out.println("Enter your model");
String model = input.nextLine();
It isn't clear how model fits in with what you are doing and how you are intending to use it, but I've left this in here, as it was in your original code
System.out.println("which services do you want for your " + model);
System.out.println("Your choices are");
for (int i = 0; i<4; i++) {
System.out.println(services[i] + ": " + prices[i]);
}
String services1 = input.nextLine();
Also you should create a constant (final) variable somewhere to indicate how many services and prices you have, and you should reference that variable in your loop iteration

Passing arrays as parameters and make calculations

I have to make a Java Program, where a user type in the total numbers of students, so I made this code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
Now, after adding the total number of students, we should add their names into an array:
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
After that, we should add correspondingly the age of each name, so I made this portion of code:
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
After making this code, I tested it using Ideone and Command Prompt and it works properly:
Now, I need to call method according to selection of the user:
if he typed 'a' a method should be called to specify the name and the age of the oldest student.
If he typed 'b' a method called to see how many students have an age specified by the user and If he typed 'c', a function called to calculate the average age of them all.
I am new to methods so I don't know how to add arrays into methods and make statements.
Here is the full code:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int numReaders = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of magazin readers:");
numReaders = scan.nextInt();
//Creating an array of names, where the length is the total number entered by the user
String[] nameStr = new String[numReaders];
int[] ages = new int[numReaders];
for(int i=0; i<numReaders; i++)
{
Scanner n = new Scanner(System.in);
System.out.println("Enter the name of reader: "+i);
nameStr[i] = n.next();
}
for(int i=0; i<numReaders; i++)
{
Scanner a = new Scanner(System.in);
System.out.println("Enter the age of reader: "+i);
ages[i] = a.nextInt();
}
//Display the results
System.out.println("Number of readers is: "+numReaders);
for (int i=0; i<numReaders; i++)
{
System.out.println("The name of reader "+i+" is "+nameStr[i]+ " and his age is "+ages[i]);
}
//Choosing a statistic
//if a:
System.out.println("Please choose a, b or C:");
Scanner stat = new Scanner(System.in);
char X;
X = stat.next().charAt(0);
if(X=='a')
System.out.println(X+X);
else if(X=='b')
//System.out.println(X);
//Scanner newAge = new Scanner(System.in);
//int ageToSearchFor = newAge.nextInt();
//maxAge(ageToSearchFor);
else
System.out.println(X);
}
}
Right, so to start with your user enters an input, for example 'a', so let's go with this:
Firstly, you need to create the method where the name of the oldest student is displayed, so let's call it 'getOldestStudent' - when naming methods this is the typical naming convention, starting lowercase and then moving to uppercase for each new word - try and make them as intuitive as possible.
When making the method signature, you need to give it its visibility and also what it is going to return. In this case, as you are only using one class, we will give it private, so it is only visible by this class.
Now we need to return 2 things, so we can either put these into a string or put them into an array, which is what I would recommend, so we are going to return an array. However, you want to input an array to search through, so this goes in tbe brackets as parameters (or arguments). Therefore our method signature is the following:
private String[] getOldestStudent(String[] students, int[] ages)
Then inside this method, you can simply do the code you need to find the oldest student, add their name and age to the array and then return this.
Need anymore help just drop a comment.
On a side note, you would have been better off creating a 'Student' object and then giving this object a 'name' property and an 'age' property and then simply making an array of students and getters and setters (or accessors and mutators) for these properties.
James Lloyd's covers your question pretty well, I thought I might add some input as I think you are struggling with some principles.
At first, I would do as James advised and create a class Student that stores the values for each person.
public class Student {
public String name;
public int age;
// Constructors allow you to create a new Object and set some variables
// when you create it.
public Student (String name) {
this.name = name;
}
}
I used public to avoid getters and setters for this explanation, but I'd use private most had I to write it by myself.
Anyways, that way you only have to use one instead of two arrays (and name and age are connected with each other, e.g., you know the age of a student you know the name of, whereas with two different arrays it could happen that you don't know if nameArray[0] belongs to ageArray[0].
So you have an array Student[] students = new Student[numReaders]; and you can set each Student after reading the input, i.e., after reading the name you call students[i] = new Student(name); If you want to set the age of a Student afterwards you can do so by using student[i].age = age.
Now that we have filled our array, we can advance to your actual question.
char method;
method = stat.next().charAt(0);
// I think switch is a little easier to read for such cases
switch(method) {
case 'a': Student oldest = getOldestStudent(students);
if (oldest != null)
System.out.println(oldest.name);
break;
case 'b': //another method
break;
default: // equals to else as if none of the other cases was fulfilled
break;
}
Now you can write your own method for each scenario you have to cover.
public Student getOldestStudent(Student[] students) {
// at first we check some cases that do not require further checks
if (students.length == 0) {
System.out.println("No students have been specified");
return null; // this might lead to a NullPointerException so check the return Object whether it is null before doing anything with it
} else if (students.length == 1)
return students[0];
// no we have to see which students if the oldest in the regular case
// the first student will be used for comparison
Student oldestStudent = students[0];
for (int i = 1; i < students.length; i++) {
// see if our current student is older
if (oldestStudent.age < students[i].age)
oldestStudent = students[i];
}
return oldestStudent;
}
This way you can easily access the Students name afterwards (see above in the switch). You can build all your methods like this by passing the array to the methods and iterating through it. Depending on whether you want to return one or more Students (as it might vary between the different methods) you have to change the return type from Student to Student[].

How to to use if and else statements properly?

I am having trouble using my if and else if statements for my personal project.
My program seems to work fine in the first lines when asking the user for input, but there is a problem in the code. My compiler is asking me to use a switch method.
I've also encountered a problem where the compiler tells me I can't convert String to double, which is something I have already found using the search.
I know this might be a lot to ask but I would really appreciate your help.
/**
* This application executes number of gallons purchased, car wash if the
* customer desires.
* There will be four options, Regular, Premium, Super,
* or None. A car wash is $1.25 if purchased with $10.00 or more. If it is
* anything equal or below $9.99 then the car wash fee is $3.00.
* Regular per gallon is $2.89
* Premium per gallon is $3.09
* Super per gallon is $3.39
*
*
* #author Christian Guerra
*/
package finalflight;
//The line below is preparing the system to ask the user for inputs
import java.util.Scanner;
public class ExxonCarServices {
public static void main(String[] args) {
String gasType;
String carWash;
String gasPrice;
String numGallons;
double gasRegular = 2.89;
double gasPremium = 3.09;
double gasSuper = 3.39;
double gasNone = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Hello which type of gas would you like today? "
+ "Please make the selection Regular, Premium, Super, or None" + " ");
gasType = keyboard.nextLine();
System.out.print("How many gallons would you like?" + " ");
numGallons = keyboard.nextLine();
System.out.print("Would you like to add a professional car wash cleaning today?"
+ " " + "Please select Yes or No" + " ");
carWash = keyboard.nextLine();
if (gasType.equals("Regular")) {
gasRegular = Regular;
} else if (gasType.equals ("Premium")) {
gasPremium = Premium;
} else if (gasType.equals("Super")) {
gasSuper = Super;
} else {
gasNone = 0;
}
if (numGallons * gasPrice <10) {
carWash = 3;
} else {
carWash = 1.25;
}
}
}
The compiler is telling you that this code is correct:
if (gasType.equals("Regular")) {
gasRegular = Regular;
} ...
but starting with Java 7.0 can also be written using a switch statement:
switch (gasType) {
case "Regular":
gasRegular = Regular;
break;
case "Premium":
gasPremium = Premium;
break;
....
}
The error you're getting about "can't convert String to double" is probably due to a missing Double.parseDouble(someString) when assigning a String to a variable of the type Double.
I doubt the compiler is telling you to use a switch-case, it's probably just suggesting it (for more than a few items, a switch-case is almost always the better option for readability's sake).
To convert a String to a Double, simply use Double.parseDouble().
In your case, that would look something like this:
double numGallonsDouble = Double.parseInt(numGallons);

Basic Java work

I am learning Java. I am fairly new to this and just doing some practice exercises,
This is what it says I must do, I have attempted it (please see my coding below) I need some help with some error messages that I keep getting.
Create a class Student to describe a student with the following attributes:
student ID
name
level
with appropriate data types.
This information should be provided, when an object is created. The program should be able to provide each piece of information, when requested. Please also write a method to input a fixed number (for instance 5) of grades (using the Scanner class) and to calculate and print their average.
A main method to run the program should be devised so that the required information is inputted via the keyboard.
import java.util.Scanner;
public class student{
public static void main (String args []){
Scanner grade = new Scanner(System.in);
int studentgrade;
int studentid;
String studentname;
System.out.println("enter student grade") ;
int studentgrade = grade.nextInt();
System.out.println("enter your studentID here");
int studentid = grade.nextInt();
System.out.println("type your student name here");
String studentname = grade.next();
answer = studentgrade + studentid + studentname;
}
}
I have updated the coding after your feedback and now it says,
variable student grade is already defined in method main
I'm so confused i hate this :(
The error message tells you exactly what the problem is:
";"expected
Means that you are missing a semicolon in your code.
answer = studentgrade + studentid + student name
should be
answer = studentgrade + studentid + studentname;
//import java.util.scanner;
import java.util.*;
public class student
{
public static void main (String args [])
{
Scanner grade = new Scanner(System.in);
int studentgrade=0;
int studentid=0;
String studentname="";
System.out.println("enter student grade");
studentgrade = grade.nextInt(); // the error is here apparently ? it highlights this line yellow and says ";" expected
System.out.println("enter your studentID here");
studentid = grade.nextInt();
System.out.println("type your student name here");
studentname = grade.next();
int answer = studentgrade + studentid;
System.out.println("answer = " + answer + "student name = " + studentname);
//+ student name
}
}
problem with this line
int studentgrade.next.int();
it is neither and assignment nor a statement. what are you trying to do with this?
it should be something like this:
int studentgrade = grade.nextInt();
And then
int studentid = next.int;
should be
int studentid = grade.nextInt();
And same problem is with
string studentname = next.string;
it should be
String studentname = grade.next();
Lots of other changes it requires in terms of being a compilable unit such as scanner should be Scanner, string should be String and system should be System. Please read java naming conventions and use standard class names as is at least.

Not sure how to create a menu which uses methods from my other classes [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
so far I have created two classes, which I will show below
I have tested both classes and they both seem to work.
I now need to create a menu which will use the two classes I have created and allow users to enter the information and to find information on their account for the following:
Add the customers details
Make a deposit to the business account
Record a meter reading to the business account
Display current balance of the business account
Display full account details
Change the discount value for the business account
Change the cost per unit for all business accounts
How to use the menu system
While I have tried my best to find out how to do it using resources online I am currently lost. Up to this point every time I have tried to create a menu system I just could not get it to work. I would greatly appreciate if someone could help me with the basics on how to go about doing it.
Thanks :)
public class GasAccount
{
private int intAccRefNo;
private String strName;
private String strAddress;
public double dblBalance;
private double dblUnits;
public static double dblUnitsCosts = 0.02;
public GasAccount (int intNewAccRefNo , String strNewName , String strNewAddress)
{
}
public GasAccount (int intNewAccRefNo , String strNewName , String strNewAddress , double dblNewUnits)
{
intAccRefNo = intNewAccRefNo;
strName = strNewName;
strAddress = strNewAddress;
dblUnits = dblNewUnits;
dblBalance = dblUnits * dblUnitsCosts;
}
public int getAccRefNo()
{
return intAccRefNo;
}
public String getName()
{
return strName;
}
public String getAddress()
{
return strAddress;
}
public void deposit(double dblDepositAmount)
{
dblBalance = dblBalance - dblDepositAmount;
}
public double getBalance()
{
return dblBalance;
}
public double getUnitCost()
{
return dblUnitsCosts;
}
public void recordUnits (double dblUnitsUsed)
{
dblBalance = dblBalance + dblUnitsUsed * dblUnitsCosts;
dblUnits = dblUnitsUsed + dblUnits;
}
public double getUnits()
{
return dblUnits;
}
public void updateUnitsCosts(double dblNewUnitsCosts)
{
this.dblUnitsCosts = dblNewUnitsCosts;
}
}
And another which extends it -
public class BusinessAccount extends GasAccount
{
private double dblDiscount;
public BusinessAccount (int intNewAccRefNo, String strNewName, String strNewAddress, double dblNewUnits, double dblNewDiscount)
{
super (intNewAccRefNo , strNewName , strNewAddress, dblNewUnits);
dblDiscount = dblNewDiscount;
}
public void setNewDiscount(double dblNewDiscount)
{
dblDiscount = dblNewDiscount;
}
public double getDiscount()
{
return dblDiscount;
}
#Override
public void recordUnits (double dblUnitsUsed)
{
double dblNewBalance;
dblBalance = dblBalance + dblUnitsUsed * dblUnitsCosts;
dblNewBalance = dblUnitsUsed * dblUnitsCosts * dblDiscount / 100;
dblBalance = dblBalance - dblNewBalance;
}
Here is what my attempted menu looks like up to the fifth option. I am doing something horribly wrong with calling in the methods from the other classes as BuisnessAccount.getMethod always shows up as an error. I am also pretty sure declaring the variables again is completely wrong as then they have no link to my other classes.
If someone could help me solve this it would be greatly appreciated
import java.util.Scanner;
public class Menu
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int Choice;
{
System.out.println("------------------------------");
System.out.println ( "1. Add the customers details" ) ;
System.out.println ( "2. Make a deposit to the business account" );
System.out.println ( "3. Record a meter reading to the business account" ) ;
System.out.println ( "4. Display current balance of the business account" ) ;
System.out.println ( "5. Display full account details" ) ;
System.out.println ( "6. Change the discount value for the business account" ) ;
System.out.println ( "7. Change the cost per unit for all business accounts ");
System.out.println ( "8. How to use the menu system ");
System.out.println ( "Any other number will exit the program");
System.out.println("------------------------------");
System.out.println ( "\n\nEnter a number from 1 to 8" );
Choice = input.nextInt();
switch (Choice)
{
case 1 :
int intNewAccRefNo;
String strNewName;
String strNewAddress;
Double dblNewUnits;
Double dblNewDiscount;
System.out.println("Please enter the account number?");
intNewAccRefNo = input.nextInt();
System.out.println("Please enter the account name?");
input.nextLine();
strNewName = input.nextLine();
System.out.println("Please enter the account address?");
strNewAddress = input.nextLine();
System.out.println("Please enter the number of initial number of units used?");
dblNewUnits = input.nextDouble();
System.out.println("Please enter the discount?");
dblNewDiscount = input.nextDouble();
case 2:
double dblDeposit;
System.out.println("Please enter the amount you want to deposit?");
dblDeposit = input.nextDouble();
System.out.println ( "The current balance: " + BusinessAccount.getBalance() ) ;
case 3:
double dblUnits;
System.out.println("Enter the number of Units Used");
dblUnits = input.nextDouble();
BusinessAccount.recordUnits(dblUnits);
case 4:
System.out.println("\n Current Balance: £"+ BusinessAccount.getBalance());
case 5:
System.out.println("Account Reference Number: " + BusinessAccount.getAccRefNo());
System.out.println("Address: " + BusinessAccount.getAddress());
System.out.println("Name: " + BusinessAccount.getName());
System.out.println("Balance: " + BusinessAccount.getBalance());
System.out.println("Discount: " + BusinessAccount.getDiscount());
System.out.println("Units: " + BusinessAccount.getUnits());
case 1 :
String strAddress;
System.out.println("Please enter the account address?");
strAddress = input.nextLine();
System.out.println("Address:" + firstAccount.getAddress());
There is no connection between what the user inputs and the method which i am calling, not sure how to fix.
By using BusinessAccount.someMethod(), you're attempting to call said method in a static context, but your methods are not static. To call upon your methods, you either need to make them static or need to create an object which can then call upon them, ie:
BusinessAccount ba= new BusinessAccount (4, "name", "address", 3.4, 43.4);
ba.someMethodFromClass();
In your case, you do NOT want them to be static. Read up more on static methods/variables (see below).
Some documentation that may be helpful:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
To answer your second question, you need to have a method (in your object's class, not main) which can assign values to your variables. ie:
public void setAddress (String address)
{
strAddress=address;
}
Then, you'd pass the address that you read in from main into your function. By doing that, you're initializing/assigning the value from the user to the value stored in your class, ie:
System.out.println("Please enter the account address?");
String temp = input.nextLine();
ba.setAddress(temp);
System.out.println("Address:" + ba.getAddress());
or better yet,
System.out.println("Please enter the account address?");
ba.setAddress(input.nextLine());
System.out.println("Address:" + ba.getAddress());
Going off of what SteveP said, it would be a good idea to store the instances of the other classes as instance variables in the Menu class.
Also, if you're using a GUI interface, this JMenu class API may come in handy:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
Also look for JMenuBar, JMenuItem

Categories