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.
Related
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[].
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.
I'm having a Java issue on a uni assignment. We've been given a file that has a set of information listed as such (there's more, this is just a formatting example):
57363 Joy Ryder D D C P H H C D
72992 Laura Norder H H H D D H H H
71258 Eileen Over C F C D C C C P
For the life of me, I can't work out how to store this in an array, AND I need it split because the letters need to be converted to a number and averaged, which will then need to be stored into a second array.
I'm new-ish to Java, so a lot of the types of things that require an import at the start of the code are unknown to me, so explaining the code changes in any replies would be greatly appreciated. The code I have so far is as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class StudentGPA_16997761 {
public static void main(String[] args) throws FileNotFoundException {
Scanner kb = new Scanner(System.in);
//get file
System.out.print("Please enter the name of the file containing student information: ");
String gradeFile = kb.next();
Scanner grades = new Scanner(new File(gradeFile));
if (new File(gradeFile).exists()) {
while (grades.hasNextLine()) {
System.out.println(grades.nextLine());
}
}
//student identification number, a first name, a surname, then 8 individual alphabetic characters that represent the
//unit grades for the student. Hence, each line of data in the text file represents a student and the grades
//they achieved in 8 units of study
//need to make array to hold student information
//need to make array that holds student id and GPA
}
}
I know that it works, as the System.out.println prints out the lines as I expected them to be read, but I can't figure out how to store them. I think I miiight be able to get the split working, but that'll still need the array/arraylist first...
You can split a string into an array using a delimiter. In your example, if all first and last names do not contain spaces themselves, you can do the following:
while (grades.hasNextLine()) {
String line = grades.nextLine();
String[] parts = line.split(" ");
// get the basics
String id = parts[0];
String firstname = parts[1];
String lastname = parts[2];
// extract the grades
int size = parts.length - 3;
String[] gradelist = new String[size];
System.arraycopy(parts, 3, gradelist, 0, size);
// do something with the grades
}
Java is especially good at OOP - Object Oriented Programming. Each line of your input file is a student, which is a perfect example of an object you can define. Let's define a Student class that holds the desired information:
public class Student{
public final int ID;
public final String name;
private LinkedList<Character> grades;
private double grade;
public Student(int i; String n, String[] g){
ID = i;
name = n;
grades = new LinkedList<Character>();
for(String s : g){
grades.add(s.charAt(0));
}
//Do parsing to turn a list of letters into a grade here...
}
public double getGrade(){
return grade;
}
}
Then you can construct students to store the information as you read it. Put this where your current while loop is in your given code.
LinkedList<Student> students = new LinkedList<Student>();
while (grades.hasNextLine()) {
String[] line = grades.nextLine().split("\\s");
Student s = new Student(Integer.parseInt(line[0]),
line[1] + " " + line[2],
Arrays.copyOfRange(line, 3, line.length));
students.add(s);
}
Then do work on students as necessary.
An exercise in the introduction to java programming book I am currently working through requires me to retrieve input from the command line using the scanner class. Each example in the book (and the code I have seen here) creates and uses a scanner object in the same method it is needed in, such as:
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter your first name: ");
String firstName = inputDevice.nextLine();
System.out.println("Enter your middle name: ");
String middleName = inputDevice.nextLine();
System.out.println("Enter your last name: ");
String lastName = inputDevice.nextLine();
inputDevice.close();
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
}
I was wondering why this method is preferred over something like the following (especially since the execise requires me to retrieve input for nine strings)
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
String firstName = prompt("Enter your first name: ");
String middleName = prompt("Enter your middle name: ");
String lastName = prompt("Enter your last name: ");
System.out.println("Your name is " + firstName + " " + middleName + " " + lastName);
}
private static String prompt(String message) {
Scanner inputDevice = new Scanner(System.in);
System.out.println(message);
return inputDevice.nextLine();
}
}
Please keep in mind I am new to both Java and programming in general.
There's nothing wrong with doing it that way, and it very well may save you a few lines in the long run, but it's not common because you can create a Scanner once and reuse it, as you've done above.
It's all style-based, but using one Scanner multiple times is fairly straightforward and avoids unnecessary complexity in your code, which is important (especially in larger-scale projects).
When you're going through the code line-by-line, your first example is much more readable to me, but that's just my opinion, as this is a fairly subjective question. The only real downside is that you're creating a new Scanner every time you call the prompt() method, which is unnecessary.
Also note that you forgot to close the Scanner in the method.
In your case you are creating the Scanner object for every call of the prompt method which is not great practice.
Also you are not closing the Scanner.
IMHO the book's code is reads easier...
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