This is the code that is meant to call a class called Couple and yet
it doesn't recognize the class why is this?
public class AgencyInterFace {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Couple c = new Couple();
int choice, position;
showSelection();
choice = console.nextInt();
while (choice != 9) {
switch (choice) {
case 1:
addCouple();
break;
case 2:
position = console.nextInt();
testCouple(position);
break;
case 3:
position = console.nextInt();
displayCouple(position);
break;
case 9:
break;
default:
System.out.println("Invalid Selection");
} //end switch
showSelection();
choice = console.nextInt();
}
}
public static void showSelection() {
System.out.println("Select and enter");
System.out.println("1 - add a new couple");
System.out.println("2 - test a couple");
System.out.println("3 - display couple");
System.out.println("9 - exit");
}
public static void addCouple() {
Scanner console = new Scanner(System.in);
String herName, hisName;
int herAge, hisAge, ageDiff;
System.out.print("her name: ");
herName = console.nextLine();
System.out.print("her age: ");
herAge = console.nextInt();
System.out.print("his name: ");
hisName = console.nextLine();
System.out.print("his age: ");
hisAge = console.nextInt();
ageDiff = herAge - hisAge;
c.addData(herName, herAge, ageDiff, hisName, hisAge, ageDiff);
}
public static void testCouple(int position) {
System.out.println(c.test(position));
}
public static void displayCouple(int position) {
System.out.println(c.display(position));
}
public static void averageAge(int position) {
System.out.println(c.avgAge());
}
public static void maxDifference(int position) {
System.out.println(c.maxDif(position));
}
public static void averageDifference(int position) {
System.out.println(c.avgDif(position));
}
}//end of class
This code is the class that is meant to be called and that is not
being recognized and is unable to be called.
public class Couple {
final private int MAX = 5;
private Person[] p1, p2;
private int total;
public Couple() {
p1 = new Person[MAX];
p2 = new Person[MAX];
total = 0;
}
private void setData1(Person p, String name, int age, int ageDiff) {
p.setName(name);
p.setAge(age);
}
public String test(int pos) {
if (pos != -1) {
if (p1[pos].getAge() < p2[pos].getAge()) return ("GOOD FOR
"+p2[pos].getName()+" !");
else return ("GOOD
FOR "+p1[pos].getName()+" !");
}
return "error";
}
public void addData(String name1, int age1, int ageDiff1, String
name2, int age2, int ageDiff2) {
p1[total] = new Person();
p2[total] = new Person();
setData1(p1[total], name1, age1, ageDiff1);
setData1(p2[total], name2, age2, ageDiff2);
total++;
}
public String display(int position) {
if (position != -1)
return ("p1: " + p1[position].getName() + "
"+p1[position].getAge()+" / n "+" p2:
"+p2[position].getName()+"
"+p2[position].getAge());
else
return ("error");
}
public String avgAge(int position) {
double avg = 0;
double sum = 0.0;
for (int i = 0; i < position; i++) {
sum += p1[total].getAge();
sum += p2[total].getAge();
}
avg = sum / position;
return ("The average age is: " + avg);
}
public void ageDifference(int position) {
double ageDif = 0.0;
double ageSum = 0.0;
for (int i = 0; i < position; i++) {
if (p1[total].getAge() < p2[total].getAge()) {
ageSum = p2[total].getAge() - p1[total].getAge();
} else {
ageSum = p1[total].getAge() - p2[total].getAge();
}
ageSum = ageDif;
}
}
}
Is this have something to do with the name of the 'Couple' file or how
I call the class. I am getting an 'Undeclared Variable' error.
You defined c inside your main() method. Therefore it is not visible in your other methods. Either pass c as a parameter to your other methods or make it a (static) property of the AgencyInterFace class instead of a local variable of main().
USING STATIC METHODS
If you want to call a method of the class, e.g. test(int position), without creating a variable c, you need to make this method static:
public static String test(int pos) {
if (pos!=-1) {
if (p1[pos].getAge()<p2[pos].getAge()) return("GOOD FOR "+p2[pos].getName()+"!");
else return("GOOD FOR"+p1[pos].getName()+"!");
}
return "error";
}
In this case, your arrays p1[] and p2[] would also need to be static --> they would only be created one time.
And example for making your arrays static:
private static Person[] p1 = new Person[MAX],
p2 = new Person[MAX];
Now you can call this method of the class using Couple.test(position) and it will return a String.
USING NON-STATIC METHODS
If you want to create multiple references of the class Couple, in that p1[] and p2[] should contain different values, you need to create a reference of the class Couple.
You can implement this by telling the program, what c is:
Couple c = new Couple();
Edit:
I see that you have created a couple, but not at the right place. If you create your couple inside of the main() method, you cannot use it anywhere except in this method. You should declare it in your class:
public class AgencyInterFace {
private static Couple c = new Couple(); //<-- here
// main-method
// other methods
}
Related
I want to sort students by their roll numbers. I know how to sort an arraylist of integers using merge sort, but sorting an ArrayList of type Student is different.
my Student class contains the following properties:
public static class Student
{
String name;
int rollNum, WebMark, dsMark, dmMark;
public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
{
this.name = name;
this.rollNum = rollNum;
this.WebMark = WebMark;
this.dsMark = dsMark;
this.dmMark = dmMark;
}
}
I've seen people use Comparators to sort ArrayLists of object's properties. However, they use it for built-in sorting like the following line (which is straightforward):
Collections.sort(Database.arrayList, new CustomComparator());
However, I want to use my mergesort functions that I wrote in my Student class. But I still don't understand how am I going to pass the property 'rollNum' into the mergesort function and how are other properties in the ArrayList are going to be moved accordingly? I've never seen this anywhere in Google.
Here is my full code:
package student;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Comparator;
public class Main
{
public static class Student
{
String name;
int rollNum, WebMark, dsMark, dmMark;
public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
{
this.name = name;
this.rollNum = rollNum;
this.WebMark = WebMark;
this.dsMark = dsMark;
this.dmMark = dmMark;
}
public String getName()
{
return name;
}
public int getRollNum()
{
return rollNum;
}
public int getWebMark()
{
return WebMark;
}
public int getDSMark()
{
return dsMark;
}
public int getDMMark()
{
return dmMark;
}
public static void addStudent(ArrayList<Student> studentArray)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Name: ");
String name = input.next();
System.out.println("Enter Roll Number");
int rollNum = input.nextInt();
System.out.println("Enter Web Mark:");
int webMark = input.nextInt();
System.out.println("Enter Data Structure Mark:");
int DSMark = input.nextInt();
System.out.println("Enter Discrete Math Mark:");
int DMMark = input.nextInt();
//create this student profile in array
Student newStudent = new Student(name,rollNum,webMark,DSMark,DMMark);
studentArray.add(newStudent);
}
public static void findStudent(int rollNum, ArrayList<Student> studentArr)
{
for(int i = 0; i < studentArr.size(); i++)
{
if(studentArr.get(i).getRollNum()==rollNum)
{
System.out.println("Roll Number: " + studentArr.get(i).getRollNum() +
", Name: " + studentArr.get(i).getName() +
", Web Grade: " + studentArr.get(i).getWebMark() +
", Data Structure Grade: " + studentArr.get(i).getDSMark() +
", Discrete Math Grade: " + studentArr.get(i).getDMMark());
}
else
{
System.out.println("Couldn't find student.");
}
}
}
public static void deleteStudent(ArrayList<Student> studentArr)
{
System.out.println("Enter Student Roll Number: ");
Scanner input = new Scanner(System.in);
int rollNum = input.nextInt();
for(int counter = 0; counter < studentArr.size(); counter++)
{
if(studentArr.get(counter).getRollNum() == rollNum)
{
studentArr.remove(counter);
}
}
}
public String toString()
{
return name + " " + rollNum + " " + WebMark + " " + dsMark + " " + dmMark;
}
public static double avg(ArrayList<Student> studentArr)
{
double[] avgArr = new double[studentArr.size()];
double max = 0.0;
for(int counter = 0; counter < studentArr.size(); counter++)
{
avgArr[counter] = (studentArr.get(counter).getWebMark() +
studentArr.get(counter).getDSMark() + studentArr.get(counter).getDMMark())/(3);
if(avgArr[counter] > max)
{
max = avgArr[counter];
}
}
return max;
}
public int compareTo(Student studCompare)
{
int compareRollNum = ((Student) studCompare).getRollNum();
//ascending order
return this.rollNum - compareRollNum;
}
/*Comparator for sorting the array by student name*/
public static Comparator<Student> StuNameComparator = new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
String StudentName1 = s1.getName().toUpperCase();
String StudentName2 = s2.getName().toUpperCase();
//ascending order
return StudentName1.compareTo(StudentName2);
//descending order
//return StudentName2.compareTo(StudentName1);
}
};
/*Comparator for sorting the array by student name*/
public static Comparator<Student> StuRollno = new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
int rollno1 = s1.getRollNum();
int rollno2 = s2.getRollNum();
//ascending order
return rollno1-rollno2;
//descending order
//return StudentName2.compareTo(StudentName1);
}
};
public static <T extends Comparable<T>> List<T> mergeSort(List<T> m)
{
// exception
if (m==null) throw new NoSuchElementException("List is null");
// base case
if (m.size() <= 1) return m;
// make lists
List<T> left = new ArrayList<>();
List<T> right = new ArrayList<>();
// get middle
int middle = m.size()/2;
// fill left list
for (int i = 0; i < middle; i++)
{
if (m.get(i)!=null) left.add(m.get(i));
}
// fill right list
for (int i = middle; i < m.size(); i++)
{
if (m.get(i)!=null) right.add(m.get(i));
}
// recurse
left = mergeSort(left);
right = mergeSort(right);
// merge
return merge(left,right);
}
private static <T extends Comparable<T>> List<T> merge(List<T> left, List<T> right)
{
List<T> result = new ArrayList<>();
// merge
while (!left.isEmpty() && !right.isEmpty())
{
if (left.get(0).compareTo(right.get(0)) <= 0)
{
result.add(left.remove(0));
}
else
{
result.add(right.remove(0));
}
}
// cleanup leftovers
while (!left.isEmpty())
{
result.add(left.remove(0));
}
while (!right.isEmpty())
{
result.add(right.remove(0));
}
return result;
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userChoice = 0;
int userChoice2 = 0;
ArrayList<Student> studentArr = new ArrayList<Student>(); //array size is 6
System.out.println("1- Merge Sort");
System.out.println("2- Shell Sort");
System.out.println("3- Quit");
userChoice2 = input.nextInt();
if (userChoice2 == 1 || userChoice2 == 2)
{
do {
System.out.println("1- Add a New Record");
System.out.println("2- Sort by Student Name");
System.out.println("3- Sort by Roll Number");
System.out.println("4- Delete a Student Specific Record");
System.out.println("5- Display a Student Specific Record");
System.out.println("6- Search");
System.out.println("7- Display the Highest Average");
System.out.println("8- Print"); //print the array size, sort time, and number of comparisons to the screen.
System.out.println("9- Quit");
System.out.println("Select your Option: \n");
userChoice = input.nextInt();
switch (userChoice) {
case 1:
Student.addStudent(studentArr);
break;
case 2:
if (userChoice2 == 1) {
//call mergesort function
} else if (userChoice2 == 2) {
//call shell sort function
}
case 3:
if (userChoice2 == 1) {
//call mergesort function
} else if (userChoice2 == 2) {
//call shell sort function
}
case 4:
Student.deleteStudent(studentArr);
break;
case 5:
System.out.println("Enter Student Roll Number: ");
int rollNum_ = input.nextInt();
Student.findStudent(rollNum_, studentArr);
break;
case 6:
case 7:
double highestAvg = Student.avg(studentArr);
System.out.println("Highest Average is: " + highestAvg);
break;
case 8:
System.out.println("Printing students...");
System.out.print(studentArr);
System.out.println("\n");
break;
case 9:
}
} while (userChoice != 9);
}
else
{
return;
}
input.close();
}
}
Your Student is already Comparable and it already compares to other Student instances using rollNum field, so the current implementation using compareTo() should already sort on that field.
But if you want to sort using a different ordering, you could write a Comparator and change your sorting method like so:
private static <T> List<T> merge(List<T> left, List<T> right, Comparator<? super T> comparator) {
.. use comparator.compare(a, b) instead of a.compareTo(b)
}
Here, you don't need to restrict T with Comparable.
in order to sort anything , the object must be comparable by somewhat. In java, there are 2 ways to do it for objects (like student):
Comparable and Comparator.
That being said, your object must implement Comparable interface and then write implementation of the necessary method compareTo where you list how you want then to compare to each other.
Another way is to implement Comparator interface and write implementation for compare method.
Once that is done, you can sort the collection with Collection.sort ..... method.
i'm new to programming and i'd like to ask that why is it that in my code i do not need to use a return function in the constructor and method?
Also why is it that after using the yearPasses function age is increased by 3 and not 1?
Apology for the lengthy code
public class Person
{
private int age;
public Person(int initialAge)
{
// Add some more code to run some checks on initialAge
if (initialAge<0)
{
System.out.println("Age is not valid, setting age to 0.");
initialAge = 0;
age = initialAge;
}
else
{
age = initialAge;
}
}
public void amIOld()
{
if (age<13)
{
System.out.println("You are young.");
}
else if (age>=13 && age<18)
{
System.out.println("You are a teenager.");
}
else
{
System.out.println("You are old.");
}
}
public void yearPasses()
{
age = age + 1;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++)
{
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++)
{
p.yearPasses();
}
p.amIOld();
System.out.println();
}
sc.close();
}
}
You don't need a return in the constructor because a constructor's job is to create an object. The new operator returns that object for you, so it doesn't need to be in the constructor itself.
Your other methods are declared with a return type of void, which means they don't return anything, so you don't need return statements in those either.
You're calling yearPasses in a loop that executes three times.
Constructors create the object, the new keyword is where the object is returned.
All your other methods are labelled as void, meaning they do not return anything.
You could add a return to your yearPasses method, that will return the new age if you want, however it depends on what you need it to do. (This is just an example of using the return)
I'm working on a program that supports inserting into a string, deleting a substring from a string, and an undo method. My professor provided the driver, which shouldn't be changed. I've written my own relevant SmartString and UndoMethod classes (there's also ADT and Test classes, but don't worry about those). But whenever I try to insert a string, I keep getting an IndexOutofBoundsException. I've accounted for the offset in StringBuilder, but I still can't quite get my code to work. The output that I got is below as well. Here is the SmartString class:
import java.util.Stack;
public class SmartString implements SmartStringADT{
StringBuilder stringBuild = new StringBuilder();
Stack<UndoMethod> undoStack = new Stack<>();
private String newString;
boolean undo = false;
public SmartString(){
newString = "";
}
public SmartString(String newString){
StringBuilder stringBuild = new StringBuilder(newString);
}
public void insert(int pos, String sstring) {
// TODO Auto-generated method stub
stringBuild.insert(pos+1, sstring);
if(!undo){
undoStack.push(new UndoMethod(sstring, sstring.length(), pos+1, 2));
}
}
public void delete(int pos, int count) {
// TODO Auto-generated method stub
stringBuild.delete(pos, (pos+count));
if(!undo){
undoStack.push(new UndoMethod(stringBuild.substring(pos, pos+count), count, pos-1,1));
}
}
public void undo() {
// TODO Auto-generated method stub
UndoMethod temp = undoStack.pop();
undo = true;
if(temp.getAction() == 1){
insert(temp.getPos(), temp.getString());
}
if(temp.getAction() == 2){
delete(temp.getPos(), temp.getCount());
}
undo = false;
}
}
My UndoMethod class:
public class UndoMethod {
private String ssString;
int count;
int pos;
int action;
public UndoMethod(){
ssString = "";
count = 0;
pos = 0;
action = 0;
}
public UndoMethod(String SSString, int Count, int Position, int Action){
ssString = SSString;
count = Count;
pos = Position;
action = Action;
}
public String getString(){
return ssString;
}
public void setString(String SSString){
ssString = SSString;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
}
My output:
Enter an action
1
Enter the position (begin counting at 0) of the letter after which to insert
19
Enter the string to insert
I am doing great!
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String >index out of range: 20
at java.lang.AbstractStringBuilder.insert(AbstractStringBuilder.java:1005)
at java.lang.StringBuilder.insert(StringBuilder.java:291)
at SmartString.insert(SmartString.java:20)
at SmartStringDriver.main(SmartStringDriver.java:38)
And for reference, the driver class, which should be good:
public static void main(String[] args) {
//Declare variables and objects
Scanner scan = new Scanner(System.in);
int action = 1, start = 0, count = 0;
String menu = "\n(1) insert\n(2) delete\n(3) Undo\n(4) Quit";
SmartString str;
String insertS = "";
System.out.println("Enter your initial Smart String:");
str = new SmartString(scan.nextLine());
try{
do{
//Prompt for an action - Insert, Delete, Undo, Quit
System.out.println("Your smart string is: \n\t" + str + " \n\t(indexing from 0 to " + (str.toString().length()-1) + " - length of " + str.toString().length() + ")");
System.out.println(menu);
System.out.println("Enter an action");
action = scan.nextInt();
scan.nextLine();
//Determine which action and prompt for necessary input
switch (action) {
case 1:
System.out.println("Enter the position (begin counting at 0) of the letter after which to insert " + insertS);
start = scan.nextInt();
scan.nextLine();
System.out.println("Enter the string to insert");
insertS = scan.nextLine();
//Invoke SmartString insert method
str.insert(start, insertS);
break;
case 2:
System.out.println("Enter the position (begin counting at 0) of the first letter to delete");
start = scan.nextInt();
System.out.println("Enter the number of letters to delete (count)");
count = scan.nextInt();
//Invoke SmartString delete method
str.delete(start, count);
break;
case 3:
//Invoke SmartString undo method
str.undo();
break;
}
}while (action != 4);
}
catch(InputMismatchException e) {
System.out.println("Entry must be numeric!");
}
System.out.println("\n Your final Smart String is " + str);
}
}
EDIT: Also, here's the SmartStringADT:
public interface SmartStringADT {
public void insert(int pos, String sstring);
public void delete(int pos, int count);
public void undo();
public String toString();
}
I made a program which asks the user for their pet name and assigns it states of mind for 5 rounds. If the pet gets too angry it is put down.
What I am having trouble with is allowing the user to restart to an earlier stage at the game before the pet died.
Compiling the code would help illustrate the issue.
Any help would be appreciated.
import java.util.Random;
import java.util.Scanner;
class dinoo {
public static void main(String[] p) {
Pet p1 = new Pet();
Pet p2 = new Pet();
Scanner scanner = new Scanner(System.in);
String petname;
String species;
String angerlevel;
int thirst;
int hunger;
int irritability;
explain();
petname = askpetname();
species = askpetspecies();
int howmanyrounds = 5;
for (int i = 0; i < howmanyrounds; i++) {
int number = i + 1;
String num = Integer.toString(number);
print("Round " + number);
String[] emotionalstate = newarray(5);
thirst = thirstlevel(p1);
hunger = hungerlevel(p1);
irritability = irritabilitylevel(p1);
angerlevel = anger(hunger, thirst, irritability);
p1 = setpetname(p1, petname);
p1 = setspecies(p1, species);
p1 = setthirst(p1, thirst);
p1 = setanger(p1, angerlevel);
p1 = sethunger(p1, hunger);
p1 = setangervalue(p1, irritability);
print(petname + "'s thirst level is " + thirst + " , hunger level is " + hunger + ", irritability level is " + irritability + " and therefore emotional state is " + angerlevel);
if (angerlevel.equals("DANGEROUS")) {
print(petname + " is looking " + angerlevel + ", get out now! we will have to put " + petname + " down.");
boolean continueEnd = petdead();
if (continueEnd == false) {
System.exit(0);
} else {
emotionalstate = wheretogo(emotionalstate[]);
}
} else if (angerlevel.equals("Serene")) {
print("He looks " + angerlevel + ". Seems in a good mood.");
} else if (angerlevel.equals("Grouchy")) {
print("You should give him a treat to cheer him up.");
}
whatdoyouwant(p1);
print("Your pets emotion is now " + anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1)));
emotionalstate[i] = anger(getthirst(p1), gethungervalue(p1), getirritabilityvalue(p1));
print("Emotional state " + emotionalstate[i] + " has been saved!");
}
System.exit(0);
}
public static String[] wheretogo(String[] a) {
Scanner scanner = new scanner;
print("which level would you like to return to?");
int number = scanner.nextInt();
String level = a[number];
return a;
}
public static boolean petdead() {
Scanner scanner = new Scanner(System.in);
print("Your pet has been killed. Would you like to continue? (True or False)");
boolean yesorno = scanner.nextBoolean();
return yesorno;
}
public static int inputint(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
int answer = scanner.nextInt();
return answer;
}
public static String[] newarray(int arraylength) {
String[] emotionalstate = new String[arraylength];
return emotionalstate;
}
//takes input from user to cheerup/feed/sing to the animal to lower values stored in setter/getter
public static Pet whatdoyouwant(Pet p1) {
Scanner scanner = new Scanner(System.in);
print("what would you like to do to the pet? (treat/water/sing)");
String ans = scanner.nextLine();
Random ran = new Random();
int reduction = ran.nextInt(6);
if (ans.equalsIgnoreCase("treat")) {
int hunger = gethungervalue(p1) - reduction;
if (hunger < 0) {
hunger = 0;
}
p1 = sethunger(p1, hunger);
print("Your pets hunger has been reduced to:");
printint(gethungervalue(p1));
} else if (ans.equals("sing")) {
int irrit = getirritabilityvalue(p1) - reduction;
if (irrit < 0) {
irrit = 0;
}
p1 = setirritability(p1, irrit);
print("Your pets irritability hs been reduced to:");
printint(getirritabilityvalue(p1));
} else if (ans.equals("water")) {
int thirst = getthirst(p1) - reduction;
if (thirst < 0) {
thirst = 0;
}
p1 = setthirst(p1, thirst);
print("Your pets thirst is has been reduced to:");
printint(getthirst(p1));
} else {
print("That action seems to agitate your pet, try something else before your pet becomes dangerous!");
}
return p1;
}
//GETTER METHOD
public static String getpetname(Pet p) {
return p.name;
}
public static String getspecies(Pet p) {
return p.species;
}
public static String getanger(Pet p) {
return p.anger;
}
public static int getthirst(Pet p) {
return p.thirst;
}
public static int gethungervalue(Pet p) {
return p.hunger;
}
public static int getangervalue(Pet p) {
return p.angervalue;
}
public static int getirritabilityvalue(Pet p) {
return p.irritability;
}
//SETTER METHOD
public static Pet setangervalue(Pet p, int whatsangervalue) {
p.angervalue = whatsangervalue;
return p;
}
public static Pet setpetname(Pet p, String name) {
p.name = name;
return p;
}
public static Pet setspecies(Pet p, String petspecies) {
p.species = petspecies;
return p;
}
public static Pet setanger(Pet p, String howangry) {
p.anger = howangry;
return p;
}
public static Pet sethunger(Pet p, int howhungry) {
p.hunger = howhungry;
return p;
}
public static Pet setthirst(Pet p, int howthirsty) {
p.thirst = howthirsty;
return p;
}
public static Pet setirritability(Pet p, int howirritable) {
p.irritability = howirritable;
return p;
}
//Method printing out statement to explain functionality of program
public static void explain() {
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
//Method to ask the pet name
public static String askpetname() {
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
return petname;
}
//Method to ask the pet species
public static String askpetspecies() {
Scanner scanner = new Scanner(System.in);
print("What species is your pet?");
String petspecies = scanner.nextLine();
return petspecies;
}
//Randomly allocates thirst value 0-10
public static int thirstlevel(Pet p1) {
Random ran = new Random();
int thirst = ran.nextInt(11);
setthirst(p1, thirst);
return thirst;
}
//Randomly Allocates hunger value 0-10
public static int hungerlevel(Pet p1) {
Random ran = new Random();
int hunger = ran.nextInt(11);
sethunger(p1, hunger);
return hunger;
}
//randomly generates a irratibilty value
public static int irritabilitylevel(Pet p1) {
Random ran = new Random();
int irritable = ran.nextInt(11);
setirritability(p1, irritable);
return irritable;
}
//Method calculates the anger value based on the thirst/hunger/irritability average
public static String anger(int thirst, int hunger, int irritability) {
int angerscore = (thirst + hunger + irritability) / 3;
String temper;
temper = Integer.toString(angerscore);
if (angerscore <= 1) {
temper = "Serene";
} else if (angerscore <= 3) {
temper = "Grouchy";
} else if (5 < angerscore) {
temper = "DANGEROUS";
}
return temper;
}
//HELPER PRINT METHOD
public static String print(String message) {
System.out.println(message);
return message;
}
public static int printint(int message) {
System.out.println(message);
return message;
}
}//END class dinoo
class Pet {
String name;
String species;
int thirst;
int hunger;
String anger;
int irritability;
int angervalue;
} //END class pet
First of all you should look at the compile errors in your code before submitting a question here.
Please read the links provided in the comments to learn how to submit a proper question.
I tried to compile your code and it had the following errors:
java2.java:51: error: '.class' expected
emotionalstate = wheretogo(emotionalstate[]);
^
java2.java:75: error: '(' or '[' expected
Scanner scanner = new scanner;
That means in line 51, you're passing emotionalstate[] , which is emotional state array, whereas emotionalstate itself is an array, so you're passing an array of an array.
So just change it to emotionalstate = wheretogo(emotionalstate)
And in line 75, your initialization of Scanner object is wrong, change it to Scanner scanner = new Scanner();
I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep