How would I add array index's together? - java

I've read data from a text file and stored them in an array called 'boat1'.
There are nine values and I am trying to add together index's [4] to [9] to get a total value.
How would I go about doing this?
Here is my code:
String[] boat1 = new String[9];
int i = 0;
while(reader.hasNextLine() && i < boat1.length) {
boat1[i] = reader.nextLine();
i++;
}
I've tried to change the values to an integer but it doesn't seem to be working..?
Thank you.

You got to parse before adding:
int a = Integer.parseInt(boat1[3]);
int b = Integer.parseInt(boat1[8]);
int c = a + b;
Your array boat1 is a String array and not an int array. You need to convert it. Note that boat1 is size of 9 meaning that it has indexes from 0 to 8. Java is 0 based.
If you want to add up a sequence of numbers (ex. 3,4,...,7,8), just loop through the indexes you want to add up and keep track of a total.

Because your array is an String type it needs to be converted to int, After you do that you will have something like this example assuming that I'm making up those values , but it should still work for your code :). Don't forget to add the for loop at the end as I have it on my code so it can find the sum of your indexes. Hope it can help you!
int sum = 0;
int[] boat = new int[9];
boat[0] = 2;
boat[1] = 4;
boat[2] = 6;
boat[3] = 8;
boat[4] = 10;
boat[5] = 12;
boat[6] = 14;
boat[7] = 16;
boat[8] = 18;
for(int i = 3; i < boat.length ; i++){
sum += boat[i];
}
System.out.println(sum);

Related

How to rotate 2-D Array in Java

[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]

Storing in an array

I'm trying to get a string to read a file, that then stores all the digits in an array that can be recalled one by one in another loop. Name the array digitStorage please :D Here's my current bit of code:
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
digit = pictureFile.substring(i, i+1);
else
digit = pictureFile.substring(39998,39999);
My question :
What to do, how could I do this, how would I get it to read each digit (single integers) 1 by 1 and then store them 1 by 1 in an array that could be later recalled, each number corresponds to a color that would be used to sketch a picture in a graphics window (there are 40,000 single digit integers in a file that i've already worked out how to read) ?
Cheers.
As you have mentioned that you have already read the file and you want to store it in some kind of array. Below code will work.
List<String> list = new ArrayList<String>();
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
list.add(pictureFile.substring(i, i+1));
else
list.add(pictureFile.substring(39998,39999));
}
If you want List of Integer then us.
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i <= 40000 ; i++) {
String digit;
if ( i <=39998)
list.add(Integer.parseInt(pictureFile.substring(i, i+1)));
else
list.add(Integer.parseInt(pictureFile.substring(39998,39999)));
}
You can iterate through list after this.
Your question is not very clear, but I believe this should do it:
int [] digitStorage = new int[40000];
for (int i = 0; i <= 40000 ; i++) {
if ( i <=39998)
int[i] = Integer.parseInt(pictureFile.substring(i, i+1));
else
int[i] = Integer.parseInt(pictureFile.substring(39998,39999));
Based on your comments and question, the easiest solution I can think of is to use String.toCharArray() and Character.digit(char, int) like
char[] chars = pictureFile.toCharArray();
int[] digitStorage = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
digitStorage[i] = Character.digit(chars[i], 10);
}
System.out.println(Arrays.toString(digitStorage));

Printing Java array -- only last element's value is shown, why?

Just to keep my skills sharp, I decided to write a small programme that prints out the values of an array, after being given two variables that each contain a different value.
My expectation was that each value would show onscreen, but this did not happen. Instead, only the last element's value was displayed onscreen (in the code below, being the number "2" --> That is an integer, not a string).
Why is this?
Also, why does dynamic initialisation produce the result I wish, but not the way I do it in the code?
Many thanks.
int[] arrayOne;
arrayOne = new int[2];
int numOne = 1;`
int numTwo = 2;`
for (int i = 0; i < arrayOne.length; i++) {`
arrayOne[i] = numOne;
arrayOne[i] = numTwo;
System.out.println(arrayOne[i]);
}
If you want to put the values of two variables into an array, you need to use two assignments:
arrayOne[0] = numOne;
arrayTwo[1] = numTwo;
Now you can use a for loop to print out the contents of the array.
This kind of defeats the purpose of using an array, though.
You're setting different values to same location, causing only last value to be saved.
Your code similar to doing:
arrayOne[0] = 1;
arrayOne[0] = 2;
After these two lines, arrayOne[0] will hold the value of 2.
If you want to put these two values, you need to put them in different places:
arrayOne[0] = 1;
arrayOne[1] = 2;
In Java (and in almost any language I know), an array can only contain one vale per cell i.e. if you do "array[i] = 1" and after "array[i] = 2" , then the i-cell will CHANGE its value from 1 to 2, not append the value 2 after the 1. In the end, youre array will contain numTwo in every single cell.
If you want to initialize the array with a different value in each cell, I'm afraid you need to do it manually, not using the loop.
You need to do the population of your array before you iterate through it with the loop.
arrayOne[0] = numOne;
arrayOne[1] = numTwo;
Then do your loop:
for (int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
Many ways to initialize an array...
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
Or:
int[] a = new int[2];
for( int i = 0; i < a.length; i++ ){
a[i] = i + 1;
}
Or:
int[] a = new int[]{ 1, 2 };
Or.
int valOne = 1;
int valTwo = 2;
int[] a = new int[]{ valOne, valTwo };
Take care when you see more than one assignment to the same array element in a loop as you have it before the println. Is this what you want? The second one wins and sets the current (i-th) element to 2.
You need to do something like this:
public class demo{
private static int i = 0;
private static int[] demo = new int[10];
public static void main(String[] args){
for(int i = 0; i < 10; i++){
addElementToArray(i);
}
for(int i = 0; i < demo.length; i++){
System.out.println(demo[i]);
}
addElementToArray(i);
}
public static void addElementToArray(int input){
try{
demo[i] = input;
i++;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't set the values inside the for-loop either, that is (imo) plain stupid, for what you are trying to achieve

int array to int number in Java

I'm new on this site and, if I'm here it's because I haven't found the answer anywhere on the web and believe me: I've been googling for quite a time but all I could find was how to convert a number to an array not the other way arround.
I'm looking for a simple way or function to convert an int array to an int number. Let me explain for example I have this :
int[] ar = {1, 2, 3};
And I want to have this:
int nbr = 123;
In my head it would look like this (even if I know it's not the right way):
int nbr = ar.toInt(); // I know it's funny
If you have any idea of how I could do that, that'd be awesome.
Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.
Result: 0
Loop 1: Result * 10 => 0, Result + 1 => 1
Loop 2: Result * 10 => 10, Result + 2 => 12
Loop 3: Result * 10 >= 120, Result + 3 => 123
This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.
You have to cycle in the array and add the right value.
The right value is the current element in the array multiplied by 10^position.
So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....
int res=0;
for(int i=0;i<ar.length;i++) {
res=res*10+ar[i];
}
Or
for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
res+=ar[i]*Math.pow(10, exp);
First you'll have to convert every number to a string, then concatenate the strings and parse it back into an integer. Here's one implementation:
int arrayToInt(int[] arr)
{
//using a Stringbuilder is much more efficient than just using += on a String.
//if this confuses you, just use a String and write += instead of append.
StringBuilder s = new StringBuilder();
for (int i : arr)
{
s.append(i); //add all the ints to a string
}
return Integer.parseInt(s.toString()); //parse integer out of the string
}
Note that this produce an error if any of the values past the first one in your array as negative, as the minus signs will interfere with the parsing.
This method should work for all positive integers, but if you know that all of the values in the array will only be one digit long (as they are in your example), you can avoid string operations altogether and just use basic math:
int arrayToInt(int[] arr)
{
int result = 0;
//iterate backwards through the array so we start with least significant digits
for (int n = arr.length - 1, i = 1; n >= 0; n --, i *= 10)
{
result += Math.abs(arr[n]) * i;
}
if (arr[0] < 0) //if there's a negative sign in the beginning, flip the sign
{
result = - result;
}
return result;
}
This version won't produce an error if any of the values past the first are negative, but it will produce strange results.
There is no builtin function to do this because the values of an array typically represent distinct numbers, rather than digits in a number.
EDIT:
In response to your comments, try this version to deal with longs:
long arrayToLong(int[] arr)
{
StringBuilder s = new StringBuilder();
for (int i : arr)
{
s.append(i);
}
return Long.parseLong(s.toString());
}
Edit 2:
In response to your second comment:
int[] longToIntArray(long l)
{
String s = String.valueOf(l); //expand number into a string
String token;
int[] result = new int[s.length() / 2];
for (int n = 0; n < s.length()/2; n ++) //loop through and split the string
{
token = s.substring(n*2, (n+2)*2);
result[n] = Integer.parseInt(token); //fill the array with the numbers we parse from the sections
}
return result;
}
yeah you can write the function yourself
int toInt(int[] array) {
int result = 0;
int offset = 1;
for(int i = array.length - 1; i >= 0; i--) {
result += array[i]*offset;
offset *= 10;
}
return result;
}
I think the logic behind it is pretty straight forward. You just run through the array (last element first), and multiply the number with the right power of 10 "to put the number at the right spot". At the end you get the number returned.
int nbr = 0;
for(int i = 0; i < ar.length;i++)
nbr = nbr*10+ar[i];
In the end, you end up with the nbr you want.
For the new array you gave us, try this one. I don't see a way around using some form of String and you are going to have to use a long, not an int.
int [] ar = {2, 15, 14, 10, 15, 21, 18};
long nbr = 0;
double multiplier = 1;
for(int i = ar.length-1; i >=0 ;i--) {
nbr += ar[i] * multiplier;
multiplier = Math.pow(10, String.valueOf(nbr).length());
}
If you really really wanted to avoid String (don't know why), I guess you could use
multiplier = Math.pow(10,(int)(Math.log10(nbr)+1));
which works as long as the last element in the array is not 0.
Use this method, using a long as your input is to large for an int.
long r = 0;
for(int i = 0; i < arr.length; i++)
{
int offset = 10;
if(arr[i] >= 10)
offset = 100;
r = r*offset;
r += arr[i];
}
This checks if the current int is larger than 10 to reset the offset to 100 to get the extra places required. If you include values > 100 you will also need to add extra offset.
Putting this at end of my post due to all the downvotes of Strings...which is a perfectly legitimate answer...OP never asked for the most efficient way to do it just wannted an answer
Loop your array appending to a String each int in the array and then parse the string back to an int
String s = "";
for(int i = 0; i < arr.length; i++)
s += "" + arr[i];
int result = Integer.parseInt(s);
From your comment the number you have is too long for an int, you need to use a long
String s = "";
for(int i = 0; i < arr.length; i++)
s += "" + arr[i];
long result = Long.parseLong(s);
If you can use Java 1.8, stream API makes it very simple:
#Test
public void arrayToNumber() {
int[] array = new int[]{1,2,3,4,5,6};
StringBuilder sb = new StringBuilder();
Arrays.stream(array).forEach(element -> sb.append(element));
assertThat(sb.toString()).isEqualTo("123456");
}
you can do it that way
public static int[] plusOne(int[] digits) {
StringBuilder num= new StringBuilder();
PrimitiveIterator.OfInt primitiveIterator = Arrays.stream(digits)
.iterator();
while (primitiveIterator.hasNext()) {
num.append(primitiveIterator.nextInt());
}
int plusOne=Integer.parseInt(String.valueOf(num))+1;
return Integer.toString(plusOne).chars().map(c -> c-'0').toArray();
}
BE SIMPLE!!!
public static int convertToInteger(int... arr) {
return Integer.parseInt(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining()));
}
this also possible to convert an Integer array to an int array
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i].intValue();
}

How to return 5 random "Powerball" numbers in Java

Trying to return 5 random numbers between 1 and 42 in Java.
I currently have logic to return a single number (putting it into an ArrayList, but I'd like to do away with that.) I'm stumped on implementation to return 5 random numbers. Would I need 5 for loops?
for (int i = 0; i < 10; i++) {
int r = (int) (Math.random() * 42 + 1);
}
I've seen some other related examples here and they seem more complex than what my needs dictate. However, I could be wrong.
Simply place each random number into an array and return the array...
public int[] powerBalls() {
int[] balls = new int[5];
for (int index = 0; index < 5; index++) {
balls[index] = (int) (Math.random() * 42) + 1;
}
return balls;
}
You can use the Set to generate 5 Unique Random numbers.
Random random = new Random();
Set randomNumbers = new HashSet<Integer>();
while(randomNumbers.size()< 5) {
randomNumbers.add(random.nextInt(42)+1);
}
Since you've mentioned that you're using an ArrayList which will hold all the random numbers, you could just add all the elements present in randomNumbers set to your ArrayList.
Update:-
To suit your needs, you need to do something like this:-
Random random = new Random();
Set<String> set = new HashSet<String>();
while(set.size()< 5) {
set.add(String.valueOf(random.nextInt(42)+1));
}
fortuneList3.addAll(set);
Be careful! Each number can be taken only one time. With your solution it is possible to get same number more than one time.
Other solution (and here you can't have same numer more than one time) is to create array with all numbers, shuffle it and take first 5:
public int[] powerBalls() {
// create array with all numbers
List<Integer> balls = new ArrayList<Integer>(42);
for (int i = 1; i <= 42; i++)
balls.add(i);
// shuffle
Collections.shuffle(balls);
// take first 5
int[] result = new int[5];
for (int i = 0; i < 5; i++)
result[i] = balls.get(i);
return result;
}
Try it like this:
IntArray = new int[5]; //Create an array
for (int i = 0; i < 5; i++) {
IntArray[i] = (int) (Math.random() * 42 + 1);
}
Store the numbers in array and return that array.
int []randArray;
randArray = new int[5];
for (int i = 0; i < 5; i++) { //for 5 random numbers
randArray[i] = (int) (Math.random() * 42 + 1);
}
//now return this array "randArray"
It's a straight forward approach.
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 5; i++)
{
while(true)
{
int r = (int) (Math.random() * 42 + 1);
if (!generated.contains(r))
{
generated.add(r);
break;
}
}
}
Just throwing my 2 cents in. I recently made a jQuery Plugin, appropriately named "Powerball". I'll share with ya the formula i'm using as well as link ya my plugin. Not sure why anyone would really need this. I did it just for fun! LoL!
The Function
function getNumbers() {
var a=[]; // array to return
for(i=1;5>=i;i++){ // for loop to get first 5 numbers
var b = Math.floor(Math.random()*59)+1; // set #
while (a.indexOf(b) > -1) { b = Math.floor(Math.random()*59)+1; } // reset # if already used
a.push(b); // add number to array
}
a.push(Math.floor(35*Math.random())+1); // add ball 6 number
return a; // 0 index array will have a length of 6, [0-4] being whiteball numbers, [5] being the red ball
}
The Plugin
jsFiddle
Contains the plugin between comment lines
Shows example use
Use is as easy as $("element").powerball(). However, only one method exist for it at the moment, $("element").powerball("setNumbers"). That method simply resets the numbers shown in the p tags.
Style: a note!
All styling is done through a style tag added to the header upon initialization. This means there's no need for extra files to add, but it also gives the ease of custom styling. See more about styling in the jsFiddle!

Categories

Resources