How do you use a separate class to determine a result? - java

my issue is in my "NumberAnalyzer.java" class, I'm supposed to be able to use the "Number.java" class to determine if a number from the ArrayList is odd (as well as even and perfect later on) but since the "isOdd()" method in "Number.java" doesn't read in an int or other variable itself, I can't find a way to test each number to make "oddCount" in the "countOdds" method of "NumberAnalyzer.java" increase to produce the number of odd numbers in the string from the runner class.
NumberAnalyzer.java
import java.util.ArrayList;
import java.util.Scanner;
import com.sun.xml.internal.ws.api.pipe.NextAction;
import static java.lang.System.*;
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer()
{
}
public NumberAnalyzer(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
System.out.println(list);
}
public void setList(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
}
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
public int countEvens()
{
int evenCount=0;
return evenCount;
}
public int countPerfects()
{
int perfectCount=0;
return perfectCount;
}
public String toString( )
{
return "";
}
}
Number.java
public class Number
{
private Integer number;
public Number()
{
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return number;
}
public boolean isOdd()
{
if(number%2==0){
return false;
}
return true;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++){
if(number%i==0){
total+= i;
}
}
return (number==total);
}
public String toString( )
{
String output = getNumber() + "\n" + getNumber()+ "isOdd == " + isOdd() + "\n" + getNumber()+ "isPerfect==" + isPerfect()+ "\n\n";
return output;
}
}
runner class
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;
public class Lab16b
{
public static void main( String args[] )
{
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
//add more test cases
}
}

When you call
test.countOdds());
control goes to NumberAnalyzer.java
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
And here you are calling Number.isOdd() method by Class name as a static way but i do not think you can do this way because isOdd() is not static.
It is compile time error
Solution:
Iterate your list and send value one by one from the list to isOdd(int val) method.
Try to make isOdd() method static which accept one numeric parameter and will return true or false.
increase your counter based on return type as you do.

Related

why can't I use parent method? (ArrayList)

everybody
I have some questions~
In the main method , int size = s.getSize()
but when I change to int size = s.size()
Why compiler show NoSuchMethodError?
Mystack is a ArrayList's child class
Why can't I use size() method?
package ch11;
import java.util.ArrayList;
import java.util.Scanner;
public class ch11_10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MyStack s = getStack(input);
int size = s.getSize();//換成s.size()
for (int i = 0; i < size; i++) {
System.out.println(s.pop());
}
}
public static MyStack getStack(Scanner input) {
System.out.print("Enter five strings: ");
MyStack s = new MyStack();
for (int i = 0; i < 5; i++) {
s.push(input.next());
}
return s;
}
}
class MyStack extends ArrayList {
public int getSize() {
return size();
}
public Object peek() {
return get(size() - 1);
}
public Object pop() {
Object o = get(size() - 1);
remove(size() - 1);
return o;
}
public void push(Object o) {
add(o);
}
#Override
public String toString() {
return "stack: " + toString();
}
}

Sorting an ArrayList of Names using a Comparator that sorts by length

I'm having trouble with my code. I tried using Strings for the arraylist but it doesn't work. When I put the class name in the arraylist, it only prints a different value. I made a class to get the length because doing it in the comparator didn't work; it just gives me a cannot find symbol error.
import java.util.*;
import java.io.*;
class StringLengthComparator implements Comparator<Name>
{
public int compare(Name n1, Name n2)
{
return n1.getLength()-n2.getLength();
}
}
public class Name implements Comparable<Name>
{
public static String name;
public Name(String n)
{
this.name = n;
}
public int compareTo(Name that)
{
return this.name.compareTo(that.name);
}
public String getName()
{
return this.name;
}
public int getLength()
{
return this.name.length();
}
public static void main(String[] args) throws Exception
{
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
//String n = keyIn.readLine();
for(int i=0;i<5;i++)
{
String n = keyIn.readLine();
N.add(new Name(n));
}
System.out.print("\n");
Collections.sort(N);
for(int i=0;i<N.size();i++)
{
System.out.println(N.get(i));
}
System.out.print("\n");
Collections.sort(N, new StringLengthComparator());
for(int i=0;i<N.size();i++)
{
System.out.println(N.get(i));
}
}
}
Error #1 for ArrayList<\String> N = new ArrayList<\String>
Error #2 for ArrayList <\Name> N = new ArrayList<>(5)
If you want to sort by length and alphabetically by choice you need 2 comperators and choose each time which one to use, by N.sort(new X), where X is the name of the comperator class you want.
You don't need Collections.sort():
class StringLengthComparator implements Comparator<Name> {
public int compare(Name n1, Name n2) {
return n1.getLength()-n2.getLength();
}
}
class StringCommonComparator implements Comparator<Name> {
public int compare(Name n1, Name n2) {
return n1.getName().compareTo(n2.getName());
}
}
public class Name {
private String name;
public Name(String n) {
this.name = n;
}
public String getName() {
return this.name;
}
public int getLength() {
return this.name.length();
}
public static void main(String[] args) throws Exception {
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
String n = keyIn.readLine();
N.add(new Name(n));
for(int i=0; i<5; i++) {
String name = keyIn.readLine();
N.add(new Name(name));
}
System.out.println();
System.out.println("Compare by Length");
N.sort(new StringLengthComparator());
for(int i=0;i<N.size();i++) {
System.out.println(N.get(i).name);
}
System.out.println();
System.out.println("Compare by String");
N.sort(new StringCommonComparator());
for(int i=0;i<N.size();i++) {
System.out.println(N.get(i).name);
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class StringLengthComparator implements Comparator<Name> {
#Override
public int compare(Name n1, Name n2) {
return n1.getLength() - n2.getLength();
}
}
public class Name implements Comparable<Name> {
public static String name;
public Name(String n) {
this.name = n;
}
#Override
public int compareTo(Name that) {
return this.name.compareTo(that.name);
}
public String getName() {
return this.name;
}
public int getLength() {
return this.name.length();
}
public static void main(String[] args) throws Exception {
ArrayList<Name> N = new ArrayList<>(5);
BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter Name: ");
for (int i = 0; i < 5; i++) {
String n = keyIn.readLine();
N.add(new Name(n));
}
System.out.print("\n");
Collections.sort(N);
for (Name name : N) {
System.out.println(name.getName());
}
System.out.print("\n");
Collections.sort(N, new StringLengthComparator());
for (int i = 0; i < N.size(); i++) {
System.out.println(N.get(i));
}
}
}

Issue recalling method. unsure of where im going wrong

Below is my code and I have notes beside where my errors are showing. Im unsure where I am going wrong when recalling my method or if that is even the issue.
import java.util.Scanner;
public class HurlerUse
{
static Hurler[] hurlerArray;
// find lowest score (static method)
public static int findLow(Hurler[] hurlerArray)
{
for(int i = 0; i < hurlerArray.length; i++)
{
int lowest = 0;
int index = 0;
for(int j=0; j<hurlerArray.length; j++)
{
int current = hurlerArray[i].totalPoints();// issue with my method 'totalPoints'
if(current < lowest)
{
lowest = current;
index = i;
}
}
return index;
}
}
//main code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Hurler[] hurlerArray = new Hurler[5];
for (int i = 0; i <4; i++)
{
hurlerArray[i] = new Hurler();
System.out.println ("Enter Hurler Name:");
hurlerArray[i].setName(sc.nextLine());
hurlerArray[i].setGoalsScored(sc.nextInt());
System.out.println("Enter the hurler's goals scored");
hurlerArray[i].setPointsScored(sc.nextInt());
System.out.println("Enter the hurler's points scored");
}
for(int i=0;i< hurlerArray.length; i++)
{
hurlerArray[i] = new Hurler(MyName, MyGoalsScored, MyPointsScored);// issue with all 3 objects in the brackets but im unsure of how to fix them
}
System.out.println("The lowest scoring hurler was " + hurlerArray[findLow(hurlerArray)].getName());// error with my code here I think it is in the method
}
}//end of class
I know the nyName, myGoalsScored, myPointsScored is incorrect but can anyone explain why?
This is the class page that accompanies it
public class Hurler
{
private String name;
private int goalsScored;
private int pointsScored;
public Hurler() //constructor default
{
name ="";
goalsScored = 0;
pointsScored = 0;
}
public Hurler(String myName, int myGoalsScored, int myPointsScored) // specific constructor
{
name = myName;
goalsScored = myGoalsScored;
pointsScored = myPointsScored;
}
//get and set name
public String getMyName()
{
return name;
}
public void setName(String myName)
{
name = myName;
}
//get and set goals scored
public int getGoalsScored()
{
return goalsScored;
}
public void setGoalsScored(int myGoalsScored)
{
goalsScored = myGoalsScored;
}
// get and set points scored
public int getPointsScored()
{
return pointsScored;
}
public void setPointsScored(int myPointsScored)
{
pointsScored = myPointsScored;
}
public int totalPoints(int myGoalsScored, int myPointsScored)
{
int oneGoal = 3;
int onePoint = 1;
int totalPoints = ((goalsScored * oneGoal) + (pointsScored * onePoint));
{
return totalPoints;
}
}
}//end of class
You call totalPoints() without parameters while method totalPoints(int, int) in Hurler class expects two int parameters.
Objects MyName, MyGoalsScored, MyPointsScored are not declared at all.
You call getName() method, while in Hurler class you do not have one. There is method getMyName(), maybe you want to call that one.

ArrayList and Passing values

I am new to programming and we just learned ArrayLists in my class today and I have an easy question for you guys, I just can't seem to find it in the notes on what to set the passing value equal to. The point of this practice program is to take in a Number Object (that class has already been created) and those Numbers in the ArrayList are supposed to be counted as odds, evens, and perfect numbers. Here is the first couple of lines of the program which is all you should need.
import java.util.ArrayList;
import static java.lang.System.*;
public class NumberAnalyzer {
private ArrayList<Number> list;
public NumberAnalyzer() {
list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
}
public void setList(String numbers) {
}
What am I supposed to set (String numbers) to in both NumberAnalyzer() and setList()? Thanks in advance for answering a noob question!
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
This is the Lab16b Class that will run the program. ^^
public class Number
{
private Integer number;
public Number()
{
number = 0;
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return 0;
}
public boolean isOdd()
{
return number % 2 != 0;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++)
{
if(number % i == 0)
{
total = total + i;
}
}
if(total == number)
{
return true;
}
else
{
return false;
}
}
public String toString( )
{
return "";
}
}
Here is the Number class. ^^
Based on the information you provided, this is what I feel NumberAnalyzer should look like. The setList function is presently being used to take a String and add the numbers in it to a new list.
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer() {
this.list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
setList(numbers);
}
public void setList(String numbers) {
String[] nums = numbers.split(" ");
this.list = new ArrayList<Number>();
for(String num: nums)
list.add(new Number(Integer.parseInt(num)));
}
}
Analyze to learn something.
public static void main(String[] args) {
String temp = "5 12 9 6 1 4 8 6";
NumberAnalyzer analyzer = new NumberAnalyzer(temp);
//foreach without lambda expressions
System.out.println("without Lambda");
for (NeverNumber i : analyzer.getList()) {
i.print();
}
//with the use of lambda expressions, which was introduced in Java 8
System.out.println("\nwith Lambda");
analyzer.getList().stream().forEach((noNumber) -> noNumber.print());
NeverNumber number = new NeverNumber(31);
number.print();
number.setNumber(1234);
number.print();
}
public class NumberAnalyzer {
private List<NeverNumber> list; //List is interface for ArrayList
public NumberAnalyzer(String numbers) {
String[] numb=numbers.split(" ");
this.list=new ArrayList<>();
for (String i : numb) {
list.add(new NeverNumber(Integer.parseInt(i)));
}
}
public void setList(List<NeverNumber> numbers) {
List<NeverNumber> copy=new ArrayList<>();
numbers.stream().forEach((i) -> {
copy.add(i.copy());
});
this.list=copy;
}
public List<NeverNumber> getList() {
List<NeverNumber> copy=new ArrayList<>();
this.list.stream().forEach((i) -> {
copy.add(i.copy());
});
return copy;
}
public NeverNumber getNumber(int index) {
return list.get(index).copy();
}
}
public class NeverNumber { //We do not use the names used in the standard library.
//In the library there is a class Number.
private int number; // If you can use simple types int instead of Integer.
public NeverNumber() {
number = 0;
}
public NeverNumber(int num) {
number = num;
}
private NeverNumber(NeverNumber nn) {
this.number=nn.number;
}
public void setNumber(int num) {
number = num;
}
public int getNumber() {
return this.number;
}
public boolean isOdd() {
return number % 2 != 0;
}
public boolean isPerfect() {
long end = Math.round(Math.sqrt(number)); //Method Math.sqrt(Number) returns a double, a method Math.round(double) returns long.
for (int i = 2; i < end + 1; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public NeverNumber copy(){
return new NeverNumber(this);
}
public void print() {
System.out.println("for: " + this.toString() + " isPer: " + this.isPerfect() + " isOdd: " + this.isOdd() + "\n");
}
#Override //Every class in Java inherits from the Object class in which it is toString(),
//so we have to override our implementation.
public String toString() {
return this.number + ""; //The object of any class + "" creates a new object of the String class,
//that is for complex types, calls the toString () method implemented in this class,
//override the toString () from the Object class. If the runs, we miss class toString()
//calls from the Object class.
}
}

Compare an Arraylist and give output

I have two ArrayLists. How can I compare the elements in the arraylists and create a new list with the results?
I need to iterate through the list to actually get its results and compare. How can I do it in Java?
Any help is appreciated.
Thanks
You can compare by implementing Comparator class.You can understand by below example in which Two Time class is getting compared.
class Time
{
int hours,minutes,seconds;
public Time(int hours,int minutes,int seconds)
{
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
public int getHours()
{
return this.hours;
}
public int getMinutes()
{
return this.minutes;
}
public int getSeconds()
{
return this.seconds;
}
public String toString()
{
return String.format("%d:%02d:%02d %s",((hours==0||hours==12)? 12:hours%12),this.minutes,this.seconds,((hours>=12)?"PM":"AM"));
}
}
class TimeComparator implements Comparator<Time>
{
public int compare(Time t1,Time t2)
{
int hours=t1.getHours()-t2.getHours();
int minutes=t1.getMinutes()-t2.getMinutes();
int seconds=t1.getSeconds()-t2.getSeconds();
if(hours>0)
return 1;
else if(hours<0)
return -1;
if(minutes>0)
return 1;
else if(minutes<0)
return -1;
if(seconds>0)
return 1;
else if(seconds<0)
return -1;
return 0;
}
public boolean equals(Object obj)
{
return true;
}
}
After this you can use Collections class to use any method like sorting or search.
I hope that the following chunck of code will get you started.
import java.util.ArrayList;
class Compare {
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("Hello");
a.add("Goodbye");
ArrayList<String> b = new ArrayList<String>();
b.add("Hello");
b.add("Bye");
if (a.size() != b.size()) {
System.out.println("Arrays must have the same size");
return;
}
ArrayList<Boolean> results = new ArrayList<Boolean>();
for(int i = 0; i < a.size(); ++i)
results.add(a.get(i).equals(b.get(i)));
for(int i = 0; i < a.size(); ++i)
System.out.println(results.get(i));
}
}

Categories

Resources