I have created a function "m7" in my class but this function is always returning value getting multiplied by 2.
If I am running this function in "psvm" it is printing the right value.
In my Alice class, the method m7() is returning 10 which is incorrect but if I am running this method in psvm then it is returning 5 which is correct.
package com.math.functions;
import java.util.*;
public class Alice {
Integer[] rank= new Integer[7];
Integer n=65;
int count=0;
public Alice() {
rank[0]=100;
rank[1]=100;
rank[2]=90;
rank[3]=80;
rank[4]=75;
rank[5]=60;
rank[6]=n;
//rank[6]=20;
//rank[7]=10;
//rank[8]=n;
Arrays.sort(rank, Collections.reverseOrder());
}
public void print() {
for (Integer a : rank) {
System.out.println(a);
}
}
public int m7() {
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}
public void res(){
int s = m7();
System.out.println("this is the value of s here :"+s);
Set<Integer> hash_Set = new HashSet<>();
for(int i=0;i<=s/2;i++){
System.out.println("hii");
hash_Set.add(rank[i]);
}
for(Integer o:hash_Set){
System.out.println(o);
System.out.println("rank:"+hash_Set.size());
}
}
public static void main(String[] args) {
Alice a=new Alice();
a.print();
System.out.println("this is: "+a.m7());
a.res();
}
}
You are reusing the value of count from the previous time you run it.
Don't declare count as a member variable, make it a local variable.
public int m7() {
int count = 0; // HERE
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}
Related
Good evening everyone, sorry for bothering.
I have a problem while trying to configure the "DynamicArray" by myself. Here I made a sort method but the terminal shows "error:unexpected type", I actually have some difficulty of solving this, can some one help me to check what's the problem I have?
Thanks in advance.
Here is my code:
package lab2;
public class DynamicArray {
private static int INITIAL_CAPACITY = 5;
private int[] data;
private int size;
public DynamicArray() {
data = new int[INITIAL_CAPACITY];
size = 0;
}
// Returns `true` if the array is empty.
public boolean isEmpty() {
if (size==0){
return true;
}
else{
return false;
}
}
// Returns the size of the array.
public int size() {
return size;
}
// Remove all elements from data.
public void clear() {
size=0;
}
// Create a `String` with the elements of the array separated by comma, without a new line character at the end.
// For instance: 4, 5, 6
public String toString() {
if(size==0){
return "";
}
StringBuilder a = new StringBuilder();
for(int i=0;i<size;i++){
if(i==size-1){
a.append(data[i]);
}
else{
a.append(data[i]).append(",").append(" ");
}
}
return a.toString();
}
// Returns `true` if the array `data` is full: no more element can be added to `data`.
// Returns `false` otherwise.
private boolean isFull() {
if(size==data.length){
return true;
}
return false;
}
// If the array `data` is full:
// 1. Create a new array `data2` doubling the size of data.
// 2. Copy the elements of `data` into `data2`.
// 3. Assign `data2` to `data`.
private void realloc() {
if(size==data.length){
int [] data2 = new int[data.length*2];
System.arraycopy(data, 0, data2, 0,data.length);
data=data2;
}
}
// The element `x` is added to `data`, and `size` is incremented by one.
// `data` is automatically resized if it is too small.
public void add(int x) {
realloc();
data[size++]=x;
}
private void checkIndex(int idx) {
if(idx >= size) {
throw new ArrayIndexOutOfBoundsException();
}
}
// Set the ith element of `data` to `x`.
public void set(int idx, int x) {
int a = data[idx];
data[idx]=x;
}
// Return the element at the index `idx` of `data`.
public int get(int idx) {
checkIndex(idx);
return data[idx];
}
// Remove the element at index `idx`.
// Shift all the elements after `idx` of one position to the left.
public void remove(int idx) {
checkIndex(idx);
for(int i = idx; i<size-1; i++){
data[i]=data[i+1];
}
size--;
}
}
And the code which the problem appear:
package lab2;
public class DynamicArrayTest {
public static void main(String[] args) {
DynamicArray array = new DynamicArray();
testAdd(array);
testRemove(array);
testGet(array);
testRealloc(array);
testSort(array);
}
public static void testAdd(DynamicArray array) {
System.out.println("Test add method.");
System.out.println(array.size());
System.out.println(array.isEmpty());
array.clear();
System.out.println(array.size());
System.out.println(array.isEmpty());
array.add(4);
array.add(5);
array.add(6);
System.out.println(array);
}
public static void testRemove(DynamicArray array) {
System.out.println("Test remove method.");
try {
for(int i = 0; i < 3; ++i) {
array.remove(1);
System.out.println(array);
System.out.println(array.size());
System.out.println(array.isEmpty());
}
}
catch(ArrayIndexOutOfBoundsException e) {}
array.remove(0);
System.out.println(array);
System.out.println(array.size());
System.out.println(array.isEmpty());
}
public static void testGet(DynamicArray array) {
System.out.println("Test get method.");
try {
array.get(4);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("OK");
}
}
public static void testRealloc(DynamicArray array) {
System.out.println("Test realloc method.");
for(int i = 0; i < 100; ++i) {
array.add(i);
}
System.out.println(array);
while(!array.isEmpty()) {
array.remove(0);
}
System.out.println(array);
System.out.println(array.size());
System.out.println(array.isEmpty());
}
public static void testSort(DynamicArray array){
System.out.println("Sort the array.");
for(int i =0; i<array.size(); ++i){
for (int j=0; j<array.size() - i; ++j){
if (array.get(j-1)<array.get(j)){
int a = array.get(j-1);
array.get(j-1)=array.get(j);
array.get(j)=a;
}
}
}
}
}
And the error code:
public static void testSort(DynamicArray array){
System.out.println("Sort the array.");
for(int i =0; i<array.size(); ++i){
for (int j=0; j<array.size() - i; ++j){
if (array.get(j-1)<array.get(j)){
int a = array.get(j-1);
array.get(j-1)=array.get(j);
array.get(j)=a;
}
}
}
}
Again, the terminal shows:
src/lab2/DynamicArrayTest.java:72: error: unexpected type
array.get(j-1)=array.get(j);
^
required: variable
found: value
src/lab2/DynamicArrayTest.java:73: error: unexpected type
array.get(j)=a;
^
required: variable
found: value
2 errors
Thanks a lot for your help.
array.get(j-1)=array.get(j);
array.get(j)=a;
should be
array.set(j-1, array.get(j));
array.set(j, a);
This line is trying to assign a value to a value. The left side of this statement would need to be a variable. You did the same mistake in multiple places.
array.get(j-1)=array.get(j);
You either need to assign the value of array.get(j) to a variable or call a setter on the array object, setting the position of j-1 to the value returned by array.get(j). Depending on what you want to do with the value.
I have been given an assignment to do the following
Generate id numbers for employees - Each id number must meet the following requirements:
a. It must be a prime number
b. It must not match a previously generated ID number
c. It must be exactly 5 digits in length
Store Employee data – for this feature the application must allow you to enter a new employee’s full name and their assigned ID number. These must be stored in the application.
So far am unsure of if am doing the correct thing but I have some code I started up below...
import java.util.Scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
primenum();
}
public static void primenum() {
int max = 20000;
System.out.println("Generate Prime num" + max);
for (int i = 10000; i < max; i++) {
boolean isPrimeNumber = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrimeNumber = false;
}
}
// print the number if prime
if (isPrimeNumber) {
System.out.println(i + " ");
}
}
}
public static void ID() {
String[] emp = new String[10];
emp[0] = "John";
emp[1] = "Mary";
emp[2] = "James";
emp[3] = "chris";
emp[4] = "charles";
}
I have just created an array that will hold some names.. but my main objective I want to get is for the next prime number generated to be stored in each of the emp[] associated with a name .. so for eg. emp[0] which is john I want him to be able to receive the next prime number for the primenum() method.. I am unsure of how to do this and will love all help apprecited.
use this solution:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class PrimeNumber {
public static void main(String[] args) {
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("John", nextPrime(1));
map.put("Mary", nextPrime(map.get("John")));
map.put("James", nextPrime(map.get("Mary")));
map.put("chris", nextPrime(map.get("James")));
map.put("charles", nextPrime(map.get("chris")));
for(Entry<String, Integer> e:map.entrySet()) {
System.out.println(e.getKey()+": "+e.getValue());
}
}
public static int nextPrime(int input){
int counter;
input++;
while(true){
int l = (int) Math.sqrt(input);
counter = 0;
for(int i = 2; i <= l; i ++){
if(input % i == 0) counter++;
}
if(counter == 0)
return input;
else{
input++;
continue;
}
}
}
}
To associate a prime number with your employee name:
Create a custom object which is responsible for relation between employee object and prime number(ID) like below :
public class EmployeeNameAndId {
private Employee employee;
private Integer id;
// constructors, getters, setters here
}
Now you need to use this object in your main class like below :
public class MainClass {
public static void main(String[] args) {
List<EmployeeNameAndId> l = new ArrayList<>();
l.add(new EmployeeNameAndId("John", generatePrimeId());
l.add(new EmployeeNameAndId("Mary", generatePrimeId());
l.add(new EmployeeNameAndId("James", generatePrimeId());
l.add(new EmployeeNameAndId("Chris", generatePrimeId());
}
}
The method should return true if the argument is even, or
false otherwise. The program’s main method should use a loop to generate 100 random integers. It should use the isEven method to determine whether each random number is even, or odd. All this is done!!!
This is the part where I can't figure it out!
When the loop is finished, the program should display the number of even numbers that were generated, and the number of odd numbers.
This is my code:
import java.util.Random;
public class EvenOdd
{
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
EvenOdd(randomInteger);
}
}
public static void EvenOdd(int x)
{
int oddNumbers = 0;
int evenNumbers = 0;
if ((x % 2) == 0)
{
System.out.println("Even");
evenNumbers++;
}
else
{
System.out.println("Odd");
oddNumbers++;
}
}
}
Try with this:
public static void main(String[] args)
{
Random random = new Random();
int randomInteger = 0;
int oddNumbers = 0;
int evenNumbers = 0;
for(int i = 0; i < 100; i++){
randomInteger = random.nextInt();
System.out.println("Random Integer: " + randomInteger);
if(evenOdd(randomInteger)) evenNumbers++;
else oddNumbers++;
}
System.out.printf("Even numbers: %d - Odd numbers: %d", evenNumbers, oddNumbers);
}
public static boolean evenOdd(int x)
{
if ((x % 2) == 0)
{
System.out.println("Even");
return true;
}
else
{
System.out.println("Odd");
return false;
}
}
Your original approach doesn't work because you initialize to 0 the oddNumbers and evenNumbers variables everytime you call the method.
Define oddNumbers, evenNumbers variables as static class variables and after the loop you can print these 2 value.
Java is not JavaScript. Also, it does not have the ability of C++ as "Static variables in functions".
Variables declared inside a method are local. Variables initialization occurs every time your code reaches a variable definition inside the method and destroyed after exiting from the method.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
So you have such variants:
1) Count numbers inside your main method and return indicator from the utility method.
1.1) boolean
public static boolean isEven(int x){
return (x % 2) == 0;
};
1.2) enum
private enum NumberType {
EVEN,
ODD
}
public static NumberType getNumberType (int x) {
if ((x % 2) == 0) {
return NumberType.EVEN;
} else {
return NumberType.ODD;
}
};
2) Make your variables static:
public class EvenOdd {
private static int evenNumbersCount = 0;
private static int oddNumbersCount = 0;
public static void main(String[] args) {
// your code
}
public static void countNumberType (int x) {
if ((x % 2) == 0) {
++evenNumbersCount;
} else {
++oddNumbersCount;
}
}
}
3) In some sophisticated situations you will need to pass container to your method:
public class EvenOdd {
private static final String EVEN = "even";
private static final String ODD = "odd";
public static void main(String[] args) {
// initialize container
Map<String, Integer> evenOddCounts = new HashMap<>(2, 1);
evenOddCounts.put(EVEN, 0);
evenOddCounts.put(ODD, 0);
Random random = new Random();
int randomInteger = 0;
for (int i = 0; i < 100; i++) {
randomInteger = random.nextInt();
countNumberType(evenOddCounts, randomInteger);
}
System.out.println(evenOddCounts.toString());
}
public static void countNumberType(Map<String, Integer> counts, int x) {
if ((x % 2) == 0) {
counts.compute(EVEN, (numberType, count) -> ++count);
} else {
counts.compute(ODD, (numberType, count) -> ++count);
}
}
}
public class ArrayMethodsTest
{
public static void main(String[] args)
{
int[] tester = {0,1,2,3,4,5};
ArrayMethods test = new ArrayMethods(tester);
for(int element : test)
{
System.out.print(element + " ");
}
test.shiftRight();
for(int element : test) //error: for-each not applicable to expression type
{
System.out.print(element + " ");
}
}
}
I figure what the problem is. Thanks to jigar joshi. However I still need to use the ArrayMethods methods for the tester that I created. I know that they work but how can it be possible to provide a tester class for an object that isn't an array since the methods are for arrays.
public class ArrayMethods
{
public int[] values;
public ArrayMethods(int[] initialValues)
{
values = initialValues;
}
public void swapFirstAndLast()
{
int first = values[0];
values[0] = values[values.length-1];
values[values.length-1] = first;
}
public void shiftRight()
{
int first = 0;
int second = first;
for(int i =0; i < values.length; i++)
{
if(i < values.length-1)
{
first = values[i];
second = values[i+1];
values[i+ 1] = first;
}
if(i == values.length)
{
values[i] = values[0];
}
}
}
}
//0,1,2,3,4,5
//5,0,1,2,3,4
test is reference of ArrayMethods which is not an Iterable or an array type and so is the error
You've already encountered the issue in which you can't iterate over an ArrayMethods, since it's not iterable. What it seems like you want to do is iterate over its values instead, considering that values is a public field.
for(int element : test.values) {
System.out.print(element + " ");
}
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).