I'm new here..
I want to make a code to remember the last 10 numbers and to be not same.
private static ArrayList<Integer> nums = new ArrayList<Integer>();
public static void main(String[] args)
{
System.out.println(getRandomNumber());
}
public static int getRandomNumber()
{
int randomN = 0, rand = Rnd.nextInt(20);
while (nums.size() == 10)
{
nums.remove(nums.get(0));
continue;
}
if (!nums.contains(rand))
{
nums.add(rand);
randomN = rand;
}
else getRandomNumber();
return randomN;
}
when the array reach 10 values the first one will be deleted .. I hope you understand what I want :) Thanks
Try using an ArrayDequeue and when the length grows to more than 10, you simple remove the items from the tail.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
class main{
public ArrayList<Integer> nums;
public Random generator;
public static void main(String[] args){
// Calling Start
(new main()).start();
}
public void start(){
nums = nums = new ArrayList<Integer>();
generator = new Random();
for(int i=0;i<15;i++){
add(generator.nextInt(20));
print();
}
}
public void add(int newNumber){
// Check by iterating if i is already in nums
Iterator it = nums.iterator();
while(it.hasNext()){
if(newNumber == (Integer) it.next())
return; // i is already in our list
// so get out add()
}
if(nums.size() == 10){
int forward = nums.get(0);
for(int i = 1; i < 10; i++){
// Move numbers back 1 position
nums.set(i-1,forward);
// Save next number in forward
forward = nums.get(i);
}
}
nums.add(newNumber);
}
public void print(){
String str = "";
Iterator it = nums.iterator();
if(it.hasNext()){
str += "num: [ " + (Integer) it.next();
}
while(it.hasNext()){
str += " , " + (Integer) it.next();
}
str += " ]";
System.out.println(str);
}
}
I would either use a circular array or a linked list for this. Depending on what you plan to use the list of numbers for.
Related
I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.
Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)
Here's the original code:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 15;
final int MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
And here's my solution to it:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 51;
final int MULTIPLE = 1;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = (index - 25) * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
Yes, basically it's really simple exercise.
Regarding to your solution we actually don't need MULTIPLE in code.
public class BasicArray {
public static void main(String[] args) {
final int LIMIT = 51;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++) {
list[index] = (index - 25);
}
list[5] = 999; // change one array value
// Print the array values
for(int value : list) {
System.out.println(value + "");
}
}
}
If you are ready for a bit of advanced java, you can try following:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(System.out::println);
}
}
Or this if you need to replace one value:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(i -> {
if (i == -20) { // change one array value
System.out.println(999);
} else {
System.out.println(i);
}
});
}
}
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());
}
}
I am trying to learn how to add dynamically data into a list but I am facing a problem.
Why am I getting wrong value index of 0. when ever I trying to add a value position of index.
import java.util.*;
public class MyList{
String[] mList = null;
int pointer;
public MyList(){
mList = new String[pointer];
}
public void add(String aStringValue){
System.out.println("add: "+pointer+ " " +aStringValue+ " "+mList.length);
if (pointer < mList.length-1) {
System.out.println(pointer+ " " +aStringValue);
mList[pointer] = aStringValue;
pointer++;
}else{
System.out.println("New List:");
String[] lStringList = new String[mList.length + 20];
System.arraycopy(mList, 0, lStringList, 0, mList.length);
mList = lStringList;
System.out.println("New List: "+mList.length);
}
}
public int size(){
int size = 0;
for (int i = 0;i<mList.length;i++) {
if (mList[i] == null) {
return size;
}else{
size++;
}
}
return size;
}
public String get(int index){
return mList[index];
}
}
public class ListSize{
public static void main(String[] args){
MyList lList = new MyList();
lList.add("Amit");
lList.add("Deepak");
lList.add("Vishal");
lList.add("hello");
lList.add("abc");
lList.add("rahul");
lList.add("ajit");
lList.add("durgesh");
lList.add("a");
lList.add("b");
lList.add("c");
lList.add("d");
lList.add("e");
System.out.println("MyList is: "+lList.size());
for (int i = 0; i<lList.size(); i++) {
System.out.println(lList.get(i));
}
}
}
I expect the Output of Amit, Deepak but the Actual output is Deepak, vishal
When you create a new array, you don't add anything to it. I suggest you always check the size is ok, and afterwards, always add the element. If you want to see this clearly, I suggest stepping through the code in your debugger.
public void add(String aStringValue) {
// ensure capacity.
if (pointer == mList.length)
mList = Arrays.copyOf(mList, mList.length + 20);
mList[pointer++] = aStringValue;
}
In your add method, if the array hasn’t got room for the string you want to add, you are creating a new and bigger array, but not adding the string to the new array.
I believe that the code in the if part of your if statement should go after the if statement instead.
// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length
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;
}