Problems with my program or netbeans error - java

I was doing an exercise and in which you ask us the following: Exercise 06: Read the data corresponding to two tables of 12 numerical elements and mix them in a third of the form: 3 from tables A, 3 from B, others 3 of the A, another 3 of the B, Etc. When making the code (according to me it is fine) I get an error in netbeans (attached a photo) can you tell me what is the reason for my error? I'm still a student. In advance thank you very much for reading (I attach my code and the image of the error).
package ejercicioarreglos_06;
import java.util.Scanner;
public class EjercicioArreglos_06 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tablaA[] = new int[12];
int tablaB[] = new int[12];
int contador = 0;
boolean eleccion = true;
int contA = 0, contB = 0;
for (int i = 0; i < tablaA.length; i++) {
System.out.print("Ingresa el valor " + (i + 1) + " de la tabla A: ");
tablaA[i] = in.nextInt();
}
for (int j = 0; j < tablaB.length; j++) {
System.out.print("Ingrese el valor " + (j + 1) + " de la tabla B: ");
tablaB[j] = in.nextInt();
}
for (int k = 0; k < tablaB.length + tablaB.length; k++) {
if (eleccion = true) {
System.out.println(tablaA[contA]);
contador++;
contA++;
if (contador > 2) {
eleccion = false;
}
} else {
System.out.print(tablaB[contB]);
contador--;
contB++;
if (contador < 0) {
eleccion = true;
}
}
}
}
}

According to Javadoc:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ArrayIndexOutOfBoundsException
It is an exception (error) that happens when we provide an index outside the limits allowed for the access of elements in an array. Remember that Java indexes start at 0 and go up to the number of elements -1.
Note the position of the public class ArrayIndexOutOfBoundsException in the class hierarchy of the Java platform:
-> java.lang.Object
--> java.lang.Throwable
---> java.lang.Exception
----> java.lang.RuntimeException
-----> java.lang.IndexOutOfBoundsException
------> java.lang.ArrayIndexOutOfBoundsException
Here is an example where we try to access an element of an array using an invalid index:
public class Test{
public static void main(String args[]){
// an array of five elements
int[] values = {8, 98, 100, 3, 14};
// we will provide an invalid index
System.out.println(values[5]);
System.exit(0);
}
}
This code compiles normally. However, when we try to run it, we get the following error message:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at Study.main(Test.java:7)
The most appropriate way to correct this error is to provide an index value that is really in the allowed range.

The If condition available seems to be true always and I corrected it to make the code work i.e., from if (eleccion = true) to if (eleccion)
package ejercicioarreglos_06;
import java.util.Scanner;
public class EjercicioArreglos_06 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tablaA[] = new int[12];
int tablaB[] = new int[12];
int contador = 0;
boolean eleccion = true;
int contA = 0, contB = 0;
for (int i = 0; i < tablaA.length; i++) {
System.out.print("Ingresa el valor " + (i + 1) + " de la tabla A: ");
tablaA[i] = in.nextInt();
}
for (int j = 0; j < tablaB.length; j++) {
System.out.print("Ingrese el valor " + (j + 1) + " de la tabla B: ");
tablaB[j] = in.nextInt();
}
for (int k = 0; k < tablaB.length + tablaB.length; k++) {
if (eleccion) {
System.out.println(tablaA[contA]);
contador++;
contA++;
if (contador > 2) {
eleccion = false;
}
} else {
System.out.print(tablaB[contB]);
contador--;
contB++;
if (contador < 0) {
eleccion = true;
}
}
}
}
}

Related

How to not print whole index if given number not found in table

I got this script to find given number from table and print number and index.
I'm having problem with number that are not in the table. I should print "number is not found" etc. and I tried with else, but not working. Any suggestions what to do with this?
with it prints whole table index.
import java.util.Scanner;
public class EtsitynAlkionIndeksi {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int[] taulukko = new int[10];
taulukko[0] = 6;
taulukko[1] = 2;
taulukko[2] = 8;
taulukko[3] = 1;
taulukko[4] = 3;
taulukko[5] = 0;
taulukko[6] = 9;
taulukko[7] = 7;
System.out.print("Mitä etsitään? ");
int etsittava = Integer.valueOf(lukija.nextLine());
// Toteuta etsimistoiminnallisuus tänne
int indeksi = 0;
while (indeksi < taulukko.length) {
int arvo = taulukko[indeksi];
int eiLoydy = 0;
if (etsittava == arvo) {
System.out.println("Luku " + etsittava + " löytyy indeksistä " + indeksi + ".");
} else {
System.out.println("Ei löydy " + eiLoydy);
}
indeksi++;
}
}
}
Use break as follows:
import java.util.Scanner;
public class EtsitynAlkionIndeksi {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int[] taulukko = new int[10];
taulukko[0] = 6;
taulukko[1] = 2;
taulukko[2] = 8;
taulukko[3] = 1;
taulukko[4] = 3;
taulukko[5] = 0;
taulukko[6] = 9;
taulukko[7] = 7;
System.out.print("Mitä etsitään? ");
int etsittava = Integer.valueOf(lukija.nextLine());
// Toteuta etsimistoiminnallisuus tänne
int indeksi = 0;
while (indeksi < taulukko.length) {
int arvo = taulukko[indeksi];
if (etsittava == arvo) {
System.out.println("Luku " + etsittava + " löytyy indeksistä " + indeksi + ".");
break;
}
indeksi++;
}
if (indeksi == taulukko.length) {
System.out.println("Ei löydy ");
}
}
}
A sample run:
Mitä etsitään? 3
Luku 3 löytyy indeksistä 4.
The statement, break; forces the loop to terminate. Also, note that I have moved System.out.println("Ei löydy " + eiLoydy); outside the while loop with the condition, if (indeksi == taulukko.length) i.e. if the value of indeksi has reached a value equal to taulukko.length, it means that the loop has not been terminated prematurely concluding that the lookup value has not been found.

When compiling program I get the error 'void' type not allowed here

I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);

Doubts for create a Totoloto with functions

Hi Guys i have a problem in my program of Totoloto. I want create a function for show the six numbers of the key but i can't because in my output show only a one number at end counter position. I make a debug with System.out.println in inside the function numeDeChaves and appears all numbers . If try without functions and its work but i want in function for legible code and learn a little more how to work the functions.
this is wrong output:
Quantas chaves pretende gerar? 6
As chaves geradas são: 1ª chave -> 2ª chave -> 3ª chave -> 4ª chave -> 5ª chave -> 6ª chave -> 36
public static void main(String[] args) {
System.out.println("Totoloto \n");
System.out.println("Quantas chaves pretende gerar?");
int numero = Ler.umInt();
int[] numeroChaves = new int[numero];
int[] chave = new int[8];
System.out.println("");
System.out.println("As chaves geradas são: ");
System.out.println(numeroDeChaves(numeroChaves));
}
public static int numeroDeChaves(int[] numeroChaves){
int contador = 1;
int totalChaves = 0;
for (int i = 0; i < numeroChaves.length; i++) {
System.out.print(contador + "ª chave -> ");
contador++;
for (int j = 0; j < numeroChaves.length; j++) {
numeroChaves[j] = chaveAleatoria(numeroChaves);
totalChaves = numeroChaves[j];
}
System.out.println("");
}
return totalChaves;
}
public static int chaveAleatoria(int chave[]) {
int numeroAleatorio = (int) (Math.random() * 43) + 6;
int ultimoNumero = chave[0] + 1;
int chaveGerada = 0;
int contarChaves = 0;
for (int i = 1; i < chave.length; i++) {
if (chave[i] == chave[i - 1] && ultimoNumero != chave[i - 1]) {
ultimoNumero = chave[i];
chave[i] = numeroAleatorio;
} else {
chave[i] = numeroAleatorio;
chaveGerada = chave[i];
System.out.print("");
}
}
return chaveGerada;
}

ACM-ICPC 7384 programming challenge

I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!

First time working with arrays, trying to create frequency table

I can't see where I'm going wrong with this one, I want it to display the frequencies of the survey's result but all I get is zeros, for example if I enter 1,1,2,2,5 I want it to output:
Displaying response frequencies...
1 2
2 2
3 0
4 0
5 1
but instead I get this:
Displaying response frequencies...
1 0
2 0
3 0
4 0
5 0
here is my main method:
import java.util.Scanner;
public class SurveyTester {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many people took the survey?");
int numPeople = input.nextInt();
Survey s = new Survey(numPeople);
int nextResponse;
for (int i = 0; i < numPeople; i++)
{
System.out.print("Input the next survey response (values 1-5):");
nextResponse = input.nextInt();
s.addResponse(nextResponse);
}
System.out.println("Displaying all responses...");
s.displayAllResponses();
System.out.println("Displaying response frequencies...");
s.displayResponseFrequencies();
}
}
here is my class:
public class Survey
{
private int numResponses;
private int maxResponses;
private int[] responses;
private int[] frequencies;
private final int NUM_RESPONSES = 5;
public Survey(int nResponses)
{
maxResponses = nResponses;
numResponses = 0;
responses = new int[nResponses];
frequencies = new int[NUM_RESPONSES]; // There are 5 possible responses to the survey
}
public void addResponse(int response)
{
// This method stores the response
// passed in the parameter 'response'
// to the next free space in the array
{
responses[numResponses]= response;
}
numResponses++;
}
public void displayAllResponses()
{
// This method displays on the screen
// all the responses to the survey
for (int i=0; i<maxResponses; i++)
{
System.out.print(responses[i] + " ");
}
System.out.println("");
}
public void calculateResponseFrequencies()
{
// This method calculates the number of
// responses for each possible answer
// to the survey, 1, 2, 3, 4 or 5
// It stores the frequencies in the
// array 'frequencies'
for (int i=1; i<=maxResponses; i++)
{
if (responses[i] == 1)
{
frequencies[1]++;
}
else if (responses[i] == 2)
{
frequencies[2]++;
}
else if (responses[i] == 3)
{
frequencies[3]++;
}
else if (responses[i] == 4)
{
frequencies[4]++;
}
else if (responses[i] == 5)
{
frequencies[5]++;
}
}
}
public void displayResponseFrequencies()
{
// This method displays the response
// frequences for each of the possible
// response, 1, 2, 3, 4 or 5
for (int i=0; i<frequencies.length; i++)
{
System.out.println((i+1) + "\t" + frequencies[i]);
}
}
}
You are not doing anything with your frequencies array. In you your addResponse method, you need to get the appropriate value and increment it. Add a statement like
frequencies[response-1] = frequencies[response-1] + 1;
Note you can do this with 2 arrays, as you are, especially for learning, but a lot of Java developers would use a Map implementation for this sort of thing, where the keys are the entered values and the values are the frequencies. Keeps all the data in one data structure.
public class DuplicatesInArray {
public static void main(String[] args) {
int count = 0;
int[] arr = new int[6];
int[] frequencyArr = new int[6];
arr[0] = 4;
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 5;
arr[5] = 4;
for(int i = 0;i < arr.length;i++){
frequencyArr[arr[i]] = frequencyArr[arr[i]] + 1;
}
for(int x = 0;x<frequencyArr.length;x++){
if(frequencyArr[x] > 0){
System.out.println(x + " " + frequencyArr[x] + " times." );
}
}
}
}
Default value in an integer array will be zero. We increment it by one for every occurrence.
Example:If integer 4 occurs 2 times,4th index at the frequencyArr is incremented twice.

Categories

Resources