I've been trying with this problem but couldn't wrap my head around it..
"Create a java method int [] roundoff (ArrayList input) that returns a new integer array containing all the input doubles correctly rounded off to integers."
This is where I got so far:
package javaProblem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class TowMethods {
public static int[] roundOff(ArrayList<Double> input) {
int [] iL=new int[input.size()];
for (double i:iL) {
//input.get(i);
int n=(int) Math.round(i) ;
iL[n]=n;
}
System.out.print(Arrays.toString(iL));
return (iL);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Double> input1 = new ArrayList<Double>();
input1.add(2.3);
input1.add(1.3);
input1.add(3.35);
/* for (int i = 0; i < 3; i++) {
double num = keyboard.nextDouble();
input.add(num);
}*/
int[] iList = roundOff(input1);
System.out.println(Arrays.toString(iList));
}
}
for (int i = 0; i < input.size(); i++) {
iL[i] = (int)(Math.round(input.get(i)));
}
Instead of your loop in roundOff method
Please try to use meaningful names when you name your variables. Also inside the roundOff method instead of the foreach loop use a classic for loop and don't iterate through the freshly created integer array but over the ArrayList which you take as a parameter.
Here is the possible solution:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class TowMethods {
public static int[] roundOff(ArrayList<Double> inputs) {
int [] integers=new int[inputs.size()];
for (int i=0; i < inputs.size(); i++) {
integers[i] = (int) Math.round(inputs.get(i));
}
return integers;
}
public static void main(String[] args) {
// Scanner keyboard = new Scanner(System.in);
ArrayList<Double> inputs = new ArrayList<Double>();
inputs.add(2.3);
inputs.add(1.3);
inputs.add(3.35);
/*
for (int i = 0; i < 3; i++) {
double num = keyboard.nextDouble();
inputs.add(num);
}
*/
int[] iList = roundOff(inputs);
System.out.println(Arrays.toString(iList));
}
}
If you want to take the user input just uncomment the commented lines in the main method.
Use Math.rint() which properly rounds to the next int value.
double [] dbls = {2.4, 8.8, 22.23, 97.6};
int[] ints = new int[dbls.length];
for (int i = 0; i < dbls.length; i++) {
ints[i] = (int)Math.rint(dbls[i]);
}
System.out.println(Arrays.toString(dbls));
System.out.println(Arrays.toString(ints));
Prints
[2.4, 8.8, 22.23, 97.6]
[2, 9, 22, 98]
Related
Our assignment says we should "write the source code and test code for a function named sumArray that accepts an array of ints and returns the sum of all elements from the array".
I think I've got SumArray.java to return sum OK, but I'm struggling to apply my method to the test input. Any help please? TIA.
SumArray.java
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
SumArrayTest.java
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
/**
* Test of main method, of class SumArray.
*/
#Test
public void testMain() {
System.out.println("main");
String[] args = null;
SumArray.main(args);
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
// int testResult = sumArray({2, 3, 4});
int testResult = SumArray sumArray(intArray);
assertEquals(expectedResult, testResult);
// fail("The test case is a prototype.");
}
}
Edit: I've tried to implement what's been suggested so far with some changes; really not sure of any of this is right; a lot of it is guesswork TBH.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray;
public static int sumArray(int[] arr) {
return sum;
}
public static SumArray input() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return new SumArray();
}
public static void main(String[] args) {
SumArray result = input();
System.out.println(result.sumArray(SumArray));
}
}
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
#Test
public void testSumArray() {
System.out.println("main");
String[] args = null;
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
assertEquals(expectedResult, SumArray.sumArray(intArray));
// fail("The test case is a prototype.");
}
}
The only error I'm seeing currently is 'cannot find symbol' for SumArray in main.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
The above is the original code you posted. Now, you say you get the correct output. Yes, here you do:
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray(); // this one will return the correct answer
sumArray(); // this one will not
}
}
The second one will return wrong data, because you don't reset the value of sum.
You should split the tasks: sumArray should receive an array, and should return the sum of the elements. Either you should change the name of the method, or change the implementation, that is what Mahmoud told you.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static Scanner scan = new Scanner(System.in); // create this on class level, not every execution of your method
public static int[] buildArray(int elements) {
int[] arr = new int[elements];
for ( int i = 0; i < elements; i++ ) {
System.out.println("Enter element nr: " + (i+1));
arr[i] = scan.nextInt();
}
return arr;
}
public static int sumArray(int[] input) {
int sum = 0; // don't use a class level one. especially not a static one, it's value could be altered by another thread
for ( int in : input ) { // iterate over the array and add the values
sum += in; // this should be in -> each iteration we add the value of in (the element of the array) to sum
}
return sum;
}
public static void main(String[] args) {
System.out.println("Provide the size of the array: ");
int param = scan.nextInt();
int[] array = buildArray(param);
int result = sumArray(array);
System.out.println("The sum of the array is: " + result);
}
}
This approach will land you with far lesser issues. It also doesn't have static variables like n and sum in your class that might lead to wrong results.
The main() method is the entry point into the application, you shouldn't test the main() method. Instead, you should test the sumArray() method and compare the expected Vs. the actual returned value from the method.
As a side note, you can better pass the input array to the sumArray() method as a parameter instead of reading it from System.in within the method body.
So your method signature can look like this:
public static int sumArray(int[] arr). The client code which uses this method, which is the main method in your case (or the unit test) can pass the array without bothering the method how this input array was got.
I am writing a program that takes in the number of ingredients. The prog
This is my code:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);:
public static void sortCalories(double[] calories,double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p=0; p<calories.length; p++) {
for (int j=p+1; j<calories.length; j++) {
if(calories[p]/price[p]>calories[j]/price[j]) {
temp = calories[p];
calories[p] = calories[j];
calories[j] = temp;
temp = price[p];
price[p] = price[j];
price[j] = temp;
temp1 = ingredientName[p];
ingredientName[p] = ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}
sorry I'm really new to all of this. I know this is a stupid/easy question, but how would I display the shuffled array after i've set it all up. I have my code below and made the class that creates the array and has the algorithm for shuffling the integers inside the array. But I can't figure out how to display the shuffled array. Heres my code below:
My main:
package lab4b;
import java.util.Scanner;
public class Lab4B {
public static void main(String[] args) {
Shuffler test = new Shuffler(15);
test.Shuffle();
test.display();
}
}
and my Shuffle class:
package lab4b;
import java.security.SecureRandom;
public class Shuffler {
private static final SecureRandom randomNumbers = new SecureRandom();
private int [] data;
public Shuffler (int size){
data = new int [size];
for(int i = 0; i<data.length;i++){
data[i]= i+1;
}
}
public void Shuffle(){
int temp;
for(int first = 0; first<data.length; first++){
int second = randomNumbers.nextInt(data.length);
temp = data[first];
data[first] = data[second];
data[second] = temp;
}
}
public void display()
{
for(int counter =0; counter<data.length; counter++ ){
System.out.print(data[counter]+ " ");
}
System.out.println();
}
}
In this loop you are reset the value of the dataarray
for(int counter =0; counter<data.length; counter++ ){
// data[counter] = counter + 1; - do not do this
System.out.print(data[counter]+ " ");
}
I'm trying to append all of numbers that the program generates, into an array.
I used ArrayList method. However i can't manage program to read arr elements.
import java.util.Random;
import java.util.ArrayList;
public class Numbers {
public ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
Furthermore; i'm trying all generated numbers to be read via another method.
(That part is the following)
How can the program read all generated numbers?
double [] numbers= StdIn.getNumbers(); // Stuck at here.
Is it possible to calling getNumbers method like that?
You can read it directly by creating the array list of type double:
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
public class Numbers {
public ArrayList<Double> getNumbers() {
Random getNum = new Random();
ArrayList<Double> arr = new ArrayList<Double>(1000);
int size = 1000;
for (int i = 0; i < size; i++) {
double gauss = getNum.nextGaussian() * 15 + 70;
arr.add(gauss);
}
return arr;
}
public static void main(String[] args) {
Numbers number = new Numbers();
ArrayList<Double> arr = number.getNumbers();
System.out.println(arr);
}
}
You can call from other class as bellow
import java.util.Random;
import java.util.ArrayList;
public class PrintArray {
public static void main(String args[]){
ArrayList<Double> arrelements=OtherClass.getNumbers();
java.util.Iterator<Double> iterator = arrelements.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class OtherClass{
public static ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
You can iterate through the ArrayList to read numbers from your ArrayList.
import java.util.Random;
import java.util.ArrayList;
import javax.swing.text.html.HTMLDocument.Iterator;
public class PrintArray {
public static void main(String args[]){
ArrayList<Double> arrelements=getNumbers();
java.util.Iterator<Double> iterator = arrelements.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
public static ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
System.out.println(arr);
return arr;
}
}
You might think of something like that:
Initiate on object of your class and call the function
public class Numbers {
public ArrayList<Double> getNumbers( )
{
Random getNum=new Random();
ArrayList<Double> arr=new ArrayList<Double>(1000);
int size=1000;
for(int i=0;i<size;i++)
{
double gauss=getNum.nextGaussian()*15+70;
arr.add(gauss);
}
return arr;
}
public static void main(String[] args) {
Numbers n = new Numbers();
List<Double> numbers = n.getNumbers();
for (Double number : numbers) {
System.out.println(number);
}
}
}
Numbers class
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public final class Numbers {
private Numbers() {}
public static List<Double> getArrayListOfNumbers() { // ArrayList
List<Double> numbers = new ArrayList<>();
for(double d : getArrayOfNumbers()) {
numbers.add(d);
}
return numbers;
}
public static double[] getArrayOfNumbers() { // Array
Random random = new Random();
double[] numbers = new double[1000];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextGaussian() * 15 + 70;
}
return numbers;
}
}
Test Drive:
import java.util.List;
public class TestDrive {
public static void main(String[] args) {
// Printing arrayList numbers
List<Double> arrayListOfNumbers = Numbers.getArrayListOfNumbers();
arrayListOfNumbers.stream().forEach(System.out::println);
// Printing certain arrayList object
System.out.println("\nArrayList #7: " + arrayListOfNumbers.get(7));
}
}
Extra info:
Usually when there's need for fixed size/length (total values/objects), arrays are used (in your case it's 1000).
While ArrayList is a collection implementing interface List, which is used when there's no need for fixed size/length or when there's need for size/length flexibility.
I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH