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.
Related
import java.util.*;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
sc.close();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input))
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
}
}
}
}
}
When I get a number input, I want to make a code that represents this number as the sum of three numbers.
The code is complete, but there are several combinations. I want to print out only one combination. How can I edit it?
First, some important suggestions:
Do not parse input inside the nested loop as it will hit the performance. Do it once outside the nested loops.
Do not close Sacnner for System.in as it also closes System.in and there is no way to open it again without restarting JVM. It means that if it is being used in some other part of your application, your application will crash.
Always follow Java naming conventions e.g. you could name numJ instead of num_j.
Coming back to your problem, there are many ways to solve it and I have listed below just a couple of them:
Use break <<label>> to exit the nested loops:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
start: for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
break start;
}
}
}
}
}
}
A sample run:
Enter a number : 123
You entered: 123
(1, 22, 100)
Put the logic in a method and return:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
printFirstCombination(num);
}
static void printFirstCombination(int num) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
return;
}
}
}
}
}
}
You can create a seperate function for that and after you find a combination, print it and return there and then to the main function. In case you didn't find a combination you return 1 which can be handled in the main function,
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int res = printCombination(input);
if(res == 1) {
// Do something
}
sc.close();
}
private static int printCombination(String input) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input)) {
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
return 0;
}
}
}
}
return 1;
}
}
I have it go through an array and assign values to it from an arraylist. I'm having trouble with trying to write a thing that can see if there are enough rows and columns for a set value in the arraylist names. everytime it prints it just prints as one line and not as row and columns with the respective numbers. I don't know what I'm doing wrong.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class SeatingChart {
public static void main(String[] args) {
// instanced variables
Scanner kb = new Scanner(System.in);
String name = "";
int r = 0;
int c = 0;
int k = 0;
String row = "";
String column = "";
ArrayList<String> names = new ArrayList<String>();
while (!name.equals("quit")) {
System.out.print("Enter first name of student: ");
// takes the name of kb and sets it to name
name = kb.nextLine();
// if the ArrayList names isEmpty then it adds the value at index
if (names.isEmpty()) {
names.add(name);
} else if (name.compareTo(names.get(names.size() - 1)) > 0) {
names.add(name);
} else {
// for loop going through the list of names to insert where it belongs
for (int i = 0; i < names.size(); i++) {
if (name.compareTo(names.get(i)) < 0) {
names.add(i, name);
i = names.size();
}
}
}
if (names.contains("quit")) {
names.remove("quit");
}
}
System.out.println(names);
// System.out.println(names);
System.out.println("how many rows do you have: ");
r = kb.nextInt();
System.out.println();
System.out.println("how many columns do you have: ");
c = kb.nextInt();
System.out.println();
System.out.println("Should students be seated row major(1) or column major(0)?");
if (kb.nextInt() == 1) {
// String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[0].length; j++) {
if (k < names.size()) {
chart[i][j] = names.get(k);
k += 1;
}
System.out.printf("%10s ", chart[i][j]);
}
}
} else if (kb.nextInt() == 2) {
String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < names.size(); i++) {
arr[i] = names.get(i);
}
System.out.println(Arrays.toString(arr));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
arr[i] = chart[r][c];
k++;
}
}
for (int i = 0; i < chart[0].length; i++) {
for (int j = 0; j < chart.length; j++) {
System.out.printf("%10s ", chart[i][j]);
}
}
System.out.println("Column order!");
}
}
}
I have fixed one IF Block for major
if (kb.nextInt() == 1) {
// String arr[] = new String[names.size()];
String[][] chart = new String[r][c];
for (int i = 0; i < chart.length; i++) {
for (int j = 0; j < chart[0].length; j++) {
if (k < names.size()) {
chart[i][j] = names.get(k);
k += 1;
}
System.out.printf("%10s ", chart[i][j]);
}
System.out.println(""); // ADD THIS
}
}
The code asks if you want to encode or decode a message, then it asks for the message. It will work by this reference:
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 "
"kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 "
Therefore if you try to encode the letter 'a' for example, it will output the letter 'k'.
My problem is that I can't include any spaces when typing the message.
Here is my code:
import java.util.Scanner;
public class SecretMessage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter 1 to encode, 2 to decode, 3 to quit:");
int start = input.nextInt();
if (start == 3){
break;
}
System.out.println("Type your message:");
String test = input.next();
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 ";
String enc = "kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$##!~`0123456789 ";
char[] array = test.toCharArray();
char[] decoded = letters.toCharArray();
char[] encoded = enc.toCharArray();
int[] position = new int[array.length];
char[] end = new char[array.length];
if (start == 1){
for (int i = 0; i < test.length(); i++){
for (int j = 0; j < decoded.length; j++){
if (array[i] == decoded[j]){
position[i] = j;
}
}
}
for (int f = 0; f < test.length(); f++){
end[f] = encoded[position[f]];
}
for (int x = 0; x < test.length(); x++){
System.out.print(end[x]);
}
System.out.println(" ");
} else {
for (int i = 0; i < test.length(); i++){
for (int j = 0; j < encoded.length; j++){
if (array[i] == encoded[j]){
position[i] = j;
}
}
}
for (int f = 0; f < test.length(); f++){
end[f] = decoded[position[f]];
}
String output = new String(end);
System.out.println(output);
}
System.out.println(" ");
} while (1 ==1);
}
}
I have a two dimensional array and I fill it with scanner. I want to copy the elements that start with letter 'a' to a new one dimensional array without using ArrayList. Please advise on what I can do to get this code functioning properly. the question is how can I know the new array size while I don't know how many words start with letter a
Here is what I have so far:
import java.util.Scanner;
class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] name = new String[2][2];
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name[i].length; j++) {
name[i][j] = input.next();
}
}
student(name);
}
public static void student(String[][] arr) {
int count = 0;
int c2 = -1;
String[] name2 = new String[count];
String temp = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
c2++;
temp = arr[i][j];
name2[c2] = temp;
count++;
temp = "";
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
}
}
A two dimensional arrray of size [n][n] is equal to one dimensional array of size n. If you want to copy them on proper place then you can use this formula, it is useful if you later want to copy these elements back to twodimensional array at proper places:
int v = i * n + j; // i and j your loops and n is length of rows or colums.
array[v] = array[i][j];
for in your codes it's like:
int v = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
v = i * arra.length +j;
name2[v] = arr[i][j];
count++;
Ok here is a working code:
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String[][] name = new String[2][2];
System.out.println("Enter the name: ");
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name[i].length; j++) {
name[i][j] = input.next();
}
}
student(name);
}
public static void student(String[][] arr) {
int count = 0;
int v = 0;
String[] name2 = new String[arr.length*arr[0].length];
String temp = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
v = i *+arr[0].length + j;
name2[v] = arr[i][j];
count++;
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
System.out.println("printing without nulls");
//if you don't want null to be printed then do this:
for (int i = 0; i < name2.length; i++) {
if(name2[i] != null)
System.out.println(name2[i]);
}
}
I did it with two nested for loop one for indicating the array size and the other for filling the elements into the array, it does the work but is there any way to do this better
public static void student(String[][] arr) {
int size = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
size++;
}
}//inner
}//outer
String[] name2 = new String[size];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
name2[count] = arr[i][j];
count++;
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
I have to build Simplex Algorithm and its working but I want to allow user to input data, in method main I made few "for" loops where I put date into arrays, but that I put the same data in another arrays, (they have exactly the same data) I have no idea how to fix it.
When I try to make just one arrays for one type of date, it's crash.
[edit]
Yep, I update those Scanners (thanks guys)
And right now I have this error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at simplex.Simplex$Modeler.(Simplex.java:224)
at simplex.Simplex.main(Simplex.java:196)"
package simplex;
import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Simplex {
private double[][] macierz; // macierz
private int LiczbaOgraniczen; // liczba ograniczen
private int LiczbaX; // liczba zmiennych "orginalnych"
private boolean MaxCzyMin;
private static final boolean MAX = true;
private static final boolean MIN = false;
private int[] baza; // baza[i] = basic variable corresponding to row i
public Simplex(double[][] macierz, int LiczbaOgraniczen, int numberOfOriginalVariable, boolean MaxCzyMin) {
this.MaxCzyMin = MaxCzyMin;
this.LiczbaOgraniczen = LiczbaOgraniczen;
this.LiczbaX = numberOfOriginalVariable;
this.macierz = macierz;
baza = new int[LiczbaOgraniczen];
for (int i = 0; i < LiczbaOgraniczen; i++)
baza[i] = LiczbaX + i;
Licz();
}
// Licz algorytm simples od startowych BFS
private void Licz() {
while (true) {
DrukujInteracje();
int q = 0;
// znajdz kolumne q wchodzącą do bazy
if (MaxCzyMin) {
q = ZnajdzIndexPoz(); //jesli szukamy max
} else {
q = ZnajdzIndexNeg(); //jesli szukamy min
}
if (q == -1){
break; // optimum
}
// znajdz rzad p wychodzący z bazy
int p = minRatioRule(q);
if (p == -1){
throw new ArithmeticException("BLAD");
}
//wiersz - kolumna
piwot(p, q);
// zaktualizuj baze
baza[p] = q;
}
}
// znajdowanie indexu niebazowej kolumny z najbardzoje pozytywnym kosztem
private int ZnajdzIndexPoz() {
int q = 0;
for (int j = 1; j < LiczbaOgraniczen + LiczbaX; j++)
if (macierz[LiczbaOgraniczen][j] > macierz[LiczbaOgraniczen][q])
q = j;
if (macierz[LiczbaOgraniczen][q] <= 0){
return -1; // optimum
} else {
return q;
}
}
// znajdowanie indexu niebazowej kolumny z najbardziej negatywnym kosztem
private int ZnajdzIndexNeg() {
int q = 0;
for (int j = 1; j < LiczbaOgraniczen + LiczbaX; j++)
if (macierz[LiczbaOgraniczen][j] < macierz[LiczbaOgraniczen][q])
q = j;
if (macierz[LiczbaOgraniczen][q] >= 0){
return -1; // optimum
} else {
return q;
}
}
// find row p using min ratio rule (-1 if no such row)
private int minRatioRule(int q) {
int p = -1;
for (int i = 0; i < LiczbaOgraniczen; i++) {
if (macierz[i][q] <= 0)
continue;
else if (p == -1)
p = i;
else if ((macierz[i][LiczbaOgraniczen
+ LiczbaX] / macierz[i][q]) < (macierz[p][LiczbaOgraniczen
+ LiczbaX] / macierz[p][q]))
p = i;
}
return p;
}
//zastosowanie metody Gauss-Jordan, aby doprowadzic macierz do postaci bazowej
private void piwot(int p, int q) {
for (int i = 0; i <= LiczbaOgraniczen; i++)
for (int j = 0; j <= LiczbaOgraniczen + LiczbaX; j++)
if (i != p && j != q)
macierz[i][j] -= macierz[p][j] * macierz[i][q] / macierz[p][q];
for (int i = 0; i <= LiczbaOgraniczen; i++)
if (i != p)
macierz[i][q] = 0.0;
for (int j = 0; j <= LiczbaOgraniczen + LiczbaX; j++)
if (j != q)
macierz[p][j] /= macierz[p][q];
macierz[p][q] = 1.0;
}
// Metoda zwraca wartosc funkcji celu
public double WartoscFunkcjiCelu() {
return -macierz[LiczbaOgraniczen][LiczbaOgraniczen + LiczbaX];
}
// metoda zwaraca wartosc x-ow
public double[] WyliczX() {
double[] x = new double[LiczbaX];
for (int i = 0; i < LiczbaOgraniczen; i++)
if (baza[i] < LiczbaX)
x[baza[i]] = macierz[i][LiczbaOgraniczen + LiczbaX];
return x;
}
// drukuj macierz => drukuj tabele
public void DrukujInteracje() {
System.out.println("Liczba Ograniczen = " + LiczbaOgraniczen);
System.out.println("Liczba zmiennych 'orginalnych' = " + LiczbaX);
for (int i = 0; i <= LiczbaOgraniczen; i++) {
for (int j = 0; j <= LiczbaOgraniczen
+ LiczbaX; j++) {
System.out.printf("%7.2f ", macierz[i][j]);
}
System.out.println();
}
System.out.println("Funkcja celu = " + WartoscFunkcjiCelu());
for (int i = 0; i < LiczbaOgraniczen; i++)
if (baza[i] < LiczbaX)
System.out.println("x_"
+ baza[i]
+ " = "
+ macierz[i][LiczbaOgraniczen + LiczbaX]);
System.out.println();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Podaj ilosc x");
int iloscX = scan.nextInt();
double[] WspolczynnikiFunkcjiCelu = new double[iloscX + 1];
for(int ggg = 0; ggg < iloscX; ggg++){
System.out.println("Podaj x" + ggg);
WspolczynnikiFunkcjiCelu[ggg] =scan.nextDouble();
}
System.out.println("Podaj ilosc ograniczen");
int iloscOgraniczen = scan.nextInt();
double[][] LewaStronaOgraniczen = new double[iloscOgraniczen][iloscX];
double[] PrawaStronaOgraniczen = new double[iloscOgraniczen + 1];
Znaki[] OperatorOgraniczen = new Znaki [iloscOgraniczen + 1];
for(int ggh = 0;ggh <iloscOgraniczen; ggh++){
System.out.println("Podaj znak ograniczenia (lessThan - equal - greatherThan ");
OperatorOgraniczen[ggh] = Znaki.valueOf(scan.next());
System.out.println("Podaj prawa strone ograniczenia");
PrawaStronaOgraniczen[ggh] = scan.nextDouble();
for(int haha = 0; haha < iloscX; haha++){
System.out.println("Lewa strona: Podaj wspolczynnik przy x" + haha);
LewaStronaOgraniczen[ggh][haha] =scan.nextDouble();
}
}
//double[] WspolczynnikiFunkcjiCelu = {Xsy[0], Xsy[1]};
// double[][] LewaStronaOgraniczen = {
// { TablicaTablic[0][0], TablicaTablic[0][1] }, { TablicaTablic[1][0], TablicaTablic[1][1] }, { TablicaTablic[2][0], TablicaTablic[2][1] }, { TablicaTablic[3][0], TablicaTablic[3][1] } };
//Znaki[] OperatorOgraniczen = { TablicaOgraniczen[0], TablicaOgraniczen[1], TablicaOgraniczen[2], TablicaOgraniczen[3] };
//double[] PrawaStronaOgraniczen = {TablicaPrawejStrony[0],TablicaPrawejStrony[1],TablicaPrawejStrony[2],TablicaPrawejStrony[3]};
Modeler model = new Modeler(LewaStronaOgraniczen, PrawaStronaOgraniczen, OperatorOgraniczen, WspolczynnikiFunkcjiCelu);
Simplex simplex = new Simplex(model.getmacierz(),
model.getLiczbaOgraniczen(),
model.getLiczbaX(), MAX);
double[] x = simplex.WyliczX();
for (int i = 0; i < x.length; i++)
System.out.println("x[" + i + "] = " + x[i]);
System.out.println("Rozwiazanie optymalne: " + simplex.WartoscFunkcjiCelu());
}
//zbior mozliwych znakow ograniczajacych
private enum Znaki {
lessThan, equal, greatherThan
}
public static class Modeler {
private double[][] a; // macierz
private int LiczbaOgraniczen; // Liczba Ograniczen
private int LiczbaX; // Liczba x w funkcji celu
public Modeler(double[][] LewaStronaOgraniczen,double[] PrawaStronaOgraniczen, Znaki[] OperatorOgraniczen, double[] WspolczynnikiFunkcjiCelu) {
LiczbaOgraniczen = PrawaStronaOgraniczen.length;
LiczbaX = WspolczynnikiFunkcjiCelu.length;
a = new double[LiczbaOgraniczen + 1][LiczbaX + LiczbaOgraniczen + 1];
for (int i = 0; i < LiczbaOgraniczen; i++) {
for (int j = 0; j < LiczbaX; j++) {
a[i][j] = LewaStronaOgraniczen[i][j];
}
}
for (int i = 0; i < LiczbaOgraniczen; i++)
a[i][LiczbaOgraniczen + LiczbaX] = PrawaStronaOgraniczen[i];
for (int i = 0; i < LiczbaOgraniczen; i++) {
int slack = 0;
switch (OperatorOgraniczen[i]) {
case greatherThan:
slack = -1;
break;
case lessThan:
slack = 1;
break;
default:
}
a[i][LiczbaX + i] = slack;
}
for (int j = 0; j < LiczbaX; j++)
a[LiczbaOgraniczen][j] = WspolczynnikiFunkcjiCelu[j];
}
public double[][] getmacierz() {
return a;
}
public int getLiczbaOgraniczen() {
return LiczbaOgraniczen;
}
public int getLiczbaX() {
return LiczbaX;
}
}
}
why have you so many scanners? Try use only one. Declare and initialize it at the beginning main method.