package myProjects;
import java.util.*;
public class Acm3 {
static int numberOfFriends;
static int rowOfChocolate;
static int columnOfChocolate;
static String division;
static Scanner myScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("How many friends you want to distribute?");
numberOfFriends = myScanner.nextInt();
System.out.println("How do you want to distribute?");
division = myScanner.next();
String[] myArray = division.split("\\s");
int[] myArray1 = new int[numberOfFriends];
int i;
for (i = 0; i <= numberOfFriends; i++); {
myArray1[i] = Integer.parseInt(myArray[i]);
System.out.print(myArray1[i]);
}
}
}
I am trying to transfer String array to Int Array.I have a string array and want to convert each elements into int and finally into array. Anyone who can help?
Thanks in advance
int[] intValues = Arrays.asList(myArray)
.stream()
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(intValues));
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;
}
}
}
}
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]
I am trying to find a way to assign values to an Array from the scanner input by using enhanced For loop. But I don't see a way I can do it.
In the code below i have declared a getInput() method which loops through the Array and assign numbers from the scanner input. But in case of enhanced For loop I can't really use something like this -
For(int i: baseData){
//basedata[i]=scanner.nextInt()}
because baseData array will not return any value as it iterates, so i thought how about iterating through scanner.nextInt() and assign values in the array, but scanner.nextInt() is not a array.
So what could the easy solution for this problem?
package com.ksk;
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
for (int i = 0; i < baseData.length; i++) {
baseData[i] = scanner.nextInt();
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
A for-each loop hides the iterator, so you won't be able to update the array with one (at least not without adding a new counter / iterator). Instead, assuming you're using Java 8+, you can write an IntStream generator using your Scanner. Something like,
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
However, this is really just an example, in real life I would prefer code that is a little more forgiving with unexpected input.
Try like this.
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = IntStream.generate(() -> scanner.nextInt())
.limit(4).toArray();
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
printInput();
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
OR
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
private static int[] baseData = new int[4];
public static void main(String[] args) {
System.out.println("Enter 4 numbers here");
getInput();
printInput();
}
static void getInput() {
int position =0;
for(int i:baseData){
baseData[position] = scanner.nextInt();
position++;
}
}
static void printInput() {
for (int i : baseData) {
System.out.println(i);
}
}
}
I wrote the following code for Pascal's triangle on https://leetcode.com/ and I got the error as follows:
Line 10: error: incompatible types: int cannot be converted to
List<List<Integer>>.
public class Solution {
public List<List<Integer>> generate(int numRows) {
List list;
int temp;
for(int i=0;i<numRows;i++) {
temp = (int) Math.pow(11,i);
list.add(Arrays.asList(temp));
}
return temp;
}
public static void main(String s[]) {
Solution solution = new Solution();
java.util.Scanner scan = new java.util.Scanner();
System.out.println("Enter the no.of Rows");
int numRows = scan.nextInt();
solution.generate(numRows);
}
}
Help me to find the solution.
You have almost right answer. Just few mistypes. Here is good one:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> generate(int numRows) {
List<Integer> list=new ArrayList<Integer>();
int temp;
for (int i = 0; i < numRows; i++) {
temp = (int) Math.pow(11, i);
list.add(temp);
}
return list;
}
public static void main(String s[]) {
Solution solution = new Solution();
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the no.of Rows");
int numRows = scan.nextInt();
Object answer=solution.generate(numRows);
System.out.println(answer);
}
}
Your method is defined as returning a List<List<Integer>> (a list of lists of integers) but you are trying to return an integer.
You have created the List in the method, so you should return that, and not the integer temp.
public List<Integer> generate(int numRows) {
List list;
int temp;
for(int i=0;i<numRows;i++) {
temp = (int) Math.pow(11,i);
list.add(Arrays.asList(temp));
}
return list;
Why are returning int value for List return type. please change it to list. It will compile properly.