public class studentDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many students are there?: ");
int numberOfstuds = scan.nextInt();
int[] nOEarray = new int[numberOfstuds];
System.out.println("\nEnter names of students up to the entered amount (" + numberOfstuds + "):");
String[] namesArray = new String[numberOfstuds];
for (int i = 0; i < numberOfstuds; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
That is part of my code for letting user input array size, however I am tasked with using the header below just for a method to get the size of the array, but I have tried inserting it and keep getting different error messages such as needs body(if I put semi-colon) or "requires ';'" if I don't and when I put curly braces around the section where it gets the array size it returns errors :Syntax error, insert "[ ]" to complete Dimension
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on token "create", AnnotationName expected after
this token
public static Student[] create()
Here is the Student class
public class Student {
//private data members
private String name;
private long idNUmber;
//constructor
public Student(){
name="Unassigned";
idNUmber=0;
}
//overloaded constructor
public Student(String x, long y) {
name=x;
idNUmber=y;
}
//getters
public String getName() {
return name;
}
public long getIdNUmber() {
return idNUmber;
}
//setters
public void setName(String n) {
name=n;
}
public void setIdNUmber(long i) {
idNUmber=i;
}
//override
public String toString() {
return "Name: "+getName()+"\nID number: "+getIdNUmber();
}
Related
So I need help with this part of JAVA in my COP class OOP programming.
First is that I need to change the addStudent to static method but the code will not run because the this.student is not static which makes no sense because it already private static
import java.util.Arrays;
public class InitializerDemo {
public static final int MAX_STUDENTS = 10;
private static Student[] students;
private Instructor instructor;
private static int numStudents = 0;
// default constructor
public InitializerDemo() {
}
// instructor mutator
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
// add a student, increment the count
//This PART!!! HELP
public static void addStudent(Student s) {
this.students[numStudents++] = s;
}
public static void main(String[] args) {
// create our aggregator object
InitializerDemo id = new InitializerDemo();
// set the instructor
id.setInstructor(new Instructor("Sally"));
// add the students
id.addStudent(new Student("Sam"));
id.addStudent(new Student("Rajiv"));
id.addStudent(new Student("Jennifer"));
id.addStudent(new Student("Test Student"));
// output
System.out.println(id);
}
public String toString() {
String s = "Instructor = " + instructor + "\n" +
"Number of students = " + numStudents + "\n" +
"Students: " + Arrays.toString(students) + "\n";
return s;
}
}
class Student {
private String name;
// instance initializer block
{
name = "noname";
}
public Student() {
}
public Student(String name) {
this.name = name;
}
public String toString() { return name; }
}
class Instructor {
private String name;
// instance initializer block
{
name = "noname";
}
public Instructor() {
}
public Instructor(String name) {
this.name = name;
}
public String toString() { return name; }
}
I need help with that addStudent Method
These are the instructions and sorry to confuse all you guys and thank you for putting time to help me
change the instance variables representing the number of students and the Student array in the aggregator object to private static variables.
• change the addStudent method in the aggregator object from an instance method to a static method
• Remove all initialization/instantiation operations from the aggregator object’s default constructor; the constructor can simple be an empty method { }
• provide a static initializer block in the aggregator object which does the following:
o initializes the number of students to 0
o instantiates the student array
o adds a single student named “Test Student” to the array using the addStudent method
Change
this.students[numStudents++] = s;
to
students[numStudents++] = s;.
I believe that should work.
You also have to initialize the students, so change
private static Student[] students;
to
private static Student[] students = new Student[MAX_STUDENTS];
I am extremely stuck on this assignment I have, this is the last part of the assignment and it is going over my head. We were given this code to start off with.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
Employee e1 = new Employee2(7, "George Costanza");
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e1.displayEmployee();
//Employee e2 = createEmployeeFromFile();
//e2.displayEmployee();
}
}
We were told to create a method called createEmployeeFromFile();. In this method we are to read from a .txt file with a Scanner and use the data to create an Employee object. Now I am confused on two things. First on the method type I should be using, and how to create an object with the data from the .txt file. This is the first time we have done this and it is difficult for me. Employee1 works fine, but when trying to create my method I get stuck on what to create it as.
Here is my rough draft code for right now.
import java.util.*;
import java.io.*;
public class TestEmployee2
{
public static void main(String[] args) throws IOException
{
EckEmployee2 e1 = new EckEmployee2(7, "George Costanza");
EckEmployee2 e2 = createEmployeeFromFile();
e1.setDepartment("Front Office");
e1.setPosition("Assistant to the Traveling Secretary");
e1.setSalary(50000.0);
e1.setRank(2);
e2.setNumber();
e2.setName();
e2.setDepartment();
e2.setPosition();
e2.setSalary();
e2.setRank();
e1.displayEmployee();
e2.displayEmployee();
}
createEmployeeFromFile(){
File myFile = new File("employee1.txt");
Scanner kb = new Scanner(myFile);
}
}
I am not expecting to get the answer just someone to point me in the right direction. Any help is greatly appreciated.
Here is my code from my main class.
public class EckEmployee2 {
private int rank;
private double number;
private double salary;
private String name;
private String department;
private String position;
public EckEmployee2() {
number = 0;
name = null;
department = null;
position = null;
salary = 0;
rank = 0;
}
public EckEmployee2(double number, String name) {
this.number = number;
this.name = name;
}
public EckEmployee2(double number, String name, String department, String position, double salary, int rank) {
this.number = number;
this.name = name;
this.department = department;
this.position = position;
this.salary = salary;
this.rank = rank;
}
public void setNumber(double num) {
this.number = num;
}
public double getNumber() {
return this.number;
}
public void setName(String nam) {
this.name = nam;
}
public String getName() {
return this.name;
}
public void setDepartment(String dept) {
this.department = dept;
}
public String getDepartment() {
return this.department;
}
public void setPosition(String pos) {
this.position = pos;
}
public String getPosition() {
return this.position;
}
public void setSalary(double sal) {
this.salary = sal;
}
public double getSalary() {
return this.salary;
}
public void setRank(int ran) {
this.rank = ran;
}
public int getRank() {
return this.rank;
}
public boolean checkBonus() {
boolean bonus = false;
if (rank < 5) {
bonus = false;
} else if (rank >= 5)
bonus = true;
return bonus;
}
public void displayEmployee() {
if (checkBonus() == true) {
System.out.println("-------------------------- ");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: \n" + department);
System.out.println("Position: \n" + position);
System.out.printf("Salary: %,.2\n" , salary);
System.out.println("Rank: \n" + rank);
System.out.printf("Bonus: $\n", 1000);
System.out.println("-------------------------- ");
} else if (checkBonus() == false)
System.out.println("--------------------------");
System.out.println("Name: " + name);
System.out.printf("Employee Number: %09.0f\n" , number, "\n");
System.out.println("Department: " + department);
System.out.println("Position: " + position);
System.out.printf("Salary: %,.2f\n" , salary);
System.out.println("Rank: " + rank);
System.out.println("-------------------------- ");
}
}
To make things more clear here are the directions
Create a method in TestEmployee2 called createEmployeeFromFile() that will read data from a file and create, populate and return an Employee object. The file it will read from is called employee1.txt, which is provided. Hard code the name of the file in the method. This file contains the employee’s number, name, department, position, salary and rank. Create a Scanner object and use the Scanner class’s methods to read the data in the file and use this data to create the Employee object. Finally return the employee object.
In java, to return a value from a method, you add that objects type into the method signature as below, and in short java method signatures are as follows
'modifier (public, private, protected)' 'return type (void/nothing, int, long, Object, etc...' 'methodName(name the method)' 'parameters (any object or primitive as a parameter'
The method below will work if you have an employee contstructor which parses the input text, and assuming the data is split my a delimiter, you can use String.split(splitString); where splitString is the character that splits the data, i.e) a comma ",".
public EckEmployee2 getEmployee()
{
try
{
/**
* This will print where your java working directory is, when you run the file
*
*/
System.out.println(System.getProperty("user.dir"));
/**
* Gets the file
*/
File myFile = new File("employee1.txt");
/**
* Makes the scanner
*/
Scanner kb = new Scanner(myFile);
/**
* A list to store the data of the file into
*/
List<String> lines = new ArrayList<>();
/**
* Adds all the lines in the file to the list "lines"
*/
while (kb.hasNext())
{
lines.add(kb.next());
}
/**
* Now that you have the data from the file, assuming its one line here, you can parse the data to make
* your "Employee"
*/
if (lines.size() > 0)
{
final String line = lines.get(0);
return new EckEmployee2(line);
}
}
/**
* This is thrown if the file you are looking for is not found, it either doesn't exist or you are searching
* in the wrong directory.
*/
catch (FileNotFoundException e)
{
e.printStackTrace();
}
/**
* Return null if an exception is thrown or the file is empty
*/
return null;
}
First your method createEmployeeFromFile() must take 2 parameters, a Scanner object to read input, and the File you're gonna be reading from using the Scanner.
The return type is Empolyee2 because the method creates a Employee2 instance and must return it.
Now, I gave you the initiatives.
Your turn to read more about Scanner object and File object.
Reading from the text file, the attributes of your object, is easy then you create an instance by using the constructor with the attributes and return it!
Hope this helps.
this is the first class
this is the template class
public class Email{
private String title;
private String to;
private double size;
private boolean sent;
static int numEmails;
public Email(String Title, String To, double Size){
title = Title;
to = To;
size = Size;
numEmails++;
}
public void displayEmail(){
System.out.printf("Subject: %30s%n", title);
System.out.printf("To: %-35s%n",to);
System.out.printf("This email has size: %.2f kB%n",size );
if(sent)
System.out.printf("This email has been sent%n");
else
System.out.printf("This email has not been sent%n");
}
public void sendEmail(){
sent = true;
displayEmail();
}
public boolean isValid(){
int sep = to.indexOf('#');
if(to.substring(sep).equals("#student.ksu.edu.sa"))
return true;
return false;
}
//setters
public void setTitle(String Title){
title = Title;
}
public void setTo(String To){
to = To;
}
public void setSize(double Size){
size = Size;
}
public void setSent(boolean Sent){
sent = Sent;
}
//getters
public String getTitle(){
return title;
}
public String getTo(){
return to;
}
public double getSize(){
return size;
}
public boolean getSent(){
return sent;
}
}//End of class
this is the second class
when I run this it says error StringIndexOutOfBounds
I guess it has to do with the method isValid()
I want to fill the first and second objects in the array by reading from user but there's an error as well which I can't seem to know why when I read from the user
import java.util.*;
public class Inbox{
static Scanner read = new Scanner (System.in);
static Email[] sentEmails = new Email[Email.numEmails];
//archive method
public static Email[] archive(Email[] emailList){
for(int i=0;i<Email.numEmails;i++)
if(emailList[i].getSent())
sentEmails[i] = new Email(emailList[i].getTitle(),emailList[i].getTo(),emailList[i].getSize());
return sentEmails;
}
//findByRecipient method
public static void findByRecipient(Email emailList[], String toAddress){
System.out.println("The emails addressed to \"everyONE#student.ksu.edu.sa\" are:");
System.out.println("==========================");
toAddress = toAddress.toLowerCase();
for(int i=0;i<Email.numEmails;i++)
if(emailList[i].getTo().equals(toAddress))
emailList[i].displayEmail();
}
//main
public static void main(String[] args){
Email[] array = new Email[10];
for(int i=0;i<2;i++){
System.out.printf("Please enter the title, recipient, and size of email %d %n", (Email.numEmails+1));
array[i] = new Email(read.nextLine(),read.nextLine(),read.nextDouble());
;}
array[2] = new Email("Urgent: Lab final","everyone#student.ksu.edu.sa",200);
array[3] = new Email("Fwd: Boarding pass","SaadAli#ksu.edu.sa",100);
array[4] = new Email("You won 1M SR!","email#spam.com",5000.0);
//1
System.out.println("The Inbox currently contains");
System.out.println("==========================");
for(int j=0;j<Email.numEmails;j++){
if(array[j]!=null)
array[j].displayEmail();}
for(int k=0;k<Email.numEmails;k++){
if(array[k].isValid())
array[k].sendEmail();
else
System.out.println("Email is invalid");
}
//2
archive(array);
System.out.println("The Inbox after sending contains:");
System.out.println("==========================");
for(int s=0;s<sentEmails.length;s++){
if(sentEmails[s]!=null)
sentEmails[s].displayEmail();}
//3
findByRecipient(array,"everyONE#student.ksu.edu.sa");
//4
System.out.println("The titles of emails in archive are:");
System.out.println("==========================");
for(int r=0;r<Email.numEmails;r++)
System.out.println(array[r].getTitle());
//5
System.out.println("Number of emails: " + Email.numEmails);
}//End of main
}//End of class
Without seeing the inputs, it's hard to be certain, but your isValid() function doesn't check if the '#' sign exists. If this function is called and the var to doesn't have an '#' sign, var sep will be set to -1, causing an error with the line "to.substring(-1)".
Hi I'm currently doing this program for my assignment to create like a virtual shop. Currently I'm using NetBean IDE 8.1 and got an error when I tried to test the program. It's said , even though the program said build successful when I tried to build the program.
I did tried to follow the instruction in this video but came out empty image here
Here is my main program ( I haven't complete the program yet but this error keeps blocking me for testing it)
import java.util.Scanner;
public class Zarashop {
int choice;
public static void main(String[] args, int clothA){
Scanner absorb = new Scanner(System.in);
// phase 1 login
cloth cl = new cloth(); // declaring objects
payment pay = new payment();
personalinfo pi = new personalinfo();
shipping ship = new shipping();
receipt re = new receipt();
System.out.println("Welcome to Zara's cloth Shopping Center");
System.out.println("\nThis an online Shopping application will help you to buy "+ "a new cloth");
System.out.println("Please enter your detail");
System.out.println("\nPlease enter your name");
String Name = absorb.nextLine(); // user input name
System.out.println("\nAre you a student? (yes) or (no)");
String personalchoice = absorb.nextLine(); // user input status
//phase 2
System.out.println("please choose your cloth" );
System.out.println("cloth A detail : size: 170cm and red color ");
int cloathA = absorb.nextInt();
System.out.println("enter quantity ");
int quantity = absorb.nextInt();
pay.setclothA(clothA); // store value
pay.setquantity(quantity);
// phase 3 payment
System.out.println("please press 1 to calculate your payment");
int choice = absorb.nextInt();
if(choice == 1){
pay.total();
}
else {
System.err.println("error!");
}
}
}
Here is my main class for cloth ( misspelled was intended)
public class cloth {
// superclass
private int quantity; //
private int clothA=200;
//void
void setclothA(int ca){
clothA = ca;
}
void setquantity(int q){
quantity=q;
}
//get
int getclothA(){
return clothA;
}
int getquantity(){
return quantity;
}
}
my main class for personalInfo
public class personalinfo {
// superclass
public String Name;
private int Password;
private String TypeCard;
private int CardNo;
private String Address;
private int TeleNo;
//void
void setName(String n){
Name = n;
}
void setPassword(int p){
Password = p;
}
void setTypeCard(String tp){
TypeCard = tp;
}
void setCardNo ( int cn){
CardNo=cn;
}
void setAddress ( int a){
CardNo=a;
}
void setTeleNo ( int tl){
TeleNo=tl;
}
//get
String getName(){
return Name;
}
String getAddress(){
return Address;
}
int getPassword(){
return Password;
}
String getTypeCard(){
return TypeCard;
}
int getCardNo(){
return CardNo;
}
int getTeleNo (){
return TeleNo;
}
}
my sub class for payment
package zarashop;
//subclass
public class payment extends cloth {
String Status = "Initial";
public void total(){
int ca = super.getclothA(); //fetching values
int q = super. getquantity();
int total= q*ca;
}
}
public class receipt extends shipping{
}
my sub for shipping
public class shipping extends payment {
public int typeofshipping;
//void
void settypeofshipping(String ts){
String typeofshipping = ts;
}
int gettypeofshipping(){
return typeofshipping;
}
}
subclass for receipt (i'm reserving this for the program to display all the necessary user input)
public class receipt extends shipping{
}
thank you everyone and sorry for my bad program and my English.
A Java application can accept any number of arguments from the command line, and all of those are interpreted as String, that's why main only takes an array of String as parameter.
Change you code to
public static void main(String[] args)
and you'll be able to launch your application.
If you need to support a numeric command-line argument, you must convert a String argument that represents a number to an int:
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
parseInt throws a NumberFormatException if the format of args[0] isn't valid.
The example comes from official documentation.
Here is your mistake: public static void main(String[] args**, int clothA**)
Change it to public static void main(String[] args)
You will need to change your main method to public static void main(String[] args). By adding int clothA as a second argument, you are chaging the signature, and then it becomes an invalid main method to launch your application from.
If you want to retrieve something from console, you will find your argument inside args.
You can then retrieve clothA as follows:
int clothA;
if (args.length > 0) {
try {
clothA = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 7 years ago.
I have a class called Student with data members:
private String name;
private long idNumber;
With correct getter and setter methods.
I need to create a tester class called StudentTest which includes the following methods:
public static Student[] createArray()
public static void populateArray(Student[] array)
public static void displayArray(Student[] array)
I am getting a "cannot find symbol" error when I try to compile my tester class.
Here is my tester class:
// Scanner class from the Java API
import java.util.Scanner;
public class StudentTester {
public static void main(String[] args) {
// Call methods
Student[] studentList = createArray();
populateArray(studentList);
displayArray(studentList);
} // end main
// Create Array Method
public static Student[] createArray() {
// Declaration & Creation of Scanner object
Scanner input = new Scanner(System.in);
// Create Array
System.out.println("Enter size of array: ");
int i = input.nextInt();
Student[] studentList = new Student[i];
return studentList;
}
// Populate Array Method
public static void populateArray(Student[] array) {
for(int i = 1; i < studentList.length; i++) {
studentList[i] = new Student();
Scanner userInput = new Scanner(System.in);
// Get Input for Name
System.out.println("Enter Student Name: ");
studentList[i].setName = userInput.nextLine();
// Get Input for Id Number
System.out.println("Enter Student ID Number: ");
studentList[i].setIdNumber = userInput.nextInt();
}
}
// Display Array Method
public static void displayArray(Student[] array) {
System.out.println("Array Contents");
for(int j = 0; j < studentList.length; j++) {
System.out.println(studentList[j].getName() + " " + studentList[j].getIdNumber());
}
}
} // end class
Please can anyone help me out, I am quite new to java.
My Student class
public class Student {
// Data Members
private String name;
private int idNumber;
// Constructor
public Student() {
name = "Unassigned";
idNumber = 0;
}
// Getters
public String getName(){
return name;
}
public int getIdNumber(){
return idNumber;
}
// Setters
public void setName(String name){
this.name = name;
}
public void setIdNumber(int idNumber){
this.idNumber = idNumber;
}
} // end class
The symbol that can't be found is to do with the array itself studentList
populateArray (and displayArray) are trying to use studentList, but you named it array in the arguments. Rename it, like
public static void populateArray(Student[] studentList) { // <-- not array.
public static void displayArray(Student[] studentList) { // <-- and here.
or use array instead of studentList in your methods.