I don't understand the labelled break statement, which for statement. Does it stop the one just below it or the one furthest from it?
Also, I do not understand why j is initialized twice, why not just initialize it inside the for statement? Furthermore, when j < arrayOfInts[i].length can't j be an element from array 0 (that is until it increments) because j can be an element from an array lower that arrayOfInt[i] right?
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
Related
I would like to know, how to find out which column in the 2D-array has got the largest sum. How would I approach this?
public static void main(String args[]) {
int[][] array = {
{ 132, 154, 118 },
{ 355, 101, 50 },
{ 432, 143, 365 },
{ 462, 234, 185 }
};
}
You could go with a nested for loop
int maxCol = 0;
int valOfMaxCol = 0;
for(int i = 0; i < 3; i++){
int sum = 0;
for(int j = 0; j < array.length; j++){
sum += array[j][i];
}
if(sum > valOfMaxCol){
valOfMaxCol = sum;
maxCol = i;
}
}
System.out.println("Max Col is " + (maxCol + 1) + " with the value " + valOfMaxCol);
I want to break a one-dimensional array in rows.
Array dimension 50. I need to output the array to the console with 10 elements per line. (lang Java 1.8) Thanks!
public void print() {
for (int i = 0; i < arr.length; i++) {
if (i<=9) {
System.out.print(arr[i] + " ");
}else {
System.out.print("\r");
}
}
}
Sample output
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
etc....
You can see it from 2 differents point of view
Each 10 numbers, print a new line : when the index ends with a 9 you reach ten elements so you print a new line println()
public void print() {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
if (i % 10 == 9) {
System.out.println();
}
}
}
Print enough number of line and on each one : print 10 elements
public void print() {
for (int i = 0; i < arr.length / 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(arr[i * 10 + j] + " ");
}
System.out.println();
}
}
Code for any number of elements per line:
public void print(int elementsPerLine) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i % elementsPerLine == 0 && i > 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
Use the following code,
public static void printResult(int[][] result)
{
for(int i=0; i<5; i++)
{
for(int j=0; j<10; j++)
{
System.out.print(result[i][j] + ", ");
}
System.out.println();
}
}
public static int[][] modifyArray( int[] singleArray )
{
int columns = 10;
int rows = singleArray.length/10;
int[][] result = new int[rows][columns];
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
result[i][j] = singleArray[columns*i + j];
}
}
return result;
}
public static void main(String[] args)
{
int[] singleArray = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
int[][] result = modifyArray( singleArray);
printResult( result );
}
You must use the modulo operator
https://en.wikipedia.org/wiki/Modulo_operation
public void print() {
for (int i = 0; i < arr.length; i++) {
if (i%10 == 0) {
System.out.print("\r");
}else {
System.out.print(arr[i] + " ");
}
}
}
Maybe you could write something like
if (i % 10 == 0)
System.out.print("\r");
}
System.out.print(arr[i] + " ");
Take slices of 10 items into a new array each time and print that array:
int count = 10;
int iterations = (arr.length / count) + ((arr.length % count) > 0 ? 1 : 0);
for (int i = 1; i <= iterations; i++) {
int[] slice = new int[count];
System.arraycopy(arr, (i - 1) * count, slice, 0, i == iterations ? (array.length % count) : count);
System.out.println(Arrays.toString(slice));
}
The above code works for any value of count.
Take a look at a code down below:
public class PrintEach10thElements {
/**
* #param args the command line arguments
*/
static List<Integer> arrays = new ArrayList<>();
public static void main(String[] args) {
//create 50 elements in an array
for (int i = 0; i <= 49; i++) {
arrays.add(i);
}
for (int g = 0; g < arrays.size(); g++) {
if ( arrays.get(g) % 10 != 0) {
System.out.print(arrays.get(g) + " ");
} else {
System.out.println();
System.out.print(arrays.get(g) + " ");
}
}
}
}
If you don't mind using a Guava library, you can also do this
List<Integer> myList = Arrays.asList(myArray);
System.out.println(Lists.partition(myList, 10).stream()
.map(subList -> subList.stream()
.map( Object::toString )
.collect(Collectors.joining(" ")))
.collect(Collectors.joining("\n")));
The goal of the code is to find the numbers that add up to the targetNumber. For example, if the targetNumber = 9 then the code should get the first two occuring indexes of the numbers that add up to the targetNumber. When I run my code, the output looks like the following:
The indexes are 10 and 1
What's wrong with the logic of the code? Thanks in advance!
public class TwoSum {
public static void main(String[] args){
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
int index1 = 0;;
int index2 = 0;
for(int i = 0; i < myArray.length; i++){
for(int j = 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
index1 = i;
index2 = j;
break;
}
}
}
System.out.println("The indexes are " + index1 + " and " + index2);
}
}
When you break, you only break out of the inner loop, so instead of printing out 1 and then 10, the outer loop continues, terminating naturally, and resulting in the print out of index 10 then index 1.
An interesting result of this is that your code essentially finds the last pair of numbers that sum to targetNumber, rather than the first. If you made your for loops count down instead of up, the code should spit out the correct values, although it wouldn't be very efficient...
I believe you're expecting indexes 0 and 8 (values 1 and 8). The problem is that your break statement only breaks from the inner loop and not the outer loop. You need to use a flag to know that you also should break from the outer loop. Also consider printing a message if no match is found.
public static void main(String[] args) throws Exception {
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
int index1 = 0;
int index2 = 0;
boolean stop = false;
for (int i = 0; i < myArray.length && !stop; i++) {
for (int j = i + 1; j < myArray.length && !stop; j++) {
if (myArray[i] + myArray[j] == targetNumber) {
stop = true;
index1 = i;
index2 = j;
}
}
}
System.out.println(stop
? "The indexes are " + index1 + " and " + index2
: "No match found");
}
Or just print the results inside the inner loop and use a return instead of a break. This way you don't have to use a flag.
public static void main(String[] args) throws Exception {
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
for(int i = 0; i < myArray.length; i++){
for(int j = i + 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
System.out.println("The indexes are " + i + " and " + j);
return;
}
}
}
System.out.println("No match found");
}
Results:
The indexes are 0 and 8
To make the code a little cleaner; that is, entirely foregoing the break statement, you should introduce a boolean variable called found to your loops. This way, you can break out of both of them more intuitively if you find your first match.
boolean found = false;
for(int i = 0; i < myArray.length && !found; i++){
for(int j = 1; j < myArray.length && !found; j++){
if(myArray[i] + myArray[j] == targetNumber){
found = true;
index1 = i;
index2 = j;
}
}
}
System.out.println("The indexes are " + index1 + " and " + index2);
If you're ever curious about what other pairs of numbers add up to your target, create a Pair<T> class which can store that kind of info. You wouldn't break out of any loops as you're essentially bruteforcing the entire thing.
class Pair<T> {
final T firstValue;
final T secondValue;
Pair(T firstValue, T secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
public T getFirstValue() {
return firstValue;
}
public T getSecondValue() {
return secondValue;
}
#Override
public String toString() {
return "{" + firstValue + ", " + secondValue + "}";
}
}
// later in your code
List<Pair<Integer>> pairs = new ArrayList<>();
for(int i = 0; i < myArray.length; i++){
for(int j = 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
pairs.add(new Pair<>(i, j));
}
}
}
System.out.println("The indexes are " + pairs);
The above prints out:
The indexes are [{0, 8}, {1, 7}, {1, 10}, {5, 7}, {5, 10}, {7, 1}, {7, 5}, {10, 1}, {10, 5}]
The break statement is breaking the inner loop but not the outer one. So its getting the last result of 3 and 6 instead of the 1 and 8.
A more appropriate way may be:
bool found=false;
for(int i = 0; i < myArray.length; i++){
if(!found){
for(int j = 1; j < myArray.length; j++){
if(myArray[i] + myArray[j] == targetNumber){
index1 = i; index2 = j;
found=true;
break;
} } }}
There are three things that are wrong with your code:
According to specification, you want to find first matching indices, while
you actually are finding last. That happens because break breaks only inner loop. The easy fix is to use label (outer:). Although the cleaner approach would be using dedicated method to do the search and return the first matched value.
You are checking pairs of indices twice and also checking pairs of the same index. The idiomatic approach that eliminates this redundancy is to start nested loop from the current value of the index of the outer loop (j = i) or (j = i + 1) if you don't want to have pairs of the same index (i, i).
You are not considering the situation when no matching index is found. In this case you will show that (0,0) is the result.
Here is your code fixed:
public static class TwoSum {
public static void main(String[] args) {
int[] myArray = {1, 6, 43, 22, 4, 6, 4, 3, 8, 7, 3};
int targetNumber = 9;
int index1 = -1;
int index2 = -1;
outer:
for (int i = 0; i < myArray.length; i++) {
for (int j = i + 1; j < myArray.length; j++) {
if (myArray[i] + myArray[j] == targetNumber) {
index1 = i;
index2 = j;
break outer;
}
}
}
if (index1 >= 0) {
System.out.println("The indexes are " + index1 + " and " + index2 + "(Values " + myArray[index1] +
" and " + myArray[index2] + ")");
} else {
System.out.println("Not found");
}
}
}
I am just sorting an array and need some advice on the sorting and I also need help printing the array after I have sorted it. Also no, I do not want to use the Arrays utility.
Code:
package Sort;
public class SortCode {
static int[] intArray = {
12, 34, 99, 1, 89,
39, 17, 8, 72, 68};
int j = 0;
int i = 0;
void printArray(int[] arrayInts) {
System.out.println("Values before sorting:");
System.out.println("Index" + "\tValue");
for (; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} //for (int j)
} //void printArray
void sortArray() {
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
int i;
int k;
for (i = 0; i < intArray.length; i++) {
for (k = 0; k > intArray.length; k++) {
if (intArray[i] > intArray[k]) {
int firstNum = intArray[i];
int secondNum = intArray[k];
intArray[i] = secondNum;
intArray[k] = firstNum;
} //if
} //for
} //for
} //void sortArray
} //class BranchCode
Change sign > for < inside for (k = 0; k > intArray.length; k++) {
Probably it should help you
You would be able to find different sorting implementation on mathbits http://mathbits.com/MathBits/Java/arrays/Sorting.htm .
Here is better example of bubble sort .
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
This might help as well Java: Sort an array
Example to use code
public class SortExample {
int[] intArray = { 12, 34, 99, 1, 89, 39, 17, 8, 72, 68 };
public void printArray(int[] arrayInts) {
for (int j = 0; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} // for (int j)
} // void printArray
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
public void process() {
System.out.println("Values before sorting:");
System.out.println("Index \tValue");
printArray(intArray);
bubbleSort(intArray);
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
printArray(intArray);
}
public static void main(String[] args) {
SortExample example = new SortExample();
example.process();
}
}
Hi guys im working on an anagram detector in any passage.
I have a problem with the array index out of bounds exception, im pretty sure the array positions and their memory locations are generated run time, there is no interference by the user.
import java.util.*;
import java.util.Random;
class never {
public static void main(String[] args) {
Scanner scan = new Scanner(System. in );
int[] array1 = new int[100];
int[] checker = {
121, 97, 104, 101, 97, 100, 104, 105, 109, 63, 32
};
String input = scan.nextLine();
String str = input.toLowerCase();
String str1 = input.replaceAll("\\W", " ");
String[] name1 = new String[5000];
name1 = str1.split(" ");
int length = name1.length;
System.out.println(length);
for (int i = 0; i < length; i++) {
if (name1[i] == " ") {
name1[i] = name1[i + 1];
}
}
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
Boolean s1 = name1[i].equals(name1[j]);
if (s1 == true) {
name1[j] = " ";
}
if (name1[i] == " ") {
name1[i] = name1[j];
name1[j] = " ";
}
}
}
length = name1.length;
System.out.println(length);
for (int i = 0; i < length; i++) {
for (int j = 0; j < name1[i].length(); j++) {
char charz = name1[i].charAt(j);
int iz = (int) charz;
for (int k = 0; k < 11; k++) {
if (iz == checker[k]) {
length--;
}
}
}
}
System.out.println(length);
for (int i = 0; i < length; i++) //Problem lies here
{
name1[i] = name1[i].toLowerCase();
}
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
int counter = 0;
char[] arr1 = name1[i].toCharArray();
char[] arr2 = name1[j].toCharArray();
java.util.Arrays.sort(arr1);
java.util.Arrays.sort(arr2);
int arraylen;
if (arr1.length != arr2.length) {
continue;
} else arraylen = arr1.length;
for (int k = 0; k < arraylen; k++) {
if (arr1[i] == arr2[i]) {
counter = counter + 1;
if (counter == arraylen) {
System.out.println(name1[i] + " " + name1[j]);
}
}
}
}
}
}
}
Index out of bounds exception means that you are trying to access a index that doesn't exists.
Say that you have an array with 9 elements. array[9] will be the 10th and it wont exists.