Max of a list of strings in Java - java

I have data in the form of
String[] values = {"4,8", "1,6", "7,8", "1,5"}
where I have to find the max of the second element and if there are more than two of the max ("4,8" and "7,8"), find the one with the min of the first. So the output of values should be a string "4,8"
I am new to JAVA and I am not sure how exactly to go about this. I tried to use string split and something like
int[] num = new int[values.length];
int[] num2 = new int[values.length];
for (int i = 0; i<values.length; i++){
String[] test = values[i].split(",");
int nummed = Integer.parseInt(test[0]);
int nummed2 = Integer.parseInt(test[1]);
num[i] = nummed;
num2[i] = nummed2;
//System.out.println(test[0]);
//System.out.println(test[1]);
}
but it is quickly becoming very complicated and I would need to know the index or maybe filter out data to find the min of the first item.

This should be enough
class Main {
public static void main(String args[]) {
String[] values = {"4,8", "1,6", "7,8", "1,5"}; // try {"4,8", "1,6", "7,8", "1,5", "1,9"}
int right = Integer.MIN_VALUE;
int left = Integer.MAX_VALUE;
for (int i = 0; i<values.length; i++){
String[] test = values[i].split(",");
int nummed = Integer.parseInt(test[0]);
int nummed2 = Integer.parseInt(test[1]);
if (nummed2 >= right) {
if (right != nummed2) {
left = Integer.MAX_VALUE;
}
right = nummed2;
if (nummed < left) {
left = nummed;
}
}
}
System.out.println(left + "," + right);
}
}

public class StringManipulation {
public static void main(String args[]) {
System.out.println(output());
}
private static String output() {
String[] values = {"4,8", "1,6", "7,8", "1,5"};
int max = Integer.MIN_VALUE;
int first = Integer.MAX_VALUE;
for(int i = 0; i < values.length; i++) {
String[] arr = values[i].split(",");
if(Integer.parseInt(arr[1]) >= max){
max = Integer.parseInt(arr[1]);
first = Integer.parseInt(arr[0]) < first ? Integer.parseInt(arr[0]):first;
}
}
return (first) + "," + (max);
}
}
There could be multiple approaches to this problem. Given my understanding of the question, this is one of the simplest solutions.

Here's a solution that makes use of the fluent Comparator api, stream api and BigDecimals:
String[] values = {"4,8", "1,6", "7,8", "1,5"};
// create a custom comparator
Comparator<BigDecimal> comparator = Comparator
// first, comparing only the right side - the remainders
.comparing((BigDecimal num) -> num.remainder(BigDecimal.ONE))
// then, comparing the left side - the decimal part
.thenComparing(num -> num.setScale(0, RoundingMode.DOWN));
// find the max value using java stream api
Arrays.stream(values)
// replace commas with dots
.map(num -> num.replace(',', '.'))
// map values to bigdecimal
.map(BigDecimal::new)
// find the max element by our custom comparator
.max(comparator)
// print if an element is found (if the array was not empty)
.ifPresent(System.out::println);

Continuing with your solution, Tested. Works as expected, It was hard to type it all on mobile though.
public static void main(String arg[])
{
String[] values = {"4,8", "1,6", "7,8", "1,5","2,8"};
int[] num = new int[values.length];
int[] num2 = new int[values.length];
for (int i = 0; i<values.length; i++){
String[] test = values[i].split(",");
int nummed = Integer.parseInt(test[0]);
int nummed2 = Integer.parseInt(test[1]);
num[i] = nummed;
num2[i] = nummed2;
//System.out.println(test[0]);
//System.out.println(test[1]);
}
int max=0;
int min=0;
for(int i=0;i<num2.length;i++)
{
if(num2[i]>max) {
max =num2[i];
min=num[i];
}
else if(num2[i]==max)
min = min>=num[i]?num[i]:min;
}
System.out.println(min+","+max);
}
}

Related

Java Deque (Finding the max number of unique integers from subarrays.)

I was trying to solve a HackerRank problem on Java Deque. My code passed all the cases apart from the ones which have 100,000 inputs.
Problem: In this problem, you are given N integers. You need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.
--->So we wre given N integers, and need to find the number of "unique integers" in each contagious subarray(of size M). And then print the maximum number of those "unique Integers".
link: https://www.hackerrank.com/challenges/java-dequeue/problem
My Code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<>();
HashSet<Integer> set = new HashSet<>();
int n = in.nextInt();
int m = in.nextInt();
int max=0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
set.add(num);
if(i>=m-1){
if(set.size()>max)max=set.size();
Integer removed=(Integer)deque.removeFirst();
set.remove(removed);
set.add((Integer)deque.peek());
}
}
System.out.println(max);
}
Please tell me where my code went wrong.
What is the point of this line?
set.add((Integer)deque.peek());
I don't see anything in your code that is slow. I just wonder how you can keep track of unique numbers by using a set, given that a set only tells you if there is such a number (but not how many occurrences of the same number there are). And you don't want to keep scanning the deque to see if the number being removed is the last one.
I don't think this is great/fast code, but it seems to pass the test-cases. I keep a count of how many of each integer there is in the window by using a map (and use some of your code).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>();
HashMap<Integer, Integer> counts = new HashMap<>();
int n = in.nextInt();
int m = in.nextInt();
int max = 0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
int count = counts.getOrDefault(num, 0);
counts.put(num, ++count);
if (i >= m - 1) {
if (counts.size() > max) max = counts.size();
Integer removed = deque.removeFirst();
int removing = counts.get(removed);
removing--;
if (removing == 0) {
counts.remove(removed);
} else {
counts.put(removed, removing);
}
}
}
System.out.println(max);
}
}
Just wanted to share how I solved it in case it helps.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque();
Set<Integer> integers = new HashSet<>();
int n = in.nextInt();
int m = in.nextInt();
long result = 0;
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.add(num);
integers.add(num);
if (deque.size() == m) {
long currentSize = integers.size();
if (currentSize > result) {
result = currentSize;
}
Integer removed = (Integer) deque.pollFirst();
if (!deque.contains(removed)) {
integers.remove(removed);
}
}
}
System.out.println(result);
}
We can optimize the space a little bit by avoiding the hashmap all together, but it seems like Hackerrank does not care about that. Any how I am putting my solution here which can solve this problem by using using a map.
private int countUniqueNumsInSubarrays(int[] nums, int m) {
Deque<Integer> deque = new LinkedList<>();
int maxUniqueCount = 0;
for (int i = 0; i < nums.length; i++) {
// if deque's left entry is outside the window then pop it out
while (!deque.isEmpty() && i - deque.peekFirst() >= m) {
deque.removeFirst();
}
// this will make sure that the deque only contains unique numbers,
// this is essentially helps us avoid that extra hash map
while (!deque.isEmpty() && nums[deque.peekLast()] == nums[i]) {
deque.removeLast();
}
deque.addLast(i);
if (i >= m - 1) {
maxUniqueCount = Math.max(maxUniqueCount, deque.size());
}
}
return maxUniqueCount;
}
import java.io.*;
import java.util.*;
import java.util.stream.Stream;
public class Solution {
public static void main(String[] args) {
var sc = new Scanner(System.in);
var split = sc.nextLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
if (!(1 <= n && n <= 100_000)) {
System.exit(0);
}
if (!(1 <= m && m <= 100_000)) {
System.exit(0);
}
if (!(m <= n)) {
System.exit(0);
}
split = sc.nextLine().split(" ");
sc.close();
int maxNumUniqueInt = 0;
HashSet<Integer> dist = new HashSet<>();
Deque<Integer> deque = new ArrayDeque<>();
int[] arr = Stream.of(split).mapToInt(Integer::parseInt).toArray();
for (int i = 0; i < m; i++) {
deque.addLast(arr[i]);
dist.add(arr[i]);
}
int num = dist.size();
if (maxNumUniqueInt < num) {
maxNumUniqueInt = num;
}
for (int i = m; i < n; i++) {
deque.addLast(arr[i]);
dist.add(arr[i]);
int remove = deque.removeFirst();
if (!deque.contains(remove)) {
dist.remove(remove);
}
num = dist.size();
if (maxNumUniqueInt < num) {
maxNumUniqueInt = num;
}
// System.out.println(i + " | " + deque + " | " + dist + " | " + maxNumUniqueInt);
}
System.out.println(maxNumUniqueInt);
}
}
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Deque<Integer> deque = new ArrayDeque<>();
int n = in.nextInt();
int m = in.nextInt();
int maxUnique = 0;
Map<Integer, Boolean> uniqSet = new HashMap<>();
for (int i = 0; i < n; i++) {
int num = in.nextInt();
deque.addLast(num);
uniqSet.put(num, true);
if(deque.size() == m){
// int uniqueSize = new HashSet<>(deque).size();
int uniqueSize = uniqSet.size();
maxUnique = Math.max(maxUnique, uniqueSize);
int x = deque.removeFirst();
if(!deque.contains(x)){
uniqSet.remove(x);
}
}
}
in.close();
System.out.println(maxUnique);
}
}

Convert a number-word (String) to its Integer Value

EDIT: right, I forgot to state the problem -- which is the fact that I get 0 as an output.
CONTEXT
My program aims to take a user-inputted number-word (1- 99) and output it as an integer (i.e. thirty-four = 34). I can't figure out where the error in my code is and need help:
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine(); //number in word-form (i.e. twenty six)
char[] charArray = word.toCharArray();//string to char array for word^
int divider = 0; //position of hyphen/space in charArray
All 2-word numbers are comprised of a tens value & a ones value. Assuming proper syntax [english], the word before the hyphen/space divider is the tens and the word following divider is the ones.
ARRAYS
//word values - components & syntax (1-99)
//ONES
public static final String[] wONES = {"one","two","three","four","five","six","seven","eight","nine"};
//TENS
public static final String[] wTENS = {null,"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
//TEENS
public static final String[] wTEENS = {"ten", "eleven", "twelve", "thirteen","fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
I've organized all the word-components into 3 different arrays: ones, tens, and teens.
//equivalent integer-array of above String arrays
//ONES
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
//TENS
public static final int[] nTENS = {0,20,30,40,50,60,70,80,90};
//TEENS
public static final int[] nTEENS = {10,11,12,13,14,15,16,17,18,19};
I created 3 other arrays that are the same as the above three arrays, except they store the integer values.
CODE
Here I separate the user-inputted String into two sections: the tens and the ones. So if the number was 72: 70 = tens and 2 = ones.
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
char[] tensArray = null; //array storing tens section of word (before divider)
for (int u = 0; u < divider; u++){
tensArray[u] = charArray[u];
}
String tens = new String(tensArray); //convert char array to String
char[] onesArray = null; //array storing ones section of word (after divider)
for (int u = divider + 1; u > divider && u < charArray.length; u++){
onesArray[u] = charArray[u];
}
String ones = new String(onesArray);
//searches for matches in String array for tens
for(int u = 0; u < wTENS.length; u++){
if(tens.equals(wTENS[u])){
tensValue = nTENS[u];
total += tensValue;
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++){
if(ones.equals(wONES[u])){
onesValue = nONES[u];
total += onesValue;
In your current code you are doing char[] tensArray = null; which should be something like char[] tensArray = new char[10]; or else you end up with NPE.
It might not be most efficient but here is a simple and better approach to your problem.
Read the line and split it on white space (assuming you are separating your words by a space).
Search each of the tokens you get after split in the above lists and add the corresponding number (same index) to your answer.
Print the answer.
Here is the code snippet:
class Main
{
public static final String[] wONES = {"one","two","three","four","five","six",
"seven","eight","nine"};
public static final String[] wTENS = {"ten","twenty","thirty","forty","fifty","sixty",
"seventy","eighty","ninety"};
public static final String[] wTEENS = {"eleven", "twelve", "thirteen","fourteen",
"fifteen", "sixteen", "seventeen", "eighteen",
"nineteen"};
public static final int[] nONES = {1,2,3,4,5,6,7,8,9};
public static final int[] nTENS = {10,20,30,40,50,60,70,80,90};
public static final int[] nTEENS = {11,12,13,14,15,16,17,18,19};
public static void main (String[] args) throws Exception
{
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine();
int answer = 0;
/* Assuming you are giving space between words */
for(String s : word.split(" ")) {
/* Scan wONES */
for(int i = 0; i < wONES.length; i++) {
if(wONES[i].equalsIgnoreCase(s)) {
answer += nONES[i];
continue;
}
}
/* Scan wTENS */
for(int i = 0; i < wTENS.length; i++) {
if(wTENS[i].equalsIgnoreCase(s)) {
answer += nTENS[i];
continue;
}
}
/* Scan wTEENS */
for(int i = 0; i < wTEENS.length; i++) {
if(wTEENS[i].equalsIgnoreCase(s)) {
answer += nTEENS[i];
continue;
}
}
}
System.out.println("Result: " + answer);
}
}
Input:
thirty four
Output:
34
You have an interesting approach to this problem. A couple of things to change:
I don't see where you set your divider index.
You seem to be doing a lot of work with character arrays, so I'm guessing you're coming from a different language. Sticking with Strings will work fine.
You don't address the "teens". This looks like a simple oversight.
I've added those fixes while attempting maintain the original approach:
public static void main(String [] args) {
Scanner scInput = new Scanner(System.in);
String word = scInput.nextLine();
int total = 0;
int tensValue = 0; //number's tens value (i.e. 30)
int onesValue = 0; //ones value (i.e. 3)
int divider = word.indexOf('-');
String tens = null;
String ones = null;
if (divider != -1) {
tens = word.substring(0, divider);
ones = word.substring(divider + 1);
} else {
ones = word;
}
//searches for matches in String array for tens
if (tens != null) {
for (int u = 0; u < wTENS.length; u++) {
if (tens.equals(wTENS[u])) {
tensValue = nTENS[u];
total += tensValue;
}
}
}
//searches for matches in String array for ones
for(int u = 0; u < wONES.length; u++) {
if (ones.equals(wONES[u])) {
onesValue = nONES[u];
total += onesValue;
}
}
// if a "teen" override what's in total
for(int u = 0; u < wTEENS.length; u++) {
if (ones.equals(wTEENS[u])) {
total = nTEENS[u];
}
}
System.out.println(total);
}

not storing text data into java array using scanner

My code is just printing out the last number from the list I create in a different program.
I need help storing the data into an array so I can sort it after.
edit: I need to take data from a file which is 'numbers.txt' and store it into an array.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[0] = numberArray;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}
Correction in the code.
1.) Inside while loop, list[0] = numberArray;, will keep adding elements on the same index 0, so lat value will override. SO something like list[i] = numberArray; will work, and increement i inside while loop. Take care of ArrayIndexOutOfBound Exception here.
public static void main(String[] args) throws Exception {
int numberArray = 0;
int[] list = new int[16];
File numbers = new File("numbers.txt");
int i =0;
// Check for arrayIndexOutofBound Exception. SInce size is defined as 16
try (Scanner getText = new Scanner(numbers)) {
while (getText.hasNext()) {
numberArray = getText.nextInt();
list[i] = numberArray;
i++;
}
getText.close();
}
System.out.println(numberArray);
int sum = 0;
for (int i = 0; i < list.length; i++) {
sum = sum + list[i];
}
System.out.println(list);
}
}

Smart way to generate permutation and combination of String

String database[] = {'a', 'b', 'c'};
I would like to generate the following strings sequence, based on given database.
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
...
I can only think of a pretty "dummy" solution.
public class JavaApplication21 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
String query = "a";
StringBuilder query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
query = query_sb.toString();
System.out.println(query);
}
query = "aa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
query = query_sb.toString();
System.out.println(query);
}
}
query = "aaa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
for (int c = 0; c < database.length; c++) {
query_sb.setCharAt(2, database[c]);
query = query_sb.toString();
System.out.println(query);
}
}
}
}
}
The solution is pretty dumb. It is not scale-able in the sense that
What if I increase the size of database?
What if my final targeted print String length need to be N?
Is there any smart code, which can generate scale-able permutation and combination string in a really smart way?
You should check this answer: Getting every possible permutation of a string or combination including repeated characters in Java
To get this code:
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else {
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++){
for(int j = 0; j < allSublists.length; j++){
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}
public static void main(String[] args){
String[] database = {"a","b","c"};
for(int i=1; i<=database.length; i++){
String[] result = getAllLists(database, i);
for(int j=0; j<result.length; j++){
System.out.println(result[j]);
}
}
}
Although further improvement in memory could be made, since this solution generates all solution to memory first (the array), before we can print it. But the idea is the same, which is to use recursive algorithm.
This smells like counting in binary:
001
010
011
100
101
...
My first instinct would be to use a binary counter as a "bitmap" of characters to generate those the possible values. However, there are several wonderful answer to related questions here that suggest using recursion. See
How do I make this combinations/permutations method recursive?
Find out all combinations and permutations - Java
java string permutations and combinations lookup
http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/
Java implementation of your permutation generator:-
public class Permutations {
public static void permGen(char[] s,int i,int k,char[] buff) {
if(i<k) {
for(int j=0;j<s.length;j++) {
buff[i] = s[j];
permGen(s,i+1,k,buff);
}
}
else {
System.out.println(String.valueOf(buff));
}
}
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
char[] buff = new char[database.length];
int k = database.length;
for(int i=1;i<=k;i++) {
permGen(database,0,i,buff);
}
}
}
Ok, so the best solution to permutations is recursion. Say you had n different letters in the string. That would produce n sub problems, one for each set of permutations starting with each unique letter. Create a method permutationsWithPrefix(String thePrefix, String theString) which will solve these individual problems. Create another method listPermutations(String theString) a implementation would be something like
void permutationsWithPrefix(String thePrefix, String theString) {
if ( !theString.length ) println(thePrefix + theString);
for(int i = 0; i < theString.length; i ++ ) {
char c = theString.charAt(i);
String workingOn = theString.subString(0, i) + theString.subString(i+1);
permutationsWithPrefix(prefix + c, workingOn);
}
}
void listPermutations(String theString) {
permutationsWithPrefix("", theString);
}
i came across this question as one of the interview question. Following is the solution that i have implemented for this problem using recursion.
public class PasswordCracker {
private List<String> doComputations(String inputString) {
List<String> totalList = new ArrayList<String>();
for (int i = 1; i <= inputString.length(); i++) {
totalList.addAll(getCombinationsPerLength(inputString, i));
}
return totalList;
}
private ArrayList<String> getCombinationsPerLength(
String inputString, int i) {
ArrayList<String> combinations = new ArrayList<String>();
if (i == 1) {
char [] charArray = inputString.toCharArray();
for (int j = 0; j < charArray.length; j++) {
combinations.add(((Character)charArray[j]).toString());
}
return combinations;
}
for (int j = 0; j < inputString.length(); j++) {
ArrayList<String> combs = getCombinationsPerLength(inputString, i-1);
for (String string : combs) {
combinations.add(inputString.charAt(j) + string);
}
}
return combinations;
}
public static void main(String args[]) {
String testString = "abc";
PasswordCracker crackerTest = new PasswordCracker();
System.out.println(crackerTest.doComputations(testString));
}
}
For anyone looking for non-recursive options, here is a sample for numeric permutations (can easily be adapted to char. numberOfAgents is the number of columns and the set of numbers is 0 to numberOfActions:
int numberOfAgents=5;
int numberOfActions = 8;
byte[][]combinations = new byte[(int)Math.pow(numberOfActions,numberOfAgents)][numberOfAgents];
// do each column separately
for (byte j = 0; j < numberOfAgents; j++) {
// for this column, repeat each option in the set 'reps' times
int reps = (int) Math.pow(numberOfActions, j);
// for each column, repeat the whole set of options until we reach the end
int counter=0;
while(counter<combinations.length) {
// for each option
for (byte i = 0; i < numberOfActions; i++) {
// save each option 'reps' times
for (int k = 0; k < reps; k++)
combinations[counter + i * reps + k][j] = i;
}
// increase counter by 'reps' times amount of actions
counter+=reps*numberOfActions;
}
}
// print
for(byte[] setOfActions : combinations) {
for (byte b : setOfActions)
System.out.print(b);
System.out.println();
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
import java.util.*;
public class Permutation {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("ENTER A STRING");
Set<String> se=find(in.nextLine());
System.out.println((se));
}
public static Set<String> find(String s)
{
Set<String> ss=new HashSet<String>();
if(s==null)
{
return null;
}
if(s.length()==0)
{
ss.add("");
}
else
{
char c=s.charAt(0);
String st=s.substring(1);
Set<String> qq=find(st);
for(String str:qq)
{
for(int i=0;i<=str.length();i++)
{
ss.add(comb(str,c,i));
}
}
}
return ss;
}
public static String comb(String s,char c,int i)
{
String start=s.substring(0,i);
String end=s.substring(i);
return start+c+end;
}
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!

add values to double[] arraylist

I have the following array
ArrayList<double[]> db_results = new ArrayList<double[]>();
and I would like to add values like this
db_results.add(new double[] {0,1,2});
but in a loop like this
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
db_results.add(new double[] {val});
}
obviously this is adding a new array each time with the single value... so how do I get it to add all into one array?
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
Create the double[] first, add the numbers to it, and add that array to the List.
(The variable should likely be declared as a List, btw, not an ArrayList, unless you're specifically passing it to something that explicitly expects an ArrayList.)
With something like that :
max = 3;
double[] doubles = new double[max];
for ( int i = 0 ; i < max; ++i)
{
double val = Double.parseDouble(i);
doubles[i] = val;
}
db_results.add(doubles);
import java.util.Scanner;
class DarrayEx2
{
public static void main(String args[])
{
int a[][]=new int[3][3];
int r,c,sumr;
Scanner s=new Scanner(System.in);
for(r=0;r<a.length;r++)
{
for (c=0;c<a.length ;c++ )
{
System.out.println("enter an element");
a[r][c]=s.nextInt();
}
}
for(r=0;r<a.length;r++)
{
sumr=0;
System.out.println("elements in a["+r+"] row is");
for (c=0;c<a[1].length ;c++ )
{
System.out.println(" "+a[r][c]);
sumr = sumr+a[r][c];
}
System.out.println(" = "+sumr);
System.out.println(" ");
}
}
}
source : http://www.exceptionhandle.com/portal/java/core-java/part-12-arrays.htm

Categories

Resources