Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "array" is null - netbeans

Sorry for the words in Spanish but the problem is summed up in that the rows, columns and diagonals add up. The thing is that when I start the code and use option 2 to 4 I get the error Exception in thread "main" java.lang. NullPointerException: Cannot read the array length because "array" is null
import java.util.Scanner;
public class Laboratorio14p2 {
static Scanner osc=new Scanner(System.in);
static int fil[],col[];
static int[][] numero;
public static void main(String[] args) {
String resp=null;
int num=0;
do {
int opc=menu();
switch(opc)
{
case 1:
System.out.println("Ingresar tamaño del array");
agregarDatos(osc.nextInt()) ;
System.out.println("Los datos han sido generados");
break;
case 2:
sumarFilas(numero);
Mostrar(fil,"fila");
break;
case 3:
sumarColumnas(numero);
Mostrar(col,"columna");
case 4:
num=sumarDiagonalDerecha(numero);
System.out.println("La suma de la diagonal Derecha es: "+num);
break;
case 5:
num=sumarDiagonalIzquierda(numero);
System.out.println("La suma de la diagonal izquierda es: "+num);
break;
case 6:
MostrarArrayBidimensional(numero);
break;
case 7:
break;
}
System.out.println("Desea continuar(s/n):");
resp=osc.next();
}while(resp.equals("s"));
}
public static void agregarDatos(int longitud)
{
numero=new int[longitud][longitud];
int li=10;
int ls=50;
for(int i=0 ;i<longitud;i++)
{
for(int j=0 ;j<longitud;j++)
{
numero[i][j]=(int)((ls-li)*Math.random()+li);
}
}
}
public static int sumarDiagonalDerecha(int[][] array)
{
int diagDer=0;
for (int i=0 ;i<array.length;i++)
{
diagDer=diagDer+array[i][i];
}
return diagDer;
}
public static int sumarDiagonalIzquierda(int[][] array)
{
int diagIzq=0;
for(int i=0 ;i<array.length;i++)
{
diagIzq=diagIzq+array[i][array.length-i];
}
return diagIzq;
}
public static int menu()
{
System.out.println("MENU DE OPCIONES");
System.out.println("------------------------");
System.out.println("1. Llenar matriz");
System.out.println("2. Sumar Filar");
System.out.println("3. Sumar columnas");
System.out.println("4. Sumar Diagonal Derecha");
System.out.println("5. Sumar Diagonal Izquierda");
System.out.println("6. Mostrar Array Bidimensional");
System.out.println("7. Salir");
System.out.println("Seleccionar Opcion[1-7]:");
int opc=osc.nextInt();
return opc;
}
public static int[] sumarFilas(int[][] array)
{
fil=new int[array.length];
for (int i=0 ;i<array.length;i++)
{
fil[i]=0;
for(int j=0;j<array.length;j++)
fil[i]=fil[i]+ array[i][j];
}
return fil;
}
public static int[] sumarColumnas(int[][] array)
{
col=new int[array.length];
for (int i=0 ;i<array.length;i++)
{
col[i]=0;
for(int j=0;j<array.length;j++)
col[i]=col[i]+ array[j][i];
}
return col;
}
public static void Mostrar(int[]resultados,String descripcion)
{
for(int i=0; i<resultados.length;i++)
{
System.out.println(descripcion+"["+i+"]="+resultados[i]);
}
}
public static void MostrarArrayBidimensional(int[][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array.length;j++)
System.out.print(array[i][j]+ " ");
System.out.println();
}
}
}
As far as I understand it is necessary to give the array a value but I have no idea how to do it pls help (the code is made in netbeans 13)

Related

Sort an array A using Quick Sort. Using reccursion

#include<iostream>
using namespace std;
void quickSort(int input[], int start, int end)
{
// your code goes here
}
void quickSort(int input[], int size)
{
quickSort(input, 0, size - 1);
}
*/
void swap(int* a,int* b){
int temp=*a;
*a=*b;
*b=temp;
}
int count(int input[],int start,int end ){
static int c=0;
if(start==end)
return c;
if(input[start]>input[end])
c++;
return count(input,start,end-1);
}
int partionArray(int input[],int start,int end ){
int c=count(input,start,end);
int pi=c+start;
swap(&input[start],&input[pi]);
int i=start;
int j=end;
while(i<pi&&j>pi)
{
if(input[i]<input[pi])
{
i++;
}
else if(input[j]>=input[pi])
{
j--;
}
else
{
swap(&input[i],&input[j]);
i++;
j--;
}
}
return pi;
}
void qs(int input[],int start, int end){
if(start>=end)
return;
int pi=partionArray(input,start,end);
qs(input,start,pi-1);
qs(input,pi+1,end);
}
void quickSort(int input[], int size) {
qs(input,0,size-1);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
quickSort(input, n);
for(int i = 0; i < n; i++) {
cout << input[i] << " ";
}
delete [] input;
}
Sort an array A using Quick Sort. Using reccursion is the question.
Input format :
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Output format :
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
What did i do wrong in this code pls can any one explain?Is every thing right with this code?

Backtrack the difference between these two codes

I have been trying to play around with backtracking. From my understanding these two codes are doing same thing but somehow I got different outcomes.
I am just trying to use some type of template to start with.
cout<<i<<endl;
backtrack(i+1);
backtrack(i+1);
and
for(int i=start; i<n; i++){
cout<<i<<endl;
backtrack(i+1);
}
The first one gets 5 as outcome and the second one gets six when I have the input of
nums=[1,1,1,1,1]
target = 3
public class Solution {
int count = 0;
public int findTargetSumWays(int[] nums, int S) {
calculate(nums, 0, 0, S);
return count;
}
public void calculate(int[] nums, int i, int sum, int S) {
if (i == nums.length) {
if (sum == S) {
count++;
}
} else {
calculate(nums, i + 1, sum + nums[i], S);
calculate(nums, i + 1, sum - nums[i], S);
}
}
}
class Solution {
public:
int count;
void backtrack(vector<int>& nums, int target, int start, int sum){
if(start==nums.size()){
if(sum==target){
count++;
}
return;
}
else{
for(int i=start; i<nums.size(); i++){
//sum+=nums[i];
backtrack(nums, target, i+1, sum+nums[i]);
sum-=nums[i];
}
}
}
int findTargetSumWays(vector<int>& nums, int target) {
count=0;
int sum=0;
int total=0;
for(auto x:nums)total+=x;
vector<vector<int>> dp;
backtrack(nums, target, 0, sum);
return count;
}
};

Check manually a JMenuItem in a JPopUpMenu?

I have a JPopUpMenu with several JCheckBoxMenuItem's on it.
Actually what I would like to do is basicly to select an item of the JPopUpMenu with a specific index.
For exemple, a method like myPopUpMenu.setSelected(2), which would select "Algérie" in my JPopUpMenu.
The problem is that I don't know any method which would allow me to check an item manually...
Here's the code of my JPopUpMenu :
MainVue.java:
public class MainVue extends JFrame implements ActionListener {
private static final JScrollPopupMenu menuProduit = new JScrollPopupMenu();
private static final JScrollPopupMenu menuPays = new JScrollPopupMenu();
private static List<String> listeFiltres = new ArrayList<String>();
private String listeDeFiltres;
private String[] tableauFiltrePermanent;
private String listeFiltrePermanent;
private String[] tableauPays = { "Autres", "Afrique du sud", "Algérie", "Allemagne", "Arabie Saoudite", "Argentine",
"Australie", "Bangladesh", "Belgique", "Brésil", "Bulgarie", "Canada", "Chine", "Corée du sud", "Egypte",
"Emirats-Arabes Unis", "Espagne", "Etats-Unis", "Ethiopie", "Europe", "France", "Hongrie", "Inde",
"Indonésie", "Irak", "Iran", "Israél", "Italie", "Japon", "Jordanie", "Kazakhstan", "Koweit", "Liban",
"Libye", "Malaisie", "Maroc", "Mexique", "Monde", "Oman", "Pakistan", "Pays-Bas", "Philippines", "Poligne",
"Portugal", "Qatar", "République tchéque", "Roumanie", "Russie", "Taïwan", "Tunisie", "Turquie",
"Ukraine" };
private String[] tableauProduit = { "Blé", "Colza", "Mais", "Orge", "Orge de Brasserie", "Palme", "Soja",
"Tournesol", "Tourteaux De Colza", "Tourteaux de Soja", "Huile de Soja", "Huile De Colza" };
private List<JCheckBoxMenuItem> listJCBProduit = new ArrayList<JCheckBoxMenuItem>();
private List<JCheckBoxMenuItem> listJCBPays = new ArrayList<JCheckBoxMenuItem>();
public static PropertiesConfiguration prop;
public MainVue(Modele modele, Controleur controleur) throws ClassNotFoundException, SQLException, IOException {
prop = new PropertiesConfiguration("config.properties");
for (int i = 0; i < tableauProduit.length; i++) {
listJCBProduit.add(new JCheckBoxMenuItem(tableauProduit[i]));
}
for (int j = 0; j < listJCBProduit.size(); j++) {
JCheckBoxMenuItem produitActuel = listJCBProduit.get(j);
menuProduit.add(produitActuel);
produitActuel.addActionListener(new OpenAction(menuProduit, boutonProduit));
}
for (int i = 0; i < tableauPays.length; i++) {
listJCBPays.add(new JCheckBoxMenuItem(tableauPays[i]));
}
for (int j = 0; j < listJCBPays.size(); j++) {
JCheckBoxMenuItem paysActuel = listJCBPays.get(j);
menuPays.add(paysActuel);
paysActuel.addActionListener(new OpenAction(menuPays, boutonPays));
}
listeDeFiltres = "";
for (int p = 0; p < listeFiltres.size(); p++) {
String filtreActuel = listeFiltres.get(p);
if (listeDeFiltres == "") {
listeDeFiltres += filtreActuel;
} else {
listeDeFiltres += "," + filtreActuel;
}
}
prop.setProperty("listeFiltres", listeDeFiltres);
}
}
Here's the JScrollPopUpMenu component :
JScrollPopUpMenu.java:
package fr.views;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
public class JScrollPopupMenu extends JPopupMenu {
protected int maximumVisibleRows = 10;
public JScrollPopupMenu() {
this(null);
}
public JScrollPopupMenu(String label) {
super(label);
setLayout(new ScrollPopupMenuLayout());
super.add(getScrollBar());
addMouseWheelListener(new MouseWheelListener() {
#Override public void mouseWheelMoved(MouseWheelEvent event) {
JScrollBar scrollBar = getScrollBar();
int amount = (event.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
? event.getUnitsToScroll() * scrollBar.getUnitIncrement()
: (event.getWheelRotation() < 0 ? -1 : 1) * scrollBar.getBlockIncrement();
scrollBar.setValue(scrollBar.getValue() + amount);
event.consume();
}
});
}
private JScrollBar popupScrollBar;
protected JScrollBar getScrollBar() {
if(popupScrollBar == null) {
popupScrollBar = new JScrollBar(JScrollBar.VERTICAL);
popupScrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override public void adjustmentValueChanged(AdjustmentEvent e) {
doLayout();
repaint();
}
});
popupScrollBar.setVisible(false);
}
return popupScrollBar;
}
public int getMaximumVisibleRows() {
return maximumVisibleRows;
}
public void setMaximumVisibleRows(int maximumVisibleRows) {
this.maximumVisibleRows = maximumVisibleRows;
}
public void paintChildren(Graphics g){
Insets insets = getInsets();
g.clipRect(insets.left, insets.top, getWidth(), getHeight() - insets.top - insets.bottom);
super.paintChildren(g);
}
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if(maximumVisibleRows < getComponentCount()-1) {
getScrollBar().setVisible(true);
}
}
public void remove(int index) {
// can't remove the scrollbar
++index;
super.remove(index);
if(maximumVisibleRows >= getComponentCount()-1) {
getScrollBar().setVisible(false);
}
}
public void show(Component invoker, int x, int y){
JScrollBar scrollBar = getScrollBar();
if(scrollBar.isVisible()){
int extent = 0;
int max = 0;
int i = 0;
int unit = -1;
int width = 0;
for(Component comp : getComponents()) {
if(!(comp instanceof JScrollBar)) {
Dimension preferredSize = comp.getPreferredSize();
width = Math.max(width, preferredSize.width);
if(unit < 0){
unit = preferredSize.height;
}
if(i++ < maximumVisibleRows) {
extent += preferredSize.height;
}
max += preferredSize.height;
}
}
Insets insets = getInsets();
int widthMargin = insets.left + insets.right;
int heightMargin = insets.top + insets.bottom;
scrollBar.setUnitIncrement(unit);
scrollBar.setBlockIncrement(extent);
scrollBar.setValues(0, heightMargin + extent, 0, heightMargin + max);
width += scrollBar.getPreferredSize().width + widthMargin;
int height = heightMargin + extent;
setPopupSize(new Dimension(width, height));
}
super.show(invoker, x, y);
}
protected static class ScrollPopupMenuLayout implements LayoutManager{
#Override public void addLayoutComponent(String name, Component comp) {}
#Override public void removeLayoutComponent(Component comp) {}
#Override public Dimension preferredLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp :parent.getComponents()){
if(comp.isVisible()) {
if(comp instanceof JScrollBar){
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension pref = comp.getPreferredSize();
dim.width = Math.max(dim.width, pref.width);
dim.height += pref.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public Dimension minimumLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp : parent.getComponents()) {
if(comp.isVisible()){
if(comp instanceof JScrollBar) {
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension min = comp.getMinimumSize();
dim.width = Math.max(dim.width, min.width);
dim.height += min.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int width = parent.getWidth() - insets.left - insets.right;
int height = parent.getHeight() - insets.top - insets.bottom;
int x = insets.left;
int y = insets.top;
int position = 0;
for(Component comp : parent.getComponents()) {
if((comp instanceof JScrollBar) && comp.isVisible()) {
JScrollBar scrollBar = (JScrollBar) comp;
Dimension dim = scrollBar.getPreferredSize();
scrollBar.setBounds(x + width-dim.width, y, dim.width, height);
width -= dim.width;
position = scrollBar.getValue();
}
}
y -= position;
for(Component comp : parent.getComponents()) {
if(!(comp instanceof JScrollBar) && comp.isVisible()) {
Dimension pref = comp.getPreferredSize();
comp.setBounds(x, y, width, pref.height);
y += pref.height;
}
}
}
}
}
Thanks in advance for any help !
The index which you get from getIndex() method use as follows. You are adding ScrollBar in your JScrollPopupMenu at 0 index. So to remove casting error update your code as follow.
int index = getIndex("name");
((JCheckBoxMenuItem)menuProduit.getComponentAtIndex(index+1)).setState(true);

passing method name as parameter for threadpool queuserworkitem

QueUserWorkItem is supposed to accept a delegate but i found exercise that passes instance method name instead of delegate like this:
public class Fibonacci
{
private int _n;
private int _fibOfN;
private ManualResetEvent _doneEvent;
public int N { get { return _n; } }
public int FibOfN { get { return _fibOfN; } }
// Constructor.
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}
// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...with id={1}", threadIndex,Thread.CurrentThread.ManagedThreadId);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}
// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}
return Calculate(n - 1) + Calculate(n - 2);
}
}
public class Program
{
static void Main()
{
const int FibonacciCalculations = 10;
// One event is used for each Fibonacci object.
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();
// Configure and start threads using ThreadPool.
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback , i);
}
for (int x = 0; x < 10;x++ )
{
Console.WriteLine("x");
}
// Wait for all threads in pool to calculate.
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations are complete.");
// Display the results.
for (int i = 0; i < FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}
why does this work? I do not see implicit or explicit delegate being passed

Fibonacci Sequence error

I am coding a Fibonacci sequence in Eclipse and this is my code-
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
It is showing an error in the return value; line saying value cannot be resolved to a variable. I don't see any other errors.
Where is value defined? You return something that was not defined anywhere.
You don't have a "value" defined, this is your error. I don't remember the thing exactly, but I think you don't need a and b, I found this in my code archive, hope it helps.
public class Fibonacci
{
public static long fibo(int n)
{
if (n <= 1) return n;
else return fibo(n - 1) + fibo(n - 2);
}
public static void main() {
int count = 5; // change accordingly, bind to input etc.
int N = Integer.parseInt(count);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fibo(i));
}
}
In case you want to stay with your own code, try returning "b" as value.
Your method is returning an int variable so you would have to define and return value as an int
I am not sure what you trying to do.
If you have "getValue" method I think "increment" method should be void.
When you want current Fibonacci value use "getValue" method.
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public void increment() {
int temp = b;
b = a + b;
a = temp;
}
public int getValue() {
return b;
}