This is the zoo manager coding:
public class ZooManager {
public void feedAnimals(Animals a, Food[] arrayFood) {
Food temp = null;
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i].getFoodName().equals(a.getTypeOfFood())) {
arrayFood[i].setAmount(arrayFood[i].getAmount() - 1);
System.out.print("Animal is fed.");
}
}
System.out.print(temp);
}
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
This is the code for the main application:
import java.util.Scanner;
public class ZooApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Animals[] a = new Animals[4];
for (int i = 0; i < 4; i++) {
System.out.print("Enter the animal name: ");
String an = in.nextLine();
System.out.print("What type of food do they eat: ");
String tof = in.nextLine();
a[i] = new Animals(an, tof);
}
Food[] b = new Food[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter the type of food: ");
String f = in.nextLine();
System.out.print("Enter the amount: ");
int am = in.nextInt();in.nextInt();
b[i] = new Food(f, am);
}
ZooManager z= new ZooManager();
System.out.print(z.feedAnimals(a[i], b));
System.out.print(z.isFoodEmpty(b[i]));
}
}
I have an error at the two final out prints on the main application. The first one is that "the void type is not allowed there." and "variable i can not be found." The second out put says that "isFoodEmpty cannot be given to the type: Food, required: Food[]." Thank you for any advice or help.
Your isFoodEmpty function is a void, so the first error is telling you that you can't print it because it doesn't return anything. Second, you are passing an individual instance of Food into a function that is looking for an array. That's the second error. Also note that variable i is only defined within the scope of the for loop, so you can't go using it outside of the loop.
Edit:
Currently your isFoodEmpty is a void. you have one of two options:
public void isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
System.out.print("True");
} else {
System.out.print("False");
}
}
}
}
[...]
isFoodEmpty(b); // it already prints within the function
or
public boolean isFoodEmpty(Food[] arrayFood) {
for (int i = 0; i < arrayFood.length; i++) {
if (arrayFood[i] == null) {
return true;
} else {
return false;
}
}
}
}
[...]
System.out.println(isFoodEmpty(b)); // print the boolean that it returns
Either way, you might want to check the logic on that function, since it will return empty if even one of the elements in the array is null. (You could have 20 food items, then one null value, and it would return true).
Related
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)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
I think this part may be the reason I'm getting the NullPointerException error, but I don't know what I'm missing. I have put my full code for the program below just in case there is something that is wrong with that that is giving me that error message.
//client class
public class Downsize
{
public static void main (String [] args)
{
System.out.print("Do you want to downsize the company? (Y/N): ");
String dummy = APIO.getString().toUpperCase();
while (dummy.equals("Y"))
{
Employee employee = new Employee();
System.out.print("Do you want to downsize the company? (Y/N):
dummy = APIO.getString().toUpperCase();
}
}
}
//object class
public class Employee
{
int numEmp;
int sprayer;
int winner;
boolean [] employees;
public Employee()
{
System.out.print("How many employees? (0 to end): ");
int numEmp = APIO.getInt();
System.out.print("Who gets the spray can first?: ");
int sprayer = APIO.getInt();
FillArray();
Selection();
Winner();
}
public void FillArray()
{
for (int i = 1; i < numEmp; i++)
{
employees[i] = true;
}
}
public void Selection()
{
System.out.println("EM="); //debugging method
for (boolean em: employees)
{
System.out.println(em);
}
int complete = numEmp;
while (complete > 1)
{
System.out.print("spraycan passed to #" + sprayer);
if ((sprayer + 1) > numEmp)
{
sprayer = 0;
}
while (employees[sprayer + 1] == false)
{
sprayer++;
if (sprayer >= numEmp)
{
sprayer = 0;
}
}
employees[sprayer + 1] = false;
System.out.print(" - sprays #" + (sprayer + 1) + "'s hair");
complete--;
sprayer++;
while (employees[sprayer] == false)
{
sprayer++;
if (sprayer > numEmp)
{
sprayer = 1;
}
}
}
}
public void Winner()
{
if (sprayer == 0)
{
sprayer = 1;
System.out.print("\nThe Winner is #" + sprayer);
System.out.print("\n");
}
}
}
//stack trace for the error message
java.lang.NullPointerException
at Employee.FillArray(Employee.java:22)
at Employee.<init>(Employee.java:14)
at Downsize.main(Downsize.java:9)
You must initialize the employees array. Once you read in the number of employees, do employees = new boolean[numEmp]; (after the line int numEmp = APIO.getInt();). Otherwise, it is null, so trying to access employees[i] throws a NullPointerException.
I see that you guys are beating around the bush in #mook's answer so let me just clarify so the OP can understand it well instead of guessing.
class Example {
int size;
boolean[] array;
void initArray() {
size = 5;
array = new boolean[size];
}
}
After declaring the size of the array and its type, you need to initialize the array. In the above example array holds 5 booleans.
If instead you write
class Example {
int size;
boolean[] array = new boolean[size];;
void initArray() {
size = 5;
}
}
Then since int is set to 0 by default, the size of array will be 0 even if you change the variable you used to declare the size later in the code. This will give you an error since you will iterate up to 5.
#mook's answer is correct.
Hi I am having trouble with Scanner to get user input two separate ArrayList. When I run this code I get an IndexOutOfBounds exception after entering the two arrays.
The code adds two binary numbers together using logic of a ripple adder. An example of intended user input would be
Enter A array: 1 0 1 0
Enter B Array: 0 0 0 1
producing: 1 0 1 1
The code works when arrays are hard coded, how can I get the user to enter the arrays?
Code is shown below
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner inputA = new Scanner(System.in);
ArrayList<Integer> aList = new ArrayList<Integer>();
ArrayList<Integer> bList = new ArrayList<Integer>();
int c = 0;
System.out.println("Enter A array");
aList.add(inputA.nextInt());
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
bList.add(inputB.nextInt());
Adder bit1 = new Adder(parseInput(aList.get(3)), parseInput(bList.get(3)), parseInput(c));
Adder bit2 = new Adder(parseInput(aList.get(2)), parseInput(bList.get(2)), bit1.getCout());
Adder bit3 = new Adder(parseInput(aList.get(1)), parseInput(bList.get(1)), bit2.getCout());
Adder bit4 = new Adder(parseInput(aList.get(0)), parseInput(bList.get(0)), bit3.getCout());
if (bit4.getCout() == false) {
System.out.println(bit4.toString() + " " + bit3.toString() + " " + bit2.toString() + " " + bit1.toString());
} else {
System.out.println("overflow!");
}
}
public static boolean parseInput(int i) {
if (i == 1) {
return true;
} else {
return false;
}
}
}
Code for Adder class:
public class Adder {
private boolean a, b, cin, cout, s;
/**
* Full Adder contructor
*/
public Adder(boolean a, boolean b, boolean cin) {
this.a = a;
this.b = b;
this.cin = cin;
s = nand(nand(a, b), cin); //sum bit
cout = or(and(nand(a, b), cin), and(a, b)); // - carry bit
}
/** Half adder constructor */
// public Adder (bloolean a, boolean b) {
//
// this.a = a;
// this.b = b;
//
// s =
//}
/**
* NAND gate
*/
public boolean nand(boolean a, boolean b) {
return a ^ b;
}
/**
* AND gate
*/
public boolean and(boolean a, boolean b) {
return a && b;
}
/**
* OR gate
*/
public boolean or(boolean a, boolean b) {
return a || b;
}
public boolean getCout() {
return cout;
}
public String toString() {
if (s == true) {
return "1";
} else {
return "0";
}
}
public String toStringCout() {
if (cout == true) {
return "1";
} else {
return "0";
}
}
}
Your entire AdderApp class can be simplified and improved to accept any bit length by accepting the input in a slightly different way and then using a for loop to add each bit. The parseInput function can be replaced with a simple boolean comparison:
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter A array");
char[] aIn = input.nextLine().replace(" ", "").toCharArray();
System.out.println("Enter B array");
char[] bIn = input.nextLine().replace(" ", "").toCharArray();
StringBuilder result = new StringBuilder();
Adder bit = new Adder(false, false, false);
for (int i = aIn.length - 1; i >= 0; --i) {
bit = new Adder((aIn[i] == '1'), (bIn[i] == '1'), bit.getCout());
result.append(bit + " ");
}
System.out.println(bit.getCout() ? "overflow!" : result.reverse());
}
}
Scanner.nextInt gets the next integer in the input, and then stops. Each of your lists only contains 1 element.
Use something along these lines instead:
String[] input = inputA.nextLine().split(" ");
for (String s : input)
{
try { aList.add(Integer.parseInt(s)); }
catch(NumberFormatException nfe) { /* handle exception as desired */ }
}
Alternatively, you should be able to use something like:
while (inputA.hasNextInt())
{
aList.add(inputA.nextInt());
}
You should be having a for loop to have an input into your ArrayList.
System.out.println("Enter A array");
for (int i = 0; i < 4; i++) {
aList.add(inputA.nextInt());
}
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
for (int i = 0; i < 4; i++) {
bList.add(inputB.nextInt());
}
The user should input 4 numbers, your one just allow the user to enter 1 number:
int count = 0;
Scanner inputA = new Scanner(System.in);
System.out.println("Enter A array");
while(count < 4){
count++;
aList.add(inputA.nextInt());
}
count = 0;
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
while(count < 4){
count++;
bList.add(inputB.nextInt());
}
If you want to use hasNextInt():
while(inputA.hasNextInt()){
count ++;
aList.add(inputA.nextInt());
if(count == 4){
count = 0;
break;
}
}
I know it may be weird question but I'm really stuck. I have simple program with two classes. I need pass array from class A to class B. I did it but I cannot test it because I have no idea how to run program. When I click on the run then only one class started. I wanted test whole program and cannot find anything how to do it. Is there any command or something which say run class A and then class B? Without it I cannot test class B because values from Array (class A) are not loaded :/ Hope you understand what I mean.
I'm using eclipse.
Thanks!
Class MarkCalculator
import java.util.Scanner;
public class MarkCalculator {
public static int[] exam_grade = new int[6];
public static int[] coursework_grade = new int[6];
public static int[] coursework_weight = new int[2];
public static int[] module_points = new int[6];
public static String module_grade, holder;
public static int counter1 = 0, counter2 = 0;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
for (int i=0; i<3; i++){
System.out.printf(i+1+". Modelue"+" Enter grade of exam:");
while (!input.hasNextInt() ){
System.out.printf("Enter only numbers! Enter grade of your exam: ");
input.next();
}
exam_grade[i]=input.nextInt();
System.out.printf(i+1+". Modelue"+" Enter grade of coursework:");
while (!input.hasNextInt()){
System.out.printf("Enter only numbers! Enter grade of your coursework: ");
input.next();
}
coursework_grade[i]=input.nextInt();
}
computeMark(coursework_grade, exam_grade, module_points);
// calculate module grade
for(int i = 0 ;i < 3; i++){
if (module_points[i] < 35){
System.out.println(i+1+".Module: Fail");
}
else if (module_points[i] >= 35 && module_points[i] <= 40){
System.out.println(i+1+".Module: Pass by compensation");
counter1++;
}
else {
System.out.println(i+1+".Module: Pass");
counter2++;
}
}
holder = computeResult(module_points, counter1,counter2, module_grade);
System.out.println("Your stage result is: "+ holder);
input.close();
}
public static int[] computeMark (int coursework_grade[], int exam_grade[], int module_points[]){
coursework_weight[0]= 50;
coursework_weight[1]= 50;
for(int i=0;i<3;i++)
{
if (coursework_grade[i] < 35 || exam_grade[i] < 35){
module_points[i]=(coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100;
if (module_points[i] > 35){
module_points[i] = 35; }
else {
module_points[i] = 0;
}
}
else {
module_points[i]=((coursework_grade[i]*coursework_weight[0] + (exam_grade[i]*(100-coursework_weight[1])))/100); }
}
return module_points;
}
public static String computeResult (int module_points[], int counter1, int counter2, String module_grade ){
int sum = 0;
double average = 0;
for (int i = 0; i < 3; i++){
sum = sum + module_points[i];
average = sum / 3;
}
for (int i = 0; i < 3; i++){
if (counter2 == 3){
module_grade = "Pass";
}
else if (average >= 40 && counter1 <= 2) {
module_grade = "Pass by compensation";
}
else {
module_grade = "Fail";
}
}
return module_grade;
}
}
Class StudentChart
public class StudentChart {
public static void main(String[] args) {
for (int i = 0; i < 3; i++){
System.out.println(MarkCalculator.coursework_weight);
}
}
}
You only need one main method.
class A {
String s;
public A(String s){
this.s = s;
}
}
public class B {
public static void main(String[] args){
A a = new A("Hello");
System.out.println(a.s + " world!");
}
}
class B will be the application program, the one with the main method. It will get values from class A. class A does not need to run for class B app to work, even though it uses values from class A.
You can have a method with a different name in another class, and call that method from your main method.
Do not call it public static void main though - that should only be used for standalone programs. If the method requires some other code to be run prior to it, it should not be the main method of a Java program.
I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error.
public static void main(String args[])
{
LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
Scanner scan = new Scanner(System.in);
ArrayList<Integer> values = new ArrayList<>();
ArrayList<String> variables = new ArrayList<>();
while(scan.hasNextLine())
{
String line = scan.nextLine();
String[] tokens = line.split(" ");
if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var"))
{
int value = 0;
for(int i=0; i<tokens.length; i++)
{
if(tokens.length==3)
{
value = Integer.parseInt(tokens[2]);
System.out.printf("%5d\n",value);
if(map.containsKey(tokens[0]))
{
values.set(values.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
}
break;
}
else if(tokens[i].charAt(0) == '+')
{
value = addition(tokens, value);
System.out.printf("%5d\n",value);
variables.add(tokens[0]);
if(map.containsKey(tokens[0]))
{
values.set(values.indexOf(tokens[0]), value);
variables.set(variables.indexOf(tokens[0]), tokens[0]);
}
else
{
values.add(value);
}
break;
}
else if(i==tokens.length-1 && tokens.length != 3)
{
System.out.println("No operation");
break;
}
}
map.put(tokens[0], value);
}
if(Character.isDigit(tokens[0].charAt(0)))
{
int value = 0;
if(tokens.length==1)
{
System.out.printf("%5s\n", tokens[0]);
}
else
{
value = addition(tokens, value);
System.out.printf("%5d\n", value);
}
}
if(line.equals("clear"))
{
clear(map);
}
if(line.equals("var"))
{
variableList(variables, values);
}
}
}
public static int addition(String[] a, int b)
{
for(String item : a)
{
if(Character.isDigit(item.charAt(0)))
{
int add = Integer.parseInt(item);
b = b + add;
}
}
return b;
}
public static void clear(LinkedHashMap<String,Integer> b)
{
b.clear();
}
public static void variableList(ArrayList<String> a, ArrayList<Integer> b)
{
for(int i=0; i<a.size(); i++)
{
System.out.printf("%5s: %d\n", a.get(i), b.get(i));
}
}
I included the whole code because I'm not sure where the error is arising from.
I'm assuming the error is arising from storing the values in the ArrayLists.
This line:
values.set(values.indexOf(tokens[0]), value);
Is throwing ArrayIndexOutOfBoundsException .
You are looking up in values where your variable name "a" currently exists, apparently to overwrite it.
However, this makes no sense: values is a List of Integer, and therefore it could never contain your variable name "a".
Therefore, List.indexOf(Object) returns -1. When you try to invoke List.set(E, int) passing -1 it will blow up.