I've tried fixing this I just cant seem to find a solution to this problem. The code is meant to print the prime numbers in a range, but it just returns the error
Static Error: Undefined name 'PrimeNumbers
Would anyone please be able to help me ?
This is my code :
import java.util.*;
public class PrimeNumbers {
private List<Integer> listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumbers primeNumberList = new PrimeNumbers(50);
primeNumberList.print(); //use our new print method
}
public PrimeNumbers (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
public void print() {
int i = 1;
for (Integer nextPrime:listOfPrimeNumbers) {
System.out.println("the " + i + "th prime is: " + nextPrime);
i++;
}
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
public List getPrimes() {
return listOfPrimeNumbers;
} //a simple getter isnt a bad idea either, even though we arent using it yet
}
Assuming, you have you code organized like this
./project
PrimeNumbers.java
PrimeNumbers.class
then you cd to ./project and type
java PrimeNumbers
Note - this only works because you didn't declare a package (iaw: you class is in the default package). Usually you have a package declaration and then it looks a bit different.
Bonus
The getter is a good idea, but you should think twice before returning a collection, because this way, you grant the receiver full access to your (internal?) datastructure and he can alter the values of that collection. And you shouldn't declare it with the raw type. Here's a better way to implement it:
public List<Integer> getPrimes() {
return Collections.unmodifiableList(listOfPrimeNumbers);
}
Now the receiver knows that he get's a list of Integer values and can't modify the result.
Related
Hello I have implemented this basic program which should sort out the strings that are inserted however it somehow is failing to insert the strings .
For example if I implement :
TestSort t = new TestSort();
t.i("abc");
t.i("aab");
Can anybody see the error and help me fix this error please ?
Thank you
Here is the code :
public class TestSort {
private int length;
String[] data;
public TestSort() {
length = 0;
}
public void i(String value) {
data[length] = value;
setSorted(data);
length++;
}
public void setSorted(String data[]) {
for(int i = data.length-1; i >= 0; i--) {
for(int j = 0; j < i; j++) {
if(data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
for(int i = 0; i < data.length; i++) {
System.out.print(data[i] +" ");
}
}
}
You don't initialize the array data. So it is set null, and accesses with data[i] will get you an NullPointerException. Even if you initialize this field, it will not work, as Arrays in Java have a fixed size, you have to reallocate the Array, if you insert a new value. You should try a List-implementation instead.
So the code should initialize in the constructor:
data = new ArrayList<String>();
and insertion would change to
data.add(value);
you can change your constructor code as (String array max length can be taken as input parameter):
public testsort()
{
data = new String[10];
length = 0;
}
But if you are not sure with the size of array you can use ArrayList.
You are getting exception because you are comparing with data[j+1] that is still null.
first time when you call
t.i("abc");
there is only one reference in data array that is pointing to String literal "abc" and that is at index 0. index 1 is still referring to null.
first String is already sorted so no need to sort that. if you are having more than one string then you should call setSorted() method.
to solve this you can put your condition in loop as:
if((data[j] != null && data[j+1] != null) &&(data[j].compareTo(data[j + 1]) > -1))
A working example but still: use a List and life is much easier :-)
public class Test {
private int length;
private String[] data;
public Test(int arrayLength) {
// INITIALIZE YOU ARRAY --> No NULLPOINTEREXCEPTION!
data = new String[arrayLength];
length = 0;
}
public void i(String value) {
data[length] = value;
length++;
}
public void setSorted() {
for (int j = 0; j < data.length - 1; j++) {
if (data[j].compareTo(data[j + 1]) > -1) {
String temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (String s : data) {
System.out.println(s);
}
}
public static void main(String[] args) {
Test t = new Test(5);
t.i("bbb");
t.i("aaa");
t.i("ccc");
t.i("zzz");
t.i("ddd");
// USE SETSORTED HERE --> else you fill your array with the same elements
t.setSorted();
}
}
The variable 'data' is null since it is nowhere initialized hence giving null pointer exception. Since 'data' is an array and as per the rule whenever an array is defined, it has to be of defined length. for e.g if we consider your case. 'data' can be initialized as :-
String[] data = new String[any numerical value]
the numerical value will be its length i.e. the maximum number of elements it can hold.
Secondly, as per your program statement :-
data[length] = value;
is trying to assign value at data's [length] index which is completely wrong since you haven't defined the length therefore how could you guess the index's value. Therefore your this approaoch is logically wrong.
For such situation i.e. whenever we're unaware about the length of the array, use of ArrayList is suggested. Therefore your program can be re-written by two ways:-
1) Either define the length of the array
String[] data = new String[n];
where n ranges from at least 1 to any positive integer.
2) By using ArrayList
public class Main {
List<String> data;
public Main(){
data = new ArrayList<String>();
}
public static void main(String... q){
Main m = new Main();
m.insertData("abc");
m.insertData("zxy");
m.insertData("aab");
m.insertData("aaa");
m.showData();
}
public void insertData(String str){
data.add(str);
Collections.sort(data);
}
public void showData(){
if(data!=null && !data.isEmpty()){
for(String s : data){
System.out.println(s);
}
}
}
}
output:-
aaa
aab
abc
zxy
Hope this helps.
as Mnementh suggested, the reason for NPE is that you have created the field data of type String[] but you never initialized it.
Other answers have provided every reason on why your code throwing ugly errors; I have just improved your code by replacing your String[] with List<String> so you don't have to worry about the size of your array anymore.
Sorting is also simplified now using Collections.sort().
have a look,
class test1 {
public static void main(String[] args) {
Test sorting = new Test();
sorting.input("abc");
sorting.input("cba");
sorting.input("aab");
sorting.setSorted();
}
}
class Test {
private List<String> data = new ArrayList<String>();
public void input(String value) {data.add(value);}
public void setSorted() {
Collections.sort(data);
for (String current : data) {
System.out.println(current);
}
}
}
if you are using Java 8, then you can use Arrays.parallerSort(), it performs sorting the same way as Collection.sort but with a parallel implementation.
Current sorting implementations provided by the Java Collections Framework > (Collections.sort and Arrays.sort) all perform the
sorting operation sequentially in the calling thread. This enhancement
will offer the same set of sorting operations currently provided by
the Arrays class, but with a parallel implementation that utilizes the
Fork/Join framework. These new API's are still synchronous with regard
to the calling thread as it will not proceed past the sorting
operation until the parallel sort is complete.
to implement it, replace Collections.sort with Arrays.parallelSort in the above code,
Replace,
Collections.sort(data);
with,
Arrays.parallelSort(data.toArray(new String[data.size()]));
I have the following code for displaying the sum of two consecutive element of ArrayList until the element left is one.for example:-
if i entered
1 2 3 4 5
output
3 7 5 //adding the two consecutive last one is as it is
10 5//doing the same thing
15
code
import java.util.*;
import java.lang.Integer;
class Substan{
ArrayList <Integer> list = new ArrayList <Integer> ();
ArrayList <Integer> newList = new ArrayList <Integer> ();// this will be the list containing the next sequence.
int index=0;
int sum=0;
Substan(){
Scanner read = new Scanner(System.in);
String choice;
System.out.println("Enter the elements of the array");
do{
int element = read.nextInt();
list.add(element);
System.out.println("More?");
choice = read.next();
}while(choice.equals("y") || choice.equals("Y"));
}
/* precondition- we have the raw list that user has enterd.
postcondition - we have displayed all the sublists,by adding two consecutives numbers and the last one is having one element.
*/
void sublist(){
while(noofElementsIsNotOneInList()){
index =0;
while(newListIsNotComplete()){
if(nextElementIsThere()){
sum = addTheConsecutive();
}
else{
sum = getLastNumber();
}
storeSumInNewList();
}
displayTheNewList();
System.out.println("");
updateTheLists();
}
displayTheNewList(); //as we have danger of Off By One Bug (OBOB)
System.out.println("");
}
private boolean noofElementsIsNotOneInList(){
boolean isnotone = true;
int size = list.size();
if ( size == 1){
isnotone = false;
}
return isnotone;
}
private boolean newListIsNotComplete(){
boolean isNotComplete = true;
int listSize = list.size();
int newListSize = newList.size();
if (listSizeIsEven()){
if ( newListSize == listSize/2){
isNotComplete = false;
}
}
else{
if( newListSize == (listSize/2) +1){
isNotComplete = false;
}
}
return isNotComplete;
}
private boolean listSizeIsEven(){
if ( list.size()%2 == 0 ){
return true;
}
else{
return false;
}
}
/*
we are at some index.
returns true if we have an element at (index+1) index.
*/
private boolean nextElementIsThere(){
if ( list.size() == index+1 ){
return false;
}
else{
return true;
}
}
/* precondition-we are at index i
postcondition - we will be at index i+2 and we return sum of elements at index i and i+1.
*/
private int addTheConsecutive(){
int sum = list.get(index)+list.get(index+1);
index += 2;
return sum;
}
/* we are at last element and we have to return that element.
*/
private int getLastNumber(){
return list.get(index);
}
private void storeSumInNewList(){
newList.add(sum);
}
private void displayTheNewList(){
int size = newList.size();
for ( int i=0;i<size;i++){
System.out.print(newList.get(i)+" ");
}
}
/*precondition - we have processed all the elements in the list and added the result in newList.
postcondition - Now my list will be the newList,as we are processing in terms of list and newList reference will have a new object.
*/
private void updateTheLists(){
list = newList;
newList = new ArrayList <Integer>();// changing the newList
}
public static void main(String[] args) {
Substan s = new Substan();
s.sublist();
}
}
So i have done a lot of refinement of my code but having a problem of sharing the local variables with the other methods.for example i have used index instance for storing the index and initially i thought that i will put this as not an instance but a local variable in method sublist() but as it cannot be viewed from other methods which needed to use the index like addTheConsecutive().So considering that i put the index at class level.So is it wright approach that put the variables that are shared at class level rather than looking at only the state of the object initially before coding and stick to that and never change it?
Consider this:
An object can communicate with other(s) only by sharing its attributes. So, if you need an object to read the state of another, the only way it can be done is by giving it "permission" to read the other object attributes.
You have two ways to do that:
Declaring the object attributes public, or
Creating getXXX() methods (makes sense for private attributes)
I personally prefer option two, because the getXXX() method returns the value ("state") of a particular attribute without the risk of being modified. Of course, if you need to modify a private attribute, you should also write a setXXX() method.
Example:
public class MyClass {
private int foo;
private String bar;
/*
* Code
*/
public int getFoo() {
return foo;
}
public String getBar() {
return bar;
}
public void setFoo(int foo) {
this.foo = foo;
}
public void setBar(String bar) {
this.bar = bar;
}
/*
* More code
*/
}
This way all the object attributes are encapsulated, and:
they cannot be read by any other object, unless you specifically call the appropriate getXXX() function, and
cannot be altered by other objects, unless you specifically call the appropriate setXXX() function.
Compare it with the non-abstracted version.
for (int index = 0; index < list.size(); index += 2) {
int sum = list.get(index);
if (index + 1 < list.size() {
sum += list.get(index + 1);
}
newList.add(sum);
}
Now, top-down refining the algorithm using names is a sound methodology, which helps in further creative programming.
As can seen, when abstracting the above again:
while (stillNumbersToProcess()) {
int sum = sumUpto2Numbers();
storeSumInNewList(sum);
}
One may keep many variables like sum as local variables, simplifying state.
One kind of helpful abstraction is the usage of conditions, in a more immediate form:
private boolean listSizeIsEven() {
return list.size() % 2 == 0;
}
private boolean nextElementIsThere() {
return index + 1 < list.size();
}
There's no point in declaring index at Class level since you dont want it to be a member or an instance of that class. Instead make it local to the method and pass it to other methods as argument where you want to access it.
I think you are asking the wrong question.
Your class variables make very little sense, as do many of the methods. This is mostly because:
Your class is doing too much
Your algorithm is a little odd
The class variables that you do have make much more sense passed as method parameters. Some methods need to see them, and some don't.
Your class is also a little odd, in that calling subList twice on the same class will not produce the same answer.
The code is littered with methods I don't quite see the point in, such as:
private boolean noofElementsIsNotOneInList(){
boolean isnotone = true;
int size = list.size();
if ( size == 1){
isnotone = false;
}
return isnotone;
}
Shouldn't this be:
private boolean noofElementsIsNotOneInList(){
return list.size() == 1;
}
And it makes no sense for it to use some arbitrary List, pass one in so that you know which List you are checking:
private boolean noofElementsIsNotOneInList(final Collection<?> toCheck){
return toCheck.size() == 1;
}
The same logic can be applied to almost all of your methods.
This will remove the instance variables and make your code much more readable.
TL;DR: Using lots of short appropriately named methods: good. Having those methods do things that one wouldn't expect: bad. Having lots of redundant code that makes things very hard to read: bad.
In fact, just to prove a point, the whole class (apart from the logic to read from stdin, which shouldn't be there anyway) can transformed into one short, recursive, method that requires no instance variables at all:
public static int sumPairs(final List<Integer> list) {
if (list.size() == 1)
return list.get(0);
final List<Integer> compacted = new LinkedList<>();
final Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
final int first = iter.next();
if (iter.hasNext()) compacted.add(first + iter.next());
else compacted.add(first);
}
return sumPairs(compacted);
}
Now you could break this method apart into several appropriately named shorter methods, and that would make sense. It's sometimes more helpful to start from the other end. Sketch out the logic of your code and what it's trying to do, then find meaningful fragments to split it into. Possibly after adding unit tests to verify behaviour.
what about doing by Recursion:
public int calculateSum(List<Integer> nums) {
displayList(nums);
if (nums.size() == 1) {
return nums.get(0);
}
List<Integer> interim = new ArrayList<Integer>();
for (int i = 0; i < nums.size(); i = i + 2) {
if (i + 1 < nums.size()) {
interim.add(nums.get(i) + nums.get(i + 1));
} else {
interim.add(nums.get(i));
}
}
return calculateSum(interim);
}
public static void displayList(List<Integer> nums){
System.out.println(nums);
}
Steps:
Run calculate sum until list has 1 element
if list has more than 1 element:
iterate the list by step +2 and sum the element and put into a new List
again call calculate sum
I am trying to use the summer to practice more Java to get better by learning how to code algorithms. I have this problem where I add elements to my ArrayList but somehow the first number I add also sets the number of positions in my list which I want to avoid. I only want the 0th index to contain the number 5. I seem to not catch a clue on how to solve this.
public class Algorithms {
private ArrayList<Integer> numbers;
public Algorithms() {
numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(4);
bubblesort();
}
public static void main(String args[]) {
new Algorithms();
}
public void bubblesort() {
System.out.println(numbers);
for (int a = 0; a < numbers.size();) {
for (int b = 1; b < numbers.size();) {
int currentNumber = numbers.get(a);
if (currentNumber > numbers.get(b)) {
//Collections.swap(numbers, currentNumber, numbers.get(b));
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
a++;
b++;
} else if (currentNumber < numbers.get(b)) {
a++;
b++;
}
System.out.println(numbers);
}
}
}
}
You are not swapping elements correctly. Instead of
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
it should be
int temp = numbers.get(a);
numbers.set(a, numbers.get(b));
numbers.set(b, temp);
The below two statements:
numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));
is not performing swapping. The first argument to the List#set(int, E) method is the index in the list, where you want to set the value passed as 2nd argument. You need to use a temp variable for swapping.
Also, the swapping didn't work for your commented line for the same reason. Collections#swap method take indices for swapping. So, just change:
Collections.swap(numbers, currentNumber, numbers.get(b));
to:
Collections.swap(numbers, a, b);
And please for the love of all that is holy, don't call method from inside a constructor. Remove the method invocation from inside the constructor, and move it to main method like this:
Algorithms algo = new Algorithms();
algo.bubbleSort()
Java newbie, what I am trying to do is retrieve a string name that prints to the screen if one of the multiple values is within a range as follows:
public class SuperHeroes {
private Map<String, Set<Integer>> names;
private Set<Integer> pageNum;
/**
* Constructor for objects of class SuperHeroes
*/
public SuperHeroes() {
names = new HashMap<>();
pageNum = new TreeSet<>();
}
/**
* The fill() method creates 2 entries.
*/
public void fill() {
pageNum.add(1);
pageNum.add(3);
pageNum.add(7);
names.put("Kent,Clark", pageNum);
pageNum = new TreeSet<>();
pageNum.add(2);
pageNum.add(6);
pageNum.add(4);
names.put("Wayne,Bruce", pageNum);
}
public void findInRange(int num, int numb) {
for (String eachName: names.keySet()) {
for (int eachNum:pageNum) {
if(eachNum >= num && eachNum <= numb) {
System.out.println(names.get(eachName));
}
}
}
}
}
The result printed to screen would be the name of superhero if the pageNum is within the range. thr output I get at the moment is all the numbers. Any help would be gratefully received. If you can point me in the right direction would be a help.
Thank you in advance.
First mistake in your code is the way you defined names and pageNum. It should be in this way:
public SuperHeroes()
{
names = new HashMap<String, Set<Integer>>();
pageNum = new TreeSet<Integer>();
}
Now You could use subSet() method of Treeset to achieve what you looking for . Here the code goes:
EDIT: While retrieving the Treeset for given name from names the returned value is needed to be typecast to TreeSet type. Same is to be done while using the subset method with tSet .
public void findInRange(int num, int numb)
{
for (String eachName: names.keySet())
{
TreeSet<Integer> tSet = (TreeSet<Integer>)names.get(eachName);
TreeSet<Integer> subSet = new TreeSet<Integer>();
subSet = (TreeSet<Integer>)tSet.subSet(num,true,numb,true);//for JDK 1.6 or above. returns num<=numbers<=numb
//TreeSet<Integer> subSet = tSet.subSet(num-1, numb+1);//for JDK version less than 1.6
if (subSet.size() != 0)
{
System.out.println("Hero is "+eachName);
break;//you can ommit it if you want to print all heroes having pagenum in range num to numb
}
}
}
The fill method is also needed to be modified as:
public void fill()
{
pageNum.add(1);
pageNum.add(3);
pageNum.add(7);
names.put("Kent,Clark", pageNum);
pageNum = new TreeSet<Integer>();//Use proper way of object construction with generics
pageNum.add(5);
pageNum.add(6);
pageNum.add(4);
names.put("Wayne,Bruce", pageNum);
}
First, you must use the name of the super hero for obtaining the treeset, then read every item in the tree and compare it with the number you need, if the comparison is true print the name of the superhero.
Look at this link
http://www.easywayserver.com/blog/java-treeset-example/
Best regards
You're telling it to print the numbers corresponding to the found name with the line
System.out.println(names.get(eachName));
If you only want to show the name, that should just be
System.out.println(eachname);
Well we are all guessing here. Maybe you need this :
public void findInRange(int num, int numb)
{
for (String eachName : names.keySet())
{
for (int eachNum : pageNum)
{
if (eachNum >= num && eachNum <= numb)
{
for (int temp = 0; temp < eachNum; temp ++)
{
System.out.println(eachName);
}
}
}
}
}
Wondering, you have initialised an pageNum in the constructor, why you are creating another one in the method fill()? That maybe the reason because the one in constructor may "hiding" from the second one in the fill method.
If anybody is interested I solved this with the following code:
public void findInRange(int num, int numb)
{
for(String eachName: names.keySet())
{
pageNum = names.get(eachName);
for (int eachNum:pageNum)
{
if(eachNum>=num&&eachNum<=numb||eachNum>=numb&&eachNum<=num)
{
System.out.println(eachName);
break;
}
}
}
}
I think the constructor is logically correct, I just can't figure out how to call it in the main ! :) Can anyone help please ? If someone would just have a quick look over my code it would be nice :) Thanks a lot !
Also, I am using arrayLists in this implementation and I have to do it this way so I don't wish to change it, even though it is far more easily implemented using only arrays.
import java.util.*;
public class PrimeNumberss {
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(10);
}
public PrimeNumberss (int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
}
Your algorithm is not correct; you will only find the primes less than N (your initial capacity), not the first N primes.
If you're going to store each prime, you should store them in a class variable not a variable local to the constructor. You won't be able to access them outside the constructor if you do.
You should expose the list using a getter method to provide access to them.
You're not printing anything in the constructor.
i==initialCapacity is clearly wrong.
Everything important is there, its small changes. Right now you are getting primes less than N, so if you want to change it to first N primes that's going to be a real functional difference. For now lets just make N=50 so you'll get well over 10 primes.
public class PrimeNumberss {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(50);
PrimeNumbers.print(); //use our new print method
}
public PrimeNumberss (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
//.... complete the constructor method as you have it. honestly, i didnt even read it all
public void print() //add this printout function
{
int i = 1;
it = listOfPrimeNumbers.listIterator();
while (it.hasNext())
{
System.out.println("the " + i + "th prime is: " + it.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
On a side note, you could probably d oa little better with the naming (PrimeNumberss and PrimeNumbers??), but I didnt change any of that. Also, intiialCapacity does not reflect what it really means. Maybe something along the lines of 'top'.