I am a beginner at java, but I'm trying to learn.
This is my program i am working on, the user will enter some values, where the program sort all the even values of the index to be the variable radie and all the odd values of the index to be height no matter what the element is. Same goes for nominator och denominator in the next method. But now i am stuck and dont know how to return the arrayList. I want to return my new arrays so i can use them in my other methods. Like i said im very new at java but find it fun to work with but now i need your help. As you can see i have been using swedish words for the outprint, sorry for that.
import java.util.Scanner;
import java.util.ArrayList;
public class program
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("-------------------------------");
System.out.println("# Test av area- och volymmetod.");
System.out.println("-------------------------------");
double result1 = area1(radie);
double result2 = area2(radie, height);
double result3 = volumeCone(radie, height);
System.out.println("Radie = " + radie + "\tHeight = " + height);
System.out.printf("Basytans area:%11.2f", result1);
System.out.println();
System.out.printf("Mantelytans area:%8.2f", result2);
System.out.println();
System.out.printf("Volym:%19.2f", result3);
System.out.println();
}
public static ArrayList<Integer> readFirstInputs(int numberOfInputs)
{
System.out.println("Please enter values, Q to quit:");
int[] inputs = new int[numberOfInputs];
ArrayList<Integer> radie = new ArrayList<Integer>();
ArrayList<Integer> height = new ArrayList<Integer>();
for(int i = 0; i < inputs.length; i++)
{
inputs[i] = keyboard.nextInt();
if (i % 2 == 0)
{
radie.add(inputs[i]);
}
else if (i % 2 != 0)
{
height.add(inputs[i]);
}
}
return ????? // return radie and height array, how?
}
public static ArrayList<Integer> readSecondInputs(int numberOfInputs)
{
System.out.println("Please enter values, Q to quit:");
int[] inputs = new int[numberOfInputs];
ArrayList<Integer> nominator = new ArrayList<Integer>();
ArrayList<Integer> denominator = new ArrayList<Integer>();
for(int i = 0; i < inputs.length; i++)
{
inputs[i] = keyboard.nextInt();
if (i % 2 == 0)
{
nominator.add(inputs[i]);
}
else if (i % 2 != 0)
{
denominator.add(inputs[i]);
}
}
return ????; // return nominator and denominator array, how?
}
/* Use my different arrays in the methods below. */
public static double area1(int radie)
{
double areaBas = Math.PI * Math.pow(radie, 2);
return areaBas;
}
public static double area2(int radie, int height)
{
double areaMantel = Math.PI * radie * Math.sqrt((Math.pow(radie, 2) + Math.pow(height, 2)));
return areaMantel;
}
public static double volumeCone(int radie, int height)
{
double volume = Math.PI * Math.pow(radie, 2) * height / 3;
return volume;
}
public static int fractionToInteger(int nominator, int denominator)
{
int amount = nominator / denominator;
return amount;
}
public static int fractionToFraction(int nominator, int denominator)
{
int remainingAmount = nominator % denominator;
return remainingAmount;
}
}
Are you allowed to use a list instead? it's way more efficient since once created, you can't change the size of an array, but if you instead create two empty lists you can just use the .add method that lists have, looking similar to this:
public static List<Integer> readFirstInputs(int numberOfInputs)
{
System.out.println("Please enter values, Q to quit:");
int[] inputs = new int[numberOfInputs];
List<Integer> evens = new List<Integer>();
List<Integer> odds = new List<Integer>();
for(int i = 0; i < inputs.length; i++)
{
inputs[i] = keyboard.nextInt();
if (i % 2 == 0)
{
evens.add(inputs[i]);
}
else if (i % 2 != 0)
{
odds.add(inputs[i]);
}
}
}
of course I am a bit confused on exactly what you want to do so you are definitely gonna have to change this up a bit, I just want to use this as a basic example of how to use a list instead.
If I understand you correctly, you would like to return from the function an array of odd numbers and an array of even numbers from user input.
but you are returning only one array which is just an array of the users inputs (with no logical meaning for the conditions in the loop).
from what I know - it is not possible to return 2 arrays, but there are solutions of course. you can return a class or a dictionary, for example.
if you choose a dictionary it will be something like Dictionary<string,object>, and will have 2 items, the string will be "odd" \ "even", and the object will be the matching array of the numbers (int[] or List<int>). odd numbers array a value of "odd" key, and even numbers array a value of "even" key in the dictionary.
two problems that appear to me here other than that:
1.) you are trying to use 2 variables that are not defined or even mentioned in the function (even and odd).
2.) in each condition you wrote return. this will exit the loop and function on the first iteration.
hope this was helpfull.
Related
I've searched through a several similar threads with the exact problem, however I have been unable to get the code to work, I want to find the closest value in the array and then remove it, here is my code :
import java.util.ArrayList;
import java.util.Scanner;
public class Entertrain {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;
while (console.hasNextInt()) {
weight.add(console.nextInt());
}
for (int i = 0; i < weight.size(); i++)
sum += weight.get(i);
if (sum > power) {
averageWagon = sum / weight.size();
//Here I want to find the closest value to averageWagon
}
System.out.println(averageWagon);
System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}
}
If it would be possible to guide me to a solution, I've tried for a few hours now and I've ended with the conclusion that I seriously lack knowledge of arrays, so in any case I will put aside this and focus on arrays for now, but would be grateful for help on this one.
It is not arrays you are looking for, it is Collections. You are using ArrayList, which implements the List.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;
while (console.hasNextInt()) {
weight.add(console.nextInt());
}
for (int i = 0; i < weight.size(); i++)
sum += weight.get(i);
if (sum > power) {
averageWagon = sum / weight.size();
Integer closest = weight.get(0);
for (Integer i: weight) {
if (Math.abs(averageWagon - closest) > Math.abs(averageWagon - i))
closest = i;
}
weight.remove(closest);
}
System.out.println(averageWagon);
System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}
You can do something like this
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Power: ");
int power = Integer.parseInt(console.nextLine());
ArrayList<Integer> weight = new ArrayList<>();
int averageWagon = 0;
int sum = 0;
while (console.hasNextInt()) {
weight.add(console.nextInt());
}
for (int i = 0; i < weight.size(); i++) {
sum += weight.get(i);
}
if (sum > power) {
averageWagon = sum / weight.size();
//Here I want to find the closest value to averageWagon
int closest = findClosestNumber(averageWagon, weight);
System.out.println("Closest number to average: "+ closest);
}
System.out.println(averageWagon);
System.out.println(weight);
System.out.println(power);
System.out.println(sum);
}
static int findClosestNumber(int num, List<Integer> numbers) {
int closest = numbers.get(0);
for (int i : numbers) {
if (Math.abs(num - i) < Math.abs(num - closest)) {
closest = i;
}
}
return closest;
}
Here's a way to do it with streams:
int sum = weight.stream().mapToInt(Integer::intValue).sum();
if (sum > power) {
int avg = sum / weight.size(); // shouldn't it be double?
weight.stream()
.min((a, b) -> Integer.compare(Math.abs(a - avg), Math.abs(b - avg)))
.ifPresent(weight::remove); // remove closest number from weight
} // list if found (i.e. if list not empty)
First a stream is used to find the sum, then the average is calculated and finally, Stream.min is used to find the minimum element of the stream, which is the one that is closest to the average.
Stream.min receives a Comparator as an argument, which has the usual comparator semantics: if the first argument is less than the second one, return a negative value; if greater, return a positive value, otherwise (if equal), return zero. In this case, a is less than b if its distance to the average is less than b's distance to the average. Here I'm using Integer.compare to perform the comparison.
Note that Stream.min doesn't return the minimum number, but an Optional<Integer> instead. This is because the weight list might be empty, so in this case there would be no minimum element. This is when the Optional.ifPresent method comes in handy: if a minimum has been found, then we remove it from the weight list, otherwise nothing happens.
I've been trying to implement Euclid's algorithm in Java for 2 numbers or more.The problem with my code is that
a) It works fine for 2 numbers,but returns the correct value multiple times when more than 2 numbers are entered.My guess is that this is probably because of the return statements in my code.
b) I don't quite understand how it works.Though I coded it myself,I don't quite understand how the return statements are working.
import java.util.*;
public class GCDCalc {
static int big, small, remainder, gcd;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Remove duplicates from the arraylist containing the user input.
ArrayList<Integer> listofnum = new ArrayList();
System.out.println("GCD Calculator");
System.out.println("Enter the number of values you want to calculate the GCD of: ");
int counter = sc.nextInt();
for (int i = 0; i < counter; i++) {
System.out.println("Enter #" + (i + 1) + ": ");
int val = sc.nextInt();
listofnum.add(val);
}
// Sorting algorithm.
// This removed the need of conditional statements(we don't have to
// check if the 1st number is greater than the 2nd element
// before applying Euclid's algorithm.
// The outer loop ensures that the maximum number of swaps are occurred.
// It ensures the implementation of the swapping process as many times
// as there are numbers in the array.
for (int i = 0; i < listofnum.size(); i++) {
// The inner loop performs the swapping.
for (int j = 1; j < listofnum.size(); j++) {
if (listofnum.get(j - 1) > listofnum.get(j)) {
int dummyvar = listofnum.get(j);
int dummyvar2 = listofnum.get(j - 1);
listofnum.set(j - 1, dummyvar);
listofnum.set(j, dummyvar2);
}
}
}
// nodup contains the array containing the userinput,without any
// duplicates.
ArrayList<Integer> nodup = new ArrayList();
// Remove duplicates.
for (int i = 0; i < listofnum.size(); i++) {
if (!nodup.contains(listofnum.get(i))) {
nodup.add(listofnum.get(i));
}
}
// Since the array is sorted in ascending order,we can easily determine
// which of the indexes has the bigger and smaller values.
small = nodup.get(0);
big = nodup.get(1);
remainder = big % small;
if (nodup.size() == 2) {
recursion(big, small, remainder);
} else if (nodup.size() > 2) {
largerlist(nodup, big, small, 2);
} else // In the case,the array only consists of one value.
{
System.out.println("GCD: " + nodup.get(0));
}
}
// recursive method.
public static int recursion(int big, int small, int remainder) {
remainder = big % small;
if (remainder == 0) {
System.out.println(small);
} else {
int dummyvar = remainder;
big = small;
small = dummyvar;
recursion(big, small, remainder);
}
return small;
}
// Method to deal with more than 2 numbers.
public static void largerlist(ArrayList<Integer> list, int big, int small, int counter) {
remainder = big % small;
gcd = recursion(big, small, remainder);
if (counter == list.size()) {
} else if (counter != list.size()) {
big = gcd;
small = list.get(counter);
counter++;
largerlist(list, gcd, small, counter);
}
}
}
I apologize in advance for any formatting errors etc.
Any suggestions would be appreciated.Thanks!
I think these two assignments are the wrong way around
big = gcd;
small = list.get(counter);
and then big not used
largerlist(list, gcd, small, counter);
Also you've used static variables, which is usually a problem.
I suggest removing static/global variables and generally don't reuse variables.
Edit: Oh yes, return. You've ignored the return value of the recursion method when called from the recursion method. That shouldn't matter as you are printing out instead of returning the value, but such solutions break when, say, you want to use the function more than once.
How would i prevent duplicating numbers from random numbers.
I need to generate 5 numbers between 1 and 9 that are each different.
I would often get same numbers like 23334, how can i prevent that?
Any help would be great!
int num2 = (int) Math.round((Math.random()*9) +1);
int num1 = (int) Math.round((Math.random()*9) +1);
int num5 = (int) Math.round((Math.random()*9) +1);
int num3 = (int) Math.round((Math.random()*9) +1);
int num4 = (int) Math.round((Math.random()*9) +1);
One option is to use shuffle algorithm (e.g. Fisher-Yates shuffle ) to generate random sequence from 1 to 9, then take first 5 numbers of the sequence
Further explanation on StackOverflow: https://stackoverflow.com/a/196065/950427
Set<Integer> set=new HashSet<>();
while (set.size()<5) {
set.add( Math.round((Math.random()*9) +1));
}
After the set is filled you have 5 unique random numbers.
UPDATE: just to illustrate Jared Burrows' comment
Create a List includes the numbers that you want (1 to 9).
Generate random number from 0 to (size of the list minus 1).
Remove one element by index from the above generated random number. And add the removed element to a array which to be returned as a results
public static void main(String[] args) {
int []answers= returnRandomNonRepeatingNumbers(5,0,9);
for(int answer: answers) {
System.out.println(answer);
}
}
public static int[] returnRandomNonRepeatingNumbers(int sizeYouWant, int poolStart, int poolEnd) {
List<Integer> pool=new ArrayList<Integer>();
for(int i=poolStart;i<=poolEnd;i++) {
pool.add(i);
}
int []answers=new int[sizeYouWant];
for(int i=0;i<sizeYouWant;i++) {
//random index to be pick and remove from pool
int randomIndex = (int) Math.round((Math.random()*(pool.size()-1)));
answers[i]=pool.remove(randomIndex);
}
return answers;
}
If the number of possible random values is small, you want to use shuffle.
List<Integer> values = IntStream.range(0, 10).boxed().collect(toList());
Collections.shuffle(values);
values = values.subList(0, 5);
If the number of possible random values is large, you want to test adding them to a Set (or the original list if small enough)
Set<Integer> valueSet = new HashSet<>();
Random rand = new Random();
while(valuesSet.size() < 5) valuesSet.add(rand.nextInt(9) + 1);
List<Integer> values = new ArrayList<>(valueSet);
Collections.shuffle(values, rand);
Note: you need to shuffle the set as it doesn't preserve order. e.g. the numbers 1,2,3 will always come out in that order with HashSet, not 3,2,1.
Floyd's subset selection algorithm is designed to do exactly what you want, and is extremely efficient even for large sets. Selecting m items from a set of n is O(m) average running time, independent of n. Here's a Java implementation.
/*
* Floyd's algorithm to chose a random subset of m integers
* from a set of n, zero-based.
*/
public static HashSet<Integer> generateMfromN(int m, int n) {
HashSet<Integer> s = new HashSet<Integer>();
for (int j = n-m; j < n; ++j) {
if(! s.add((int)((j+1) * Math.random()))) {
s.add(j);
}
}
return s;
}
One possible approach to this problem can be divide & conquer. Step of following describes the approach:
Say m is the minimum & n is the maximum, within what i wanna get x number of randoms
Choose a random p between m & n. Save it to an array of answer. decrease x by 1 as we get one answer to our problem.
Now take a q a random number between m & p-1, another r a random number between p+1 & n. Fill up the answer array with q & r decrease x 1 for q and another 1 for the r.
Now carry on this process recursively, until the lower bound (m) & higher bound (n) becomes equal or x becomes 0.
Benefit: benefit of this approach is that, in worst case, it's runtime will be O(x), where x is the number of random number required. The best case scenarion is also o(x), as i have to find at least n number of random. These two comprise average case to θ(x) complexity.
import java.util.Random;
class GenerateDistinctRandom{
static int alreadyPut = 0;
static Random rand = new Random();
public static int[] generateDistinctRandom(int howMany, int rangeMin, int rangeMax)
{
int randomNumbers[] = new int[howMany];
GenerateDistinctRandom.recursiveRandomGenerator(rangeMin, rangeMax, randomNumbers, howMany);
return randomNumbers;
}
private static void recursiveRandomGenerator(int rangeMin, int rangeMax, int[] storage ,int storageSize)
{
if(rangeMax - rangeMin <= 0 || GenerateDistinctRandom.alreadyPut == storageSize)
{
return ;
}
int randomNumber = GenerateDistinctRandom.rand.nextInt(rangeMax-rangeMin) + rangeMin;
storage[GenerateDistinctRandom.alreadyPut] = randomNumber;
GenerateDistinctRandom.alreadyPut++;
//calling the left side of the recursion
recursiveRandomGenerator(rangeMin, randomNumber - 1, storage, storageSize);
recursiveRandomGenerator(randomNumber + 1, rangeMax, storage, storageSize);
}
public static void main(String []args){
int howMany = 5;
int distinctNumber[] = GenerateDistinctRandom.generateDistinctRandom(howMany 0, 9);
for(int i = 0;i < howMany;i++)
{
System.out.println(distinctNumber[i]);
}
}
}
I suppose you would need to store the ones that have been generated into an array and compare the new random number to the list to ensure it is unique.
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] numbers = new int[5];
int tempNumber = 0;
for(int numberCounter = 0; numberCounter < numbers.length;)
{
tempNumber = (int) Math.round((Math.random()*9) +1);
if(!contains(numbers, tempNumber)){
numbers[numberCounter++] = tempNumber;
}
}
}
public static boolean contains(final int[] numbersArray, final int tempNumber) {
for (final int numberFromArray : numbersArray) {
if (numberFromArray == tempNumber) {
return true;
}
}
return false;
}
I notice you did not use an array in your example, so in case you do not know how to use them yet, you could also make 5 variables.
int randomNumber = 0;
int firstNumber = Math.round((Math.random()*9) +1);
int secondNumber = 0;
while(secondNumber == 0){
randomNumber = Math.round((Math.random()*9) +1)l
if(randomNumber != firstNumber){
secondNumber = randomNumber;
}
}
And you could continue making while statements like that. But if you are supposed to know about arrays, you should definitely be using one to store the numbers.
How about this?
package com.se;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TestRandom {
List<Integer> comp = new ArrayList<>();
int listSize = 20;
public void doTask() {
Random ran = new Random();
int i = 0;
while(i < listSize){
int randomNumber = ran.nextInt(80) + 1;
if(!comp.contains(randomNumber)){
comp.add(randomNumber);
i++;
}
}
for(Integer num : comp){
System.out.println(num);
}
}
public static void main(String[] args) {
TestRandom testRandom = new TestRandom();
testRandom.doTask();
}
}
Write a method to generate and return a set of random values in an int array of a user specified size. The values should all be between +/- N, where N is a constant such as 100.
Thank you.
Here's Mine;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
int limit, numbers;
Random random = new Random();
Scanner scan = new Scanner(System.in);
System.out.print ("Enter your limit value for your array: "); //Needs to be positive.
limit = scan.nextInt();
int[] list = new int[limit];
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + ", ");
}
numbers = random.nextInt(limit - (0 - limit)) + (0 - limit);
System.out.println (numbers);
System.out.println (list[numbers]);
}
}
public List<Integer> random(int range, int count){
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<count;i++){
if(Math.random() > 0.5){
//adding positive value with probability of 0.5
result.add((int)(Math.random() * (double)range));
}else{
//adding negative value with probability of 0.5
result.add(-1 * (int)(Math.random() * (double)range));
}
}
return result;
}
If you want to create your own random number generator, the easiest one to implement will be Linear Congruential Generator. Read from wiki and try yourself. Ask here if you need help.
My professor asked us to generate random variables between 0 and 0.5. I wrote this code:
public class Random_Number_Generator {
double randomGenerator() {
Random generator = new Random();
double num = generator.nextDouble() * (0.5 - 0);
return num;
}
}
But my professor is saying this code is generating random numbers not random variables. What could this mean?
Apparently I misread the post; the following should be read with that in mind.
In that code, num and generators are local variables. A random number (a value) is assigned to the variable called num using the Random object named by the generator variable. Finally, the value stored in the variable num is returned from the method.
In any case, generator.nextDouble() returns a value between [0,1) so to get a value between [0,0.5), just scale it by half: divide it by two or, as done, multiply it by a half.
The - 0 in the above code is silly, but "okay" because (0.5 - 0) == 0.5.
(Also, it is good to get into the practice of to creating one Random instance and re-using it .. although this issue is more obvious in .NET.)
Now, actual random variable is, as far as I know, a function that maps values to their probability. I don't think you're supposed to return a function, so I've scratched this: the closest thing to what I guess you're supposed to do:
import java.util.*;
import java.lang.*;
class RandomVar
{
TreeMap<Double, Integer> variables;
public RandomVar()
{
variables = new TreeMap<Double, Integer>();
int count = Main.RandGen.nextInt(15);
double probabilityLeft = 1.0;
for (int i = 0 ; i < count - 1; i++)
{
int toPut = Main.RandGen.nextInt(100);
while (variables.containsValue(toPut)) toPut = Main.RandGen.nextInt(100);
double prob = probabilityLeft * Main.RandGen.nextDouble();
variables.put(prob, toPut);
}
int toPut = Main.RandGen.nextInt(100);
while (variables.containsValue(toPut)) toPut = Main.RandGen.nextInt(100);
double prob = probabilityLeft;
variables.put(prob, toPut);
}
public int getValue()
{
double rand = Main.RandGen.nextDouble();
double sum = 0;
for (double prob : variables.keySet()) //keySet() is sorted ascending
{
if (prob >= rand)
return variables.get(prob);
}
return variables.get(variables.lastKey());
}
//Shows probabilities of values
public void test()
{
for (double key : variables.keySet())
System.out.println(key + " :: " + variables.get(key));
}
}
class Main
{
public static Random RandGen = new Random();
public static void main (String[] args)
{
RandomVar rv = new RandomVar();
rv.test();
System.out.println("------------------------------");
for (int i = 0; i < 40 ; i++)
System.out.print(rv.getValue() + ", ");
}
}
This is very lousy solution, basically a class which allows you to return values with a set (random) probability. I still don't know if this is what you professor wants though...
Try this code:
public static void main(String[] arg) {
System.out.print(Random());
}
public static double Random() {
double START = 0;
double END = 0.5;
Random random = new Random();
double token = RandomNumber(START, END, random);
return token;
}
public static double RandomNumber(double aStart, double aEnd, Random aRandom) {
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
// get the range, casting to long to avoid overflow problems
double range = aEnd - aStart;
// compute a fraction of the range, 0 <= frac < range
double fraction = (range * aRandom.nextDouble());
double randomNumber = (fraction + aStart);
return randomNumber;
}