Java Program assistance - java

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());
}
}

Related

How to send from deque and split it into two lists?

Hello everyone I was given the assignment in which I have
In main, you create a queue with generated Strings
word genereting should be done in main
You pass it to executeTasks, they are split into the appropriate lists
I have a problem with referencing things in code
it is still confusing for me☹️
it was much easier on the numbers
Write a program that in the ArrayDeque queue will put 50 objects storing strings (strings), consisting of the letter 'a' repeated a random number of times (repeat range: 1-50).
Filling the object with the repeats of the letter 'a' can be done with a for loop.
Part 2
Extend the program from the first part in such a way that you pass the created queue to the method of your class, which will separate the objects from the queue into two ArrayList collections.
One of them will hold objects with an even number of 'a' characters, the other one with an odd number.
in general, I have done the task in a slightly different way, but I need to correct it
import java.util.*;
import java.lang.*;
class TaskManager {
List<String> executedTasks;
List<String> even;
List<String> odd;
// constructor
public TaskManager() {
executedTasks = new ArrayList<>();
even = new ArrayList<>();
odd = new ArrayList<>();
}
//method serving the list of tasks
public void executeTasks(Deque<String> theQueue) {
while (theQueue.size() > 0) {
String theTask = theQueue.poll();
System.out.println("Processing the task: " + theTask);
char c = 'a';
for (int n = 0; n < 50; n++) {
String result = "";
int count = (char) (Math.random() * 50 + 1);
for (int i = 0; i < count; i++) {
result += c;
}
System.out.println(result);
if (result.length() % 2 == 0) {
even.add(result);
} else {
odd.add(result);
}
executedTasks.add(theTask);
System.out.println("\nExecuted total " + executedTasks.size() + " tasks\n");
}
}
}
}
/* Name of the class has to be "Main" only if the class is public. */
public class QueuesAndLoops {
public static void main(String[] args) throws java.lang.Exception {
char c = 'a';
Deque<String> taskQueue1 = new ArrayDeque<>();
for (int n = 0; n < 1; n++) {
taskQueue1.offer("The first task number " + (n + 1));
}
TaskManager taskExecutor = new TaskManager();
taskExecutor.executeTasks(taskQueue1);
System.out.println("Parzyste:");
System.out.println(taskExecutor.even);
System.out.println("Nieparzyste:");
System.out.println(taskExecutor.odd);
}
}
and this code works but I have a problem to change it to the required version
no one replied but it was about reworking it in a similar way
import java.util.*;
import java.lang.*;
class TaskManager {
List<String> even;
List<String> odd;
// constructor
public TaskManager() {
even = new ArrayList<>();
odd = new ArrayList<>();
}
//method serving the list of tasks
public void executeTasks(Deque<String> theQueue) {
String task;
while ((task = theQueue.poll()) != null) {
System.out.println(task);
boolean isAdded = task.length() % 2 == 0 ? even.add(task) : odd.add(task);
}
}
}
public class QueuesAndLoops {
public static void main(String[] args) throws java.lang.Exception {
final int NUM_TASKS = 50;
String chr = "a";
Deque<String> taskQueue1 = new ArrayDeque<>();
for (int i = 0; i < NUM_TASKS; i++) {
taskQueue1.offer(chr.repeat((int) (Math.random() * 50 + 1)));
}
TaskManager taskExecutor = new TaskManager();
taskExecutor.executeTasks(taskQueue1);
System.out.println("Even:");
System.out.println(taskExecutor.even);
System.out.println("Odd:");
System.out.println(taskExecutor.odd);
}
}

Function value always getting multiplied by 2

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;
}

Printing on same line

I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}

Random, and not same with last 10. (Java)

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.

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}

Categories

Resources