Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Question:
Write a Number class that can be used to determine if a number is odd, even, or
perfect. Then, use this Number class to determine how many numbers in the list are odd, even, and perfect.
Number Class:
public class Number
{
private Integer number;
public Number(int n)
{
number=n;
}
public boolean isEven()
{
if(number % 2 == 0)
return true;
else
return false;
}
public boolean isOdd()
{
if(number % 2 != 0)
return true;
else
return false;
}
public boolean isPerfect()
{
int count = 0;
for(int i = 1; i<number; i++)
{
if(number % i == 0)
count += i;
}
if(number == count)
{
return true;
}
else
return false;
}
public String toString()
{
return "" +number;
}
}
My number class is running good there is no problem in my Number class. But in my number analyzer class where i find the number of odd,even and perfect.
Number Analyzer class:
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer(int l)
{
list=l;
}
public int countOdds()
{
int odd = 0;
for(int i=0; i<list.size(); i++)
{
if(list.isOdd() == true)
return odd++;
}
}
public int countEvens()
{
int even = 0;
for(int x = 0; x<list.size(); x++)
{
if(list.isEven() == true)
return even++;
}
}
public int countPerfects()
{
int perfect = 0;
for(int z = 0; z<list.size(); z++)
{
if(list.isPerfect() == true)
return perfect++;
}
}
public String toString()
{
return "" + list;
}
}
Please make correction on this class so my program run perfectly. I do not understand the problem please make change in this so program work perfectly.
Runner of program:
import static java.lang.System.*;
public class Runner
{
public static void main( String args[] )
{
int[] r = {5, 12, 9, 6, 1, 4, 8, 6 };
NumberAnalyzer test = new NumberAnalyzer(r);
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
}
}
Correct answers with this Runner:
[5, 12, 9, 6, 1, 4, 8, 6]
odd count = 3
even count = 5
perfect count = 2
Thank you
I didn't understand how it could work if it even didn't complile but nevermind. You need to change 2 classes: NumberAnalyzer and Runner. Please have a look:
public class Runner {
public static void main(String args[]) {
Number[] r = {new Number(5), new Number(12), new Number(9), new Number(6),
new Number(1), new Number(4), new Number(8), new Number(6)};
NumberAnalyzer test = new NumberAnalyzer(r);
out.println(test);
out.println("odd count = " + test.countOdds());
out.println("even count = " + test.countEvens());
out.println("perfect count = " + test.countPerfects() + "\n\n\n");
}
}
and
import java.util.Arrays;
import java.util.List;
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer(Number[] l) {
list = Arrays.asList(l);
}
public int countOdds() {
int odd = 0;
for (Number value : list) {
if (value.isOdd() == true) {
odd++;
}
}
return odd;
}
public int countEvens() {
int even = 0;
for (Number value : list) {
if (value.isEven() == true) {
even++;
}
}
return even;
}
public int countPerfects() {
int perfect = 0;
for (Number value : list) {
if (value.isPerfect() == true) {
perfect++;
}
}
return perfect;
}
public String toString() {
return "" + list;
}
}
in that case it returns a correct output.
Your approach for resolving this problem has a lot of problems, especially in NumberAnalyzer class.
1) You should call the isOdd(), isEven() etc. on an element of the list, not on the list itself -> list.get(i).isEven()
2) The return even++ will exit the loop and return 1 if the condition is met, and the method is not even working since you don't have a return statement in case if the if statement from the for loop doesn't get executed.
3) Not a big problem, but the x and z can be declared as i too -> more intuitive ( i ndex)
4) The isPerfect() method is not correct, an easy solution to solve this problem could be using Math.sqrt() and Math.floor()
5) You're trying to pass an int[] array and the constructor expect an int. And after this, you have an ArrayList<Number> inside the NumberAnalyzer class and you're trying to assign to this list an int value.
Solutions:
1) + 2) + 3) :
public class NumberAnalyzer {
private List<Number> list; //Changed the ArrayList<> to List<>
public NumberAnalyzer(List<Number> l) {
list = l;
}
public int countOdds() {
int odd = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).isOdd())
odd++;
}
return odd;
} // SAME FOR THE OTHER METHODS.
}
4)
public boolean isPerfect()
{
int square = Math.sqrt(number);
return (square - Math.floor(square)) == 0;
}
5) The static void main method should now look like this:
Integer[] r = {5, 12, 9, 6, 1, 4, 8, 6};
List<Integer> rList = Arrays.asList(r);
List<Number> numberList = rList.stream().map(Number::new).collect(Collectors.toList());
NumberAnalyzer test = new NumberAnalyzer(numberList);
Related
I have to find a missing element from the array where array has got values from <0, N>.
For example: int tablica[] = {0, 1, 2, 3, 5};, missing number is 4.
I have got 3 implementations of this code, but...
Only one gives me output, why?
Why naiveFindMissing() and optimalFindMissing() don't give any output?
public class Zad2_Selftraining {
public static void main(String[] args) {
findMissing();
naiveFindMissing();
optimalFindMissing();
}
public static void findMissing() {
int tablica[] = {0, 1, 2, 3, 5};
for(int i = 0; i<tablica.length;i++ ){
if (tablica[i] != i){
System.out.println("Missing: " + i);
return;
}
}
System.out.println("Everything is correct");
return;
}
private static int naiveFindMissing() {
int array[] = {0,1,2,4,5,6,7};
int missing = 0;
boolean elementFound;
for (int elementToFind = 0; elementToFind <= array.length; elementToFind++) {
elementFound = false;
for (int elementInArray : array) {
if (elementToFind == elementInArray) {
elementFound = true;
break;
}
}
if (!elementFound) {
missing = elementToFind;
break;
}
}
return missing;
}
private static int optimalFindMissing() {
int array[] = {0,1,2,4,5,6,7};
int expectedSum = (array.length + 1) * array.length / 2;
int actualSum = 0;
for (int element : array) {
actualSum += element;
}
return expectedSum - actualSum;
}
}
Because you have System.out.println statement only in first method. The other two methods just return result without printing it
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running
package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class bubbleSort {
public static void main(String[] args) {
int length = getLength();
List<Integer> randomList = createList(length);
System.out.println("The list before sorting:\n" + randomList);
List<Integer> newList = sortList(randomList, length);
System.out.println("The list after sorting:\n" + newList);
}
public static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
int length = Integer.parseInt(reader.nextLine());
return length;
}
public static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> randomList = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
return randomList;
}
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
}
}
}
return randomList;
}
}
Create a swap method to make it clearer (both for us and yourself):
private void swap(List<Integer> values, x, y) {
int temp = values.get(x);
values.set(x, values.get(y));
values.set(y, temp);
}
Other suggestions:
name your class BubbleSort rather than bubbleSort. Convention for class names is to start with uppercase.
don't pass the length as a second argument to your sort method. It's redundant and might become incorrect if someone sneakily adds an item to the list.
rename randomList to values or numbers or randomNumbers. No need to repeat the type in the variable name.
replace sorted == false with !sorted. This is the common and more readable notation
getLength and createList can be private
Consider using the main method to create an instance of your sorting class, with the list as a field. In that way the methods won't have to pass the list along to each other. Your code will be more readable and more object-oriented.
EDIT: you could take the separation even further and move all the static methods into a separate class called 'Application' or 'Main'. See edited code below:
Here's roughly how the code would look following my suggestions:
public class BubbleSort {
// a field
private List<Integer> numbers;
public BubbleSort(List<Integer> numbers) {
this.numbers = numbers;
}
public static List<Integer> sort() {
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int x = 0; x < length - 1; x++) {
if(numbers.get(x) > numbers.get(x + 1)) {
sorted = false;
swap(x, x + 1);
}
}
}
return numbers;
}
private void swap(x, y) {
int temp = numbers.get(x);
numbers.set(x, numbers.get(y));
numbers.set(y, temp);
}
}
The Application class. It's purpose is to get the length from the user, create test data and set up and call a BubbleSort instance:
public class Application {
public static void main(String[] args) {
int length = getLength();
List<Integer> unsorted = createList(length);
System.out.println("The list before sorting:\n" + unsorted);
// creating an instance of the BubbleSort class
BubbleSort bubbleSort = new BubbleSort(unsorted );
List<Integer> sorted = bubbleSort.sort();
System.out.println("The list after sorting:\n" + sorted);
}
private static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
return Integer.parseInt(reader.nextLine());
}
private static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> numbers = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
numbers.add(randomnumber);
}
return numbers;
}
BTW Good job splitting off those methods getLength and createList. That's the right idea.
you made a couple of mistakes
this:
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
should be:
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
full method:
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
}
}
}
return randomList;
}
Write a method to return the Toy that occurs in the list most frequent and another method to sort the toys by count.
This is my code
import java.util.ArrayList;
public class ToyStore {
private ArrayList<Toy> toyList;
public ToyStore() {
}
public void loadToys(String toys) {
toyList = new ArrayList<Toy>();
for (String item : toys.split(" ")) {
Toy t = getThatToy(item);
if (t == null) {
toyList.add(new Toy(item));
} else {
t.setCount(t.getCount() + 1);
}
}
}
public Toy getThatToy(String nm) {
for (Toy item : toyList) {
if (item.getName().equals(nm)) {
return item;
}
}
return null;
}
public String getMostFrequentToy() {
int position = 0;
int maximum = Integer.MIN_VALUE;
for (int i = toyList.size() - 1; i >= 0; i--) {
if (toyList.get(i).getCount() > maximum)
maximum = toyList.get(i).getCount();
position = i;
}
return toyList.get(position).getName();
}
public void sortToysByCount() {
ArrayList<Toy> t = new ArrayList<Toy>();
int count = 0;
int size = toyList.size();
for (int i = size; i > 0; i--) {
t.add(new Toy(getMostFrequentToy()));
t.get(count).setCount(getThatToy(getMostFrequentToy()).getCount());
toyList.remove(getThatToy(getMostFrequentToy()));
count++;
}
toyList = t;
}
public String toString() {
return toyList + "" + "\n" + "max == " + getMostFrequentToy();
}
}
Here is the method I care about
public void sortToysByCount() {
ArrayList<Toy> t = new ArrayList<Toy>();
int count = 0;
int size = toyList.size();
for (int i = size; i > 0; i--) {
t.add(new Toy(getMostFrequentToy()));
t.get(count).setCount(getThatToy(getMostFrequentToy()).getCount());
toyList.remove(getThatToy(getMostFrequentToy()));
count++;
}
toyList = t;
}
Here is my output
[sorry 4, bat 1, train 2, teddy 2, ball 2]
Here is what I want
[sorry 4, train 2, teddy 2, ball 2, bat 1];
What is wrong in my code? How do I do it?
The problem is in your getMostFrequentToy() method:
Replace
if (toyList.get(i).getCount() > maximum)
maximum = toyList.get(i).getCount();
position = i;
with
if (toyList.get(i).getCount() > maximum) {
maximum = toyList.get(i).getCount();
position = i;
}
because you want to get the position that corresponds to that maximum.
You have some in-efficiencies in your code. Every single time you call getMostFrequentToy(), you are iterating over the whole list, which may be fine as you are constantly removing objects, but you really don't need to make new Toy objects for those that already exist in the list.
So, this is "better", but still not sure you need to getThatToy when you should already know which one is the most frequent.
String frequent;
for (int i = size; i > 0; i--) {
frequent = getMostFrequentToy();
t.add(new Toy(frequent));
t.get(count).setCount(getThatToy(frequent).getCount());
toyList.remove(getThatToy(frequent));
count++;
}
Anyways, I think the instructions asked you to return the Toy object, not its name.
It's quite simple, just keep track of the max count.
public Toy getMostFrequentToy() {
Toy mostFrequent = null;
int maximum = Integer.MIN_VALUE;
for (Toy t : toyList) {
if (t.getCount() > maximum)
mostFrequent = t;
}
return t;
}
Now, the above code can become
public void sortToysByCount() {
ArrayList<Toy> t = new ArrayList<Toy>();
// int count = 0;
int size = toyList.size();
Toy frequent;
for (int i = size; i > 0; i--) {
frequent = getMostFrequentToy();
t.add(frequent);
// t.get(count).setCount(frequent.getCount()); // Not sure about this
toyList.remove(frequent);
// count++;
}
toyList.clear();
toyList.addAll(t);
}
Realistically, though, when you want to sort, you really should see how to create a Comparator for your Toy objects.
How can I alter the below method to work with an ArrayList?
I was thinking something like this:
public static boolean sortArrayList(ArrayList<Integer> list) {
return false;
}
but i'm not sure how to complete it.
Here is the method that I am trying to convert from working with an Array to instead work with an ArrayList:
public static boolean sortArrayList(final int[] data) {
for(int i = 1; i < data.length; i++) {
if(data[i-1] > data[i]) {
return false;
}
}
return true;
}
public static boolean sortArrayList(final ArrayList <Integer> data) {
for (int i = 1; i < data.size(); i++) {
if (data.get(i - 1) > data.get(i)) {
return false;
}
}
return true;
}
I have a few problems with the accepted answer, as given by #Sanj: (A) it doesn't handle nulls within the list, (B) it is unnecessarily specialized to ArrayList<Integer> when it could easily be merely Iterable<Integer>, and (C) the method name is misleading.
NOTE: For (A), it's quite possible that getting an NPE is appropriate - the OP didn't say. For the demo code, I assume that nulls are ignorable. Other interpretations a also fair, e.g. null is always a "least" value (requiring different coding, LAAEFTR). Regardless, the behaviour should be JavaDoc'ed - which I didn't do in my demo #8>P
NOTE: For (B), keeping the specialized version might improve runtime performance, since the method "knows" that the backing data is in an array and the compiler might extract some runtime efficiency over the version using an Iterable but such claim seem dubious to me and, in any event, I would want to see benchmark results to support such. ALSO Even the version I demo could be further abstracted using a generic element type (vs limited to Integer). Such a method might have definition like:
public static <T extends Comparable<T>> boolean isAscendingOrder(final Iterable<T> sequence)
NOTE: For (C), I follow #Valentine's method naming advice (almost). I like the idea so much, I took it one step further to explicitly call out the directionality of the checked-for-sortedness.
Below is a demonstration class that shows good behaviour for a isAscendingOrder which address all those issues, followed by similar behaviour by #Sanj's solution (until the NPE). When I run it, I get console output:
true, true, true, true, false, true
------------------------------------
true, true, true, true, false,
Exception in thread "main" java.lang.NullPointerException
at SortCheck.sortArrayList(SortCheck.java:35)
at SortCheck.main(SortCheck.java:78)
.
import java.util.ArrayList;
public class SortCheck
{
public static boolean isAscendingOrder(final Iterable<Integer> sequence)
{
Integer prev = null;
for (final Integer scan : sequence)
{
if (prev == null)
{
prev = scan;
}
else
{
if (scan != null)
{
if (prev.compareTo(scan) > 0)
{
return false;
}
prev = scan;
}
}
}
return true;
}
public static boolean sortArrayList(final ArrayList<Integer> data)
{
for (int i = 1; i < data.size(); i++)
{
if (data.get(i - 1) > data.get(i))
{
return false;
}
}
return true;
}
private static ArrayList<Integer> createArrayList(final Integer... vals)
{
final ArrayList<Integer> rval = new ArrayList<>();
for(final Integer x : vals)
{
rval.add(x);
}
return rval;
}
public static void main(final String[] args)
{
final ArrayList<Integer> listEmpty = createArrayList();
final ArrayList<Integer> listSingleton = createArrayList(2);
final ArrayList<Integer> listAscending = createArrayList(2, 5, 8, 10 );
final ArrayList<Integer> listPlatuea = createArrayList(2, 5, 5, 10 );
final ArrayList<Integer> listMixedUp = createArrayList(2, 5, 3, 10 );
final ArrayList<Integer> listWithNull = createArrayList(2, 5, 8, null);
System.out.print(isAscendingOrder(listEmpty ) + ", ");
System.out.print(isAscendingOrder(listSingleton) + ", ");
System.out.print(isAscendingOrder(listAscending) + ", ");
System.out.print(isAscendingOrder(listPlatuea ) + ", ");
System.out.print(isAscendingOrder(listMixedUp ) + ", ");
System.out.print(isAscendingOrder(listWithNull ) + "\n");
System.out.println("------------------------------------");
System.out.print(sortArrayList(listEmpty ) + ", ");
System.out.print(sortArrayList(listSingleton) + ", ");
System.out.print(sortArrayList(listAscending) + ", ");
System.out.print(sortArrayList(listPlatuea ) + ", ");
System.out.print(sortArrayList(listMixedUp ) + ", ");
System.out.print(sortArrayList(listWithNull ) + "\n");
}
}
Try below function, it takes integer array and converts it into a ArrayList and then computes the result :
public static boolean sortArrayList(final int[] data) {
List<Integer> aList = new ArrayList<Integer>();
for (int index = 0; index < data.length; index++)
aList.add(data[index]);
for (int i = 1; i < aList.size(); i++) {
if (aList.get(i - 1) > aList.get(i)) {
return false;
}
}
return true;
}
I'm new to programming, I'm not sure where I'm going wrong with this one.
Here is my main method:
import java.util.*;
public class DisplayFactors
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a integer: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
FactorGenerator factor = new FactorGenerator(input);
System.out.print(factor.getNextFactor());
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
}
}
Here is my class:
public class FactorGenerator {
private int num;
private int nextFactor;
public FactorGenerator(int n)
{
num = nextFactor = n;
}
public int getNextFactor()
{
int i = nextFactor - 1 ;
while ((num % i) != 0)
{
i--;
}
nextFactor = i;
return i;
}
public boolean hasMoreFactors()
{
if (nextFactor == 1)
{
return false;
}
else
{
return true;
}
}
}
Currently if I enter 15 as the integer I only get one factor back, which is 5, but I need it to display all the factors: 15, 5, 3 and 1. Where am I going wrong?
When you use
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
you say that while there aren't any more factors, print them on the screen, but you need
to print the factors as long as they exist in the list.
So in Java you will have:
while (factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
must be
while (factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}