Unchecked or unsafe operations when compiled, exception when atempted to run - java

When I attempt to compile my code, this error occurs:
Note: GoFishEdited.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
When I tried to run it, this error message occurs:
Exception in thread "main" java.lang.NullPointerException
at Habitat.stockUp(Habitat.java:20)
at GoFishEdited.main(GoFishEdited.java:14)
I'm pretty sure the error is in the stoockUp method, but I don't understand what could be wrong with it.
Here is my code:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
int[] fishArray;
ArrayList<Fish> catchF = new ArrayList<Fish>();
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
fishArray = h1.stockUp();
System.out.println("Start with some weights:");
for (int i : fishArray) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishArray.length]; // array of Fish
for (int i=0; i < fishArray.length; i++) {
fishGroup[i] = new Fish(fishArray[i]); // make fish
}
System.out.println("Fish are made. Now put them in a habitat:\n");
for (Fish f : fishGroup) {
h1.addFish(f);
}
System.out.println("\nAll in. The habitat displays them:\n");
h1.printFish();
System.out.println("\nMove some fish to the second habitat.\n");
for(Fish f : fishGroup){
h2.addFish(f);
}
System.out.println("\nPrint both habitats:\n");
h1.printFish();
h2.printFish();
System.out.println("\nCatch some fish.\n");
for(Fish f : fishGroup){
catchF = h1.catchFish(f);
}
}
}
And:
public class Habitat {
ArrayList<Fish> stringer = new ArrayList<Fish>();
int[] fishArr;
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public ArrayList<Fish> catches = new ArrayList<Fish>();
public int[] stockUp(){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
return fishArr;
}
public Habitat(){
int[] hab;
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
public ArrayList catchFish(Fish f){
int caught = 0 + (int)(Math.random() * ((100 - 0) + 1));
if(caught < catchProbability){
catches.add(f);
stringer.remove(f);
}
return catches;
}
public void printGrid(int[][] twoD){
int i, j;
for ( i = 0 ; i < twoD.length ; i++ ){
for ( j = 0 ; j < twoD[i].length ; j++ ){
System.out.print( twoD[i][j] + " " );
}
System.out.println();
}
}
public void toGrid(String[] oneD){
int cols = (int) Math.floor(Math.sqrt(oneD.length));
int currentCol = 0;
for(String element : oneD) {
System.out.print(element + "\t");
if(currentCol >= cols) {
System.out.println("");
currentCol = 0;
}
else {
currentCol++;
}
}
}
}
I would appreciate an explanation, because I am thoroughly confused, and just want to see if it'll work properly.

The problem is that you never initialize fishArr in Habitat
And the unchecked operation warning might come from public ArrayList catchFish(Fish f){, you should parameterize your return type

Related

Limit execution time of my Method

The following is my Brute force code for Sudoku:
public abstract class SudokuBoard
{
protected int ROWS = 9;
protected int COLS = 9;
int solutionsCounter;
double startTime;
double endTime;
String[] data = new String[8];
int puzzleNum = countTotalRows();
// data accessors
public abstract int get(int r, int c);
public abstract void set(int r, int c, int v);
// specific constraints checker, returns true even if the values are not complete
abstract boolean isRowCompatible(int r, int c);
abstract boolean isColCompatible(int r, int c);
abstract boolean isBoxCompatible(int r, int c);
// returns true if element S[r,c] is compatible, even if some values arount it are not filled
public boolean isCompatible(int r, int c)
{
for (int i=0; i<ROWS; i++)
for (int j=0; j<COLS; j++)
if(! (isRowCompatible(r, c) && isColCompatible(r, c) && isBoxCompatible(r, c)))
return false;
return true;
}
// this is the one called to solve the sudoku
public void solve()
{
//convert to seconds
startTime = System.nanoTime() / 1000000000.0;
solve(1,1);
}
// function to incorporate clues
public void incorporateClues(int[] clues)
{
for (int i=0; i<clues.length; i++)
set(clues[i]/100, (clues[i]%100)/10, clues[i]%10);
}
// the recursive backtracking function that does the hardwork
void solve(int r, int c)
{
while (((System.nanoTime() / 1000000000.0) - startTime) < 10) {
System.out.println("Time: " + ((System.nanoTime() / 1000000000.0) - startTime));
if (r<=9 && c<=9)
{
if (get(r,c) == 0)
{
for (int v=1; v<=COLS; v++)
{
set(r,c,v);
if (isCompatible(r,c))
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
set(r, c, 0);
}
else
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
else
{
solutionsCounter = solutionsCounter + 1;
//convert to seconds
endTime = System.nanoTime() / 1000000000.0;
// print();
}
}
}
// sample display function
void print()
{
for(int i=1; i<=ROWS; i++)
{
for (int j=1; j<=COLS; j++)
System.out.print(get(i,j));
System.out.println();
}
System.out.println("count: " + solutionsCounter);
}
void saveData (String[] data) throws java.io.IOException
{
try
{
java.io.BufferedWriter outfile = new java.io.BufferedWriter(new java.io.FileWriter("15-clue_results.csv", true));
for (int i = 0; i < data.length; i++) {
outfile.write(String.valueOf(data[i]));
outfile.append(',');
}
outfile.append('\n');
outfile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
static int countTotalRows () {
int count = 0;
try
{
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new java.io.FileReader("15-clue_results.csv"));
String input;
while((input = bufferedReader.readLine()) != null)
{
count = count + 1;
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return count;
}
public static void main(String []arg)
{
int numClues;
try {
java.io.BufferedReader csvFile = new java.io.BufferedReader(new java.io.FileReader("clue_set"));
String dataRow;
while ((dataRow = csvFile.readLine()) != null) {
SudokuBoard board = new SB_IntMatrix();
String[] stringSet = new String[15];
int[] PUZZLE1 = new int[15];
board.puzzleNum = board.puzzleNum + 1;
stringSet = dataRow.split(" ");
for (int i = 0; i < stringSet.length; i++) {
PUZZLE1[i] = Integer.parseInt(stringSet[i]);
}
board.incorporateClues(PUZZLE1);
for (int i = 0; i < 1; i++) {
board.solutionsCounter = 0;
board.solve();
board.data[0] = Integer.toString(board.puzzleNum);
board.data[1] = dataRow;
board.data[2] = Integer.toString(board.solutionsCounter);
board.data[3 + i] = Double.toString(board.endTime - board.startTime);
}
try
{
board.saveData(board.data);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
csvFile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
The requirement is to limit the solving time of solve(int r, int c) to only 1 hour.
To do this, I tried to put it inside a while loop while (((System.nanoTime() / 1000000000.0) - startTime) < 10) . The number 10 is to just test the code.
I understand that I looped it only 5 times in main method but, it resets back to 0 always and never stops and exceeds the limit of my loop in main.
You should use a Future:
final ExecutorService executor = Executors.newFixedThreadPool(4);
final Future<Boolean> future = executor.submit(() -> {
// Call solve here
return true;
});
future.get(60, TimeUnit.MINUTES); // Blocks
You can do something like:
Init the start date:
LocalDateTime startDateTime = LocalDateTime.now();
And check if 1 hour has elapsed:
LocalDateTime toDateTime = LocalDateTime.now();
if (Duration.between(startDateTime, toDateTime).toHours() > 0) {
// stop the execution
}

Display elements from List - Double type

i have problem with display elements from list.
Button action:
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
int lewy = Integer.parseInt(kresLewy.getText());
int prawy = Integer.parseInt(kresPrawy.getText());
licz(field.getText(),prawy,lewy);
}
});
Here is my list:
static public double licz(String wiersz, int lewy, int prawy) {
double wynik = 0.0;
///////Lista podawana z klawiatury z krokiem co 1
List<Double> listaX = new ArrayList();
for (int i = lewy; i <= prawy; i++) {
listaX.add((double) i);
}
System.out.println(listaX);
try {
StringReader tekstReader = new StringReader(wiersz);
wykresy.parser parser_obj
= new wykresy.parser(new wykresy.MyLexer(tekstReader));
TElement result = (TElement) parser_obj.parse().value;
wynik = result.oblicz();
System.out.println("WYNIK:" + wiersz + " = " + wynik);
} catch (Exception e) {
System.out.println("Podczs obliczenia wystapil blad. (" + e.getMessage() + ")");
} catch (Error error) {
System.out.println("Podczs obliczenia wystapil blad. (" + error.getMessage() + ")");
}
//}
return wynik;
}
I think problem is in "lewy" and "prawy", because list is empty. How can I solve it?
Just iterate through the list and print the values.
Using foreach loop:
for(Double d: listaX){
System.out.println(d);
}
Using functional operation:
listaX.forEach((d) -> {
System.out.println(d);
});
According to your edit, the only problem is: lewy, prawy are switched, so your loop goes from 10 to 0 -> which results in an empty list.
You have several problems:
lewy, prawy are switched
licz does not return something
wynik is unused
public static void main(String[] args) {
int lewy = 0;
int prawy = 10;
licz("Text",lewy, prawy);
}
static public void licz(String wiersz, int lewy, int prawy) {
double wynik = 0.0;
List<Double> listaX = new ArrayList();
for (int i = lewy; i <= prawy; i++) {
listaX.add((double) i);
}
System.out.println(listaX);
}
If you want to print out something you can use System.out.println(listaX), which prints the object to the console.
public static void main(String[] args) {
int lewy = 0;
int prawy = 10;
List<Double> listaX = new ArrayList();
for (int i = lewy; i <= prawy; i++) {
listaX.add((double) i);
}
System.out.println(listaX);
}
See this Post: How to print out all the elements of a List in Java?

java how to execute method

I have created a class Hotel defined as follows:
import java.util.Random;
public class Hotel {
private Osoba[] tab = new Osoba[100];
public void zamelduj(Osoba os, int num) {
if (tab[num - 1] == null) {
System.out.println("Pokoj o numerze " + num + "jest zajety");
return;
}
tab[num - 1] = os;
}
public void wymelduj(int num) {
tab[num - 1] = null;
}
public void zamienOsoby(int num1, int num2) {
Osoba o = tab[num1 - 1];
tab[num1 - 1] = tab[num2 - 1];
tab[num2 - 1] = o;
}
public void znajdzWolnePokoje() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println(i + 1);
}
}
public void przydzielPokoje50() {
for (int i = 0; i < 50; i++) {
Random r = new Random();
Osoba o = new Osoba();
int num = r.nextInt(100);
tab[num] = o;
}
}
public void wypisz() {
for (int i = 0; i < 100; i++) {
if (tab[i] == null) System.out.println("Pokoj nr. " + (i + 1) + " jest wolny");
else System.out.println("Pokoj nr. " + i + " jest zajety przez " + tab[i].imie + " " + tab[i].nazwisko);
}
}
public static void main(String[] args) {
Hotel h = new Hotel();
//h.przydzielPokoje50();
//h.wypisz();
h.zamelduj(null, 30);
}
}
I also have a class Osoba:
public class Osoba {
public String imie;
public String nazwisko;
Osoba() {
imie = null;
nazwisko = null;
}
Osoba(String imie, String nazwisko) {
this.imie = imie;
this.nazwisko = nazwisko;
}
}
I want to execute the method Zamelduj, which will assign a person (Osoba) to a cell in a table. However, every time I insert something other than null in the following it says that the first argument is not a capable parameter of the method.
h.zamelduj(null, 30);
What am I doing wrong?
I think your problem is that on the line " h.zamelduj(null, 30);" you need to create a new Osoba:
h.zamelduj(new Osoba("o.o", "._.!"), 30);
what happens is that the function is expecting a Osoba, if you give it another thing, it refuses. i hope it helps
You need to create an object of the class hotel (in your class from where you want to call the method type):
Hotel myObjectHotel = new Hotel();
And then you can call the method trough:
myHotelObject. zamelduj(give parameters here);
:)
Update:
Missed the real question. Just focused on the topic. I'm sorry. ;)

CombSort implementation in java

I am using Comb Sort to sort out a given array of Strings. The code is :-
public static int combSort(String[] input_array) {
int gap = input_array.length;
double shrink = 1.3;
int numbOfComparisons = 0;
boolean swapped=true;
//while(!swapped && gap>1){
System.out.println();
while(!(swapped && gap==1)){
gap = (int)(gap/shrink);
if(gap<1){
gap=1;
}
int i = 0;
swapped = false;
String temp = "";
while((i+gap) < input_array.length){
numbOfComparisons++;
if(Compare(input_array[i], input_array[i+gap]) == 1){
temp = input_array[i];
input_array[i] = input_array[i+gap];
input_array[i+gap] = temp;
swapped = true;
System.out.println("gap: " + gap + " i: " + i);
ArrayUtilities.printArray(input_array);
}
i++;
}
}
ArrayUtilities.printArray(input_array);
return numbOfComparisons;
}
The problem is that while it sorts many arrays , it gets stuck in an infinite loop for some arrays, particularly small arrays. Compare(input_array[i], input_array[i+gap]) is a small method that returns 1 if s1>s2, returns -1 if s1
try this version. The string array is changed to integer array (I guess you can change it back to string version). The constant 1.3 is replaced with 1.247330950103979.
public class CombSort
{
private static final int PROBLEM_SIZE = 5;
static int[] in = new int[PROBLEM_SIZE];
public static void printArr()
{
for(int i=0;i<in.length;i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
}
public static void combSort()
{
int swap, i, gap=PROBLEM_SIZE;
boolean swapped = false;
printArr();
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int)( gap / 1.247330950103979);
}
swapped = false;
for (i = 0; gap + i < PROBLEM_SIZE; ++i)
{
if (in[i] - in[i + gap] > 0)
{
swap = in[i];
in[i] = in[i + gap];
in[i + gap] = swap;
swapped = true;
}
}
}
printArr();
}
public static void main(String[] args)
{
for(int i=0;i<in.length;i++)
{
in[i] = (int) (Math.random()*PROBLEM_SIZE);
}
combSort();
}
}
Please find below implementation for comb sort in java.
public static void combSort(int[] elements) {
float shrinkFactor = 1.3f;
int postion = (int) (elements.length/shrinkFactor);
do {
int cursor = postion;
for(int i=0;cursor<elements.length;i++,cursor++) {
if(elements[i]>elements[cursor]) {
int temp = elements[cursor];
elements[cursor] = elements[i];
elements[i] = temp;
}
}
postion = (int) (postion/shrinkFactor);
}while(postion>=1);
}
Please review and let me know your's feedback.

How to use Multiple classes and methods in Java in which each class gets values from user

In this program i created simple addition, multiplication and transpose of given matrix a & b. I use three classes, in first class i get row and columns values from user and in second class, i created 7 methods. In first method i get values for matrix a & b from user. I get error from this first method of second class. i enclosed with output what error i get earlier.
import java.util.*;
class InitialValues
{
int row,col;
int taa = 0, tbb = 0, sum = 0, mul = 0;
void init()
{
Scanner ip1 = new Scanner (System.in);
System.out.print("Enter Row and column size : ");
row = ip1.nextInt();
col = ip1.nextInt();
System.out.println();
System.out.println("Row & Column : "+row+ " & " + col);
}
}
class GetdValue extends InitialValues
{
int [][] a = new int [row][col];
int [][] b = new int [row][col];
int i=0,j=0;
Scanner ip = new Scanner (System.in);
void getVal()
{
System.out.println("Enter A & B values"+" which having "+row+ " rows & " + col+" columns\n");
for (i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
a[i][j] = ip.nextInt();
b[i][j] = ip.nextInt();
//aa[i][j] = a [i][j];
//bb[i][j] = b [i][j];
}
System.out.println("\n");
}
}
{
int [][] aa = a;
int [][] bb = b;
}
void displayA()
{
for (i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
System.out.print(a[i][j]+" " );
}
System.out.println("\n");
}
}
void displayB()
{
for (i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
System.out.print(b[i][j]+" " );
}
System.out.println("\n");
}
}
/*void displayAdd()
{
for (i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
sum = a[i][j]+b[i][j];
System.out.print(sum+" " );
}
System.out.println("\n");
}
}
void displayMul()
{
for (i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
mul = a[i][j]*b[i][j];
System.out.print(mul+" " );
}
System.out.println("\n");
}
}
/*void displayTransposeA()
{
for (i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
taa = aa[j][i];
System.out.print(taa+" " );
}
System.out.println("\n");
}
}
void displayTransposeB()
{
for (i=0;i<col;i++)
{
for(j=0;j<row;j++)
{
tbb = bb[j][i];
System.out.print(tbb+" " );
}
System.out.println("\n");
}
}*/
}
class Matrixx
{
public static void main (String arg[])
{
//InitialValues in = new InitialValues();
//in.init();
System.out.println();
GetdValue ob = new GetdValue();
ob.init();
ob.getVal();
//ob.displayA();
//ob.displayB();
}
}
output:
Enter Row and column size : 2 2
Row & Column : 2 & 2
Enter A & B values which having 2 rows & 2 columns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GetdValue.getVal(Matrixx.java:37)
at Matrixx.main(Matrixx.java:136)
The row and col (defined in the super class) are zeros
at the moment when you allocate space for the a and b arrays.
So actually you create two arrays a and b of sizes [0][0].
And so you get this exception when you try accessing a[0][0].
You should give some non-zero values to row and col.
See your fixed code below.
Note the init method in GetdValue.
import java.util.*;
class InitialValues {
int row, col;
int taa = 0, tbb = 0, sum = 0, mul = 0;
void init() {
Scanner ip1 = new Scanner(System.in);
System.out.print("Enter Row and column size : ");
row = ip1.nextInt();
col = ip1.nextInt();
System.out.println();
System.out.println("Row & Column : " + row + " & " + col);
}
}
class GetdValue extends InitialValues {
int[][] a;
int[][] b;
int i = 0, j = 0;
Scanner ip = new Scanner(System.in);
public void init(){
super.init();
a = new int[row][col];
b = new int[row][col];
}
void getVal() {
System.out.println("Enter A & B values" + " which having "
+ row + " rows & " + col + " columns\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
a[i][j] = ip.nextInt();
b[i][j] = ip.nextInt();
// aa[i][j] = a [i][j];
// bb[i][j] = b [i][j];
}
System.out.println("\n");
}
}
{
int[][] aa = a;
int[][] bb = b;
}
void displayA() {
for (i = 0; i < col; i++) {
for (j = 0; j < row; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("\n");
}
}
void displayB() {
for (i = 0; i < col; i++) {
for (j = 0; j < row; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println("\n");
}
}
/*
* void displayAdd() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { sum =
* a[i][j]+b[i][j]; System.out.print(sum+" " ); } System.out.println("\n");
* } }
*
* void displayMul() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { mul =
* a[i][j]*b[i][j]; System.out.print(mul+" " ); } System.out.println("\n");
* } }
*
*
* /*void displayTransposeA() { for (i=0;i<col;i++) { for(j=0;j<row;j++) {
* taa = aa[j][i]; System.out.print(taa+" " ); } System.out.println("\n");
* } }
*
* void displayTransposeB() { for (i=0;i<col;i++) { for(j=0;j<row;j++) { tbb
* = bb[j][i]; System.out.print(tbb+" " ); } System.out.println("\n"); } }
*/
}
class Matrixx {
public static void main(String arg[]) {
// InitialValues in = new InitialValues();
// in.init();
System.out.println();
GetdValue ob = new GetdValue();
ob.init();
ob.getVal();
// ob.displayA();
// ob.displayB();
}
}
Declare a and b arrays in InitValues class and initialize them in your init method after row and col initialization.

Categories