Program would neither execute or terminate - java

After trying out a few ways to fix my code from an arrayindexoutofbound exception, there's one way it wouldn't produce the exception, however the program would not output anything like it should, it would not throw exceptions or errors, and it shows that the program is not terminated. Here's the code:
import java.util.*;
public class treez {
final Scanner in;
public treez()
{
in=new Scanner(System.in);
run();
in.close();
}
public void run()
{
System.out.println("Enter normal restaurant numbers and pho restaurant numbers");
final String input=in.nextLine();
final int[] rest=createarray(input);
final int normal=rest[0];
final int pho=rest[1];
final String input1=in.nextLine();
final int[] phoresspecific=createarray(input1);
Arrays.sort(phoresspecific);
boolean[][] matrix;
matrix=new boolean[normal][normal];
for(int i=0;i<normal;i++)
{
for(int j=0;j<normal;j++)
{
matrix[i][j]=false;
}
}
int[] total=new int[normal];
for(int i=0;i<matrix.length;i++) matrix[i]=new boolean[normal];
for(int i=0;i<normal;i++)
{
total[i]=i;
total[i]=Arrays.binarySearch(total, i);
}
Arrays.sort(total);
for(int i=0 ; i < normal - 1; i++) {
int x = 0;
int y = 0;
String ans = in.nextLine();
int[] arraya = createaarray(ans);
x = arraya[0];
y = arraya[1];
matrix[x][y]= true;
matrix[y][x]=true;
}
in.close();
int answer=decisions(pho,matrix,phoresspecific,normal);
System.out.println(answer);
}
private int decisions(int pho, boolean matrix[][],int[] phoresspecific,int normal)
{
int steps=0;
if(pho==2)
{
for(int j=0;j<normal-1;j++)
{
for(int i=phoresspecific[0];i<normal-1;i++)
{
if(matrix[j][i]==true)
{
j++;
steps++;
if(j==phoresspecific[1]) break;
}
}
if(j==phoresspecific[1]) break;
}
}
else
{
int counter=0;
int[] step=new int[pho-1];
for(int j=0;j<pho-1;j++)
{
counter=0;
for(int i=0;i<normal-1;i++)
{
for(int l=phoresspecific[j];l<normal-1;l+=0)
{
if(matrix[i][l]==true)
{
i++;
step[j]++;
if(i==j)
{
counter++;
}
}
}
if(counter==pho) break;
}
}
Arrays.sort(step);
steps=step[0];
}
steps--;
return(steps);
}
private int[] createarray(final String input)
{
final String[] args=input.trim().split("\\s+");
final int[] list=new int[2];
for(int i=0;i<2;i++)
list[i]=Integer.parseInt(args[i]);
return list;
}
private int[] createaarray(final String ans)
{
final String[] args=ans.trim().split("\\s+");
final int[] list=new int[2];
for(int i=0;i<2;i++)
list[i]=Integer.parseInt(args[i]);
return list;
}
public static void main(String args[])
{
new treez();
}
}
From the previous mistakes, I believe the error is either in line 83 or 85, which are:
for(int l=phoresspecific[j];l<normal-1;l+=0)
{
if(matrix[i][l]==true)
in
for(int l=phoresspecific[j];l<normal-1;l+=0)
{
if(matrix[i][l]==true)
{
i++;
step[j]++;
if(i==j)
{
counter++;
}
}
}
With input:
8 5
0 6 4 3 7
0 1
0 2
2 3
4 3
6 1
1 5
7 3
The program would neither produce an output or terminate. Help would be appreciated.
Edit:the exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at treez.decisions(treez.java:85)
at treez.run(treez.java:52)
at treez.<init>(treez.java:9)
at treez.main(treez.java:127)
Edit2:This program is used to determine the minimum time used for a person to reach all the locations wrote in from input line 2. There's no edge weight since it takes one minute from one place to another. All the lines after second lines states there is a road connecting place a and b.

Have you checkt your build configurations?
And its kind a hard looking for possible errors when you provide not a lot of information about your program.
EDIT: I managed to get it running and can confirm that you program (with your input does not return anything and I didn't step trough every piece of code)
But you always use the "createarray" function, which you have two times implemented and its the same function (exept of the name of the value you pass).
Then you have an infinite loop in this code:
for(int i=0;i<normal-1;i++){
for(int l=phoresspecific[j];l<normal-1;l+=0){
if(matrix[i][l]==true){
i++;
step[j]++;
if(i==j) counter++;
}
}
if(counter==pho) break;
}
The inner for-loop doesnt increment its value and is always trying to evaluate the if condition wich will always stay the same due to the never changing index l . That is probably your error.
Another EDIT:
In the second line of your parameters you have more than two values, but your functions always read only two parameters.

Related

trying to print arrays in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I had a code I needed to submit and every time I try to run it, I get the same errors over and over again.
Here's the question
Write the following Java methods:
(a). readValues to input ten integer values into an array of integers
TAB from a text file “Values.txt”. This array TAB is passed to the
method as parameter. Assume that the number of students in the file is
equal to the length of the array.
(b). oddValues that takes the array TAB as parameter and returns the
number of odd values found in TAB.
(c). replaceOdd that takes the array TAB as a parameter. It should
replace every odd value in TAB by the sum of all odd values.
Hint: your method must first compute the sum of all odd values.
(d). printValues that takes the array TAB as a parameter and prints
its content on the screen.
(e). main that declares the array TAB and calls the above four
methods.
N.B.: In your program, use the methods and variable names as mentioned
above.
And this is the code:
import java.util.*;
import java.io.*;
public class Finalexam
{
public static void main (String [] args ) throws FileNotFoundException
{
int sum=0;
int [] TAB=new int [10];
ReadValues(TAB);
oddValues(TAB);
replaceOdd(TAB);
printValues(TAB);
System.out.println("The sum is" + sum);
}
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
public static double oddValues(int[] TAB)
{
int i;
double odd=0;
int fn=0;
for(i=1; i<odd; i++){
while(odd % 2 !=0)
{
odd = fn;
}
break;
}
return fn;
}
public static int replaceOdd(int[] TAB)
{
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
public static void printValues(int[] TAB)
{
int i;
for(i=0; i<10; i++){
System.out.println(TAB[i]+"\t");
}
System.out.println();
}
}
In which part I'm doing wrong? I cant even run it.
Firstly there is a compilation error in your code.
In your method
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
You have too many extra brackets, well thats not the problem though, the problem is the scanner object s is declared inside the for loop where as you are closing it later outside the loop, since the scope of the variable is not outside the loop, hence the error.
The correct way should be
public static void readValues (int [] tab){
int i;
Scanner s = new Scanner ("Values.txt") ;
for(i=0; i<10; i++){
tab[i]=s.nextInt();
}
s.close();
}
Also there are many thing that will work in your code but is a bad practice or is not following conventions.
Variable names (e.g tab) should always be in camel case. It should only be a capital if it is a constant, which is not in your case.
The method names starts with small letter.
Also you are calling the two methods replaceOdd(TAB) and oddValues(TAB) But the return value is not being used anywhere.
FileNotFoundException will never be thrown
If you closely look at this method below
public static double oddValues(int[] TAB) {
int i;
double odd = 0;
int fn = 0;
for (i = 1; i < odd; i++) {
while (odd % 2 != 0) {
odd = fn;
}
break;
}
return fn;
}
The loop will never execute as odd is 0 so i<odd will always be false. Also the logic for odd is wrong.
public static int replaceOdd(int[] TAB){
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
This method will always return zero, the logic is wrong.
There are many more logical errors. I would suggest you to look into them as well

Java- function seems to mess up the console, nothing will be printed out after calling the function

I was asked to program a method that receives a scanner, and returns a sorted array of words which contain only letters, with no repetitions (and no bigger in length than 3000). Then, I was asked to program a method that checks whether a certain given string is contained in a given vocabulary. I used a simple binary search method.
This is what I've done:
public static String[] scanVocabulary(Scanner scanner){
String[] array= new String[3000];
int i=0;
String word;
while (scanner.hasNext() && i<3000) {
word=scanner.next();
if (word.matches("[a-zA-Z]+")){
array[i]=word.toLowerCase();
i++;
}
}int size=0;
while (size<3000 && array[size]!=null ) {
size++;
}
String[] words=Arrays.copyOf(array, size);
if (words.length==0 || words.length==1) {
return words;
}
else {
Arrays.sort(words);
int end= removeDuplicatesSortedArr(words);
return Arrays.copyOf(words, end);
}
}
private static int removeDuplicatesSortedArr(String[] array) { //must be a sorted array. returns size of the new array
int n= array.length;
int j=0;
for (int i=0; i<n-1; i++) {
if (!array[i].equals(array[i+1])) {
array[j++]=array[i];
}
}
array[j++]=array[n-1];
return j;
}
public static boolean isInVocabulary(String[] vocabulary, String word){
//binary search
int n=vocabulary.length;
int left= 0;
int right=n-1;
while (left<=right) {
int mid=(left+right)/2;
if (vocabulary[mid].equals(word)){
return true;
}
else if (vocabulary[mid].compareTo(word)>0) {
right=mid-1;
}else {
right=mid+1;
}
}
return false;
}
while trying the following code:
public static void main(String[] args) {
String vocabularyText = "I look at the floor and I see it needs sweeping while my guitar gently weeps";
Scanner vocabularyScanner = new Scanner(vocabularyText);
String[] vocabulary = scanVocabulary(vocabularyScanner);
System.out.println(Arrays.toString(vocabulary));
boolean t=isInVocabulary(vocabulary, "while");
System.out.println(t);
System.out.println("123");
}
I get nothing but-
[and, at, floor, gently, guitar, i, it, look, my, needs, see, sweeping, the, weeps, while]
nothing else is printed out nor returned. Both functions seem to be working fine separately, so I don't get what I'm doing wrong.
I would be very happy to hear your thoughts, thanks in advance :)
This has nothing to do with the console. Your isInVocabulary method is entering an infinite loop in this block:
if (!isInVocabulary(vocabulary, "while")) {
System.out.println("Error");
}
If you were to debug through isInVocabulary, you would see that after a few iterations of the while loop,
left = 0;
right = 2;
mid = 1;
if (vocabulary[mid].equals(word)){
// it doesn't
} else if (vocabulary[mid].compareTo("while") > 0) {
// it doesn't
} else {
right = mid + 1;
// this is the same as saying right = 1 + 1, i.e. 2
}
So you'll loop forever.

Java check the array contains certain values in order [duplicate]

This question already has answers here:
Find an array inside another larger array
(15 answers)
Closed 4 years ago.
I defined an array which contains random numbers.I get some numbers from the user and put them in other array.I want to check whether first array contains the second array in order.My code is not enough to check order.It is just checking contains or not.
EX:
arr1=[45, 21,1,19 ,8,90,21,2] ,arr2=[21,1,19]
result=TRUE
arr1=[45,21,1,19,8,90,21,2] ,arr2=[21,19] result=FALSE
public class Main {
private static int[] array1;
public static int[] list() {
array1 = new int[10];
for(int i=0;i<array1.length;i++)
{
array1[i] = randomFill();
}
return array1;
}
public static void print()
{
for(int n: array1)
{
System.out.println(n+" ");
}
}
public static int randomFill()
{
Random rand = new Random();
int randomNum = rand.nextInt(90)+10; //to generate two digits number which is between 10-99 to the array
return randomNum;
}
public static void main(String args[])
{
list();
print();
Scanner s=new Scanner(System.in);
System.out.println("How many numbers will you add? ");
int n=s.nextInt();
int array2[]=new int[n];
System.out.println("Enter the numbers:");
for(int i=0;i<n;i++){//for reading array
array2[i]=s.nextInt();
}
for(int i: array2){ //for printing array
System.out.println(i);
}
int result=0;
for(int i=0;i<array1.length;i++)
{
for(int j=0;j<array2.length;j++)
{
if(array1[i]==array2[j])
{
result=result+1;
}
}
}
if(result==n)
{
System.out.println("TRUE");
}
else
{
System.out.println("false");
}
}
}
Here is the hard way without any helper
Integer i,j,k;
Boolean found=false;
for(i=0;i<arr1.length;i++) {
// we look for the index of the first element of the second array in the original one
if(arr2[0] == arr1[i] ) {
found=true;
// after that we iterate in both arrays simultaneously
for(j=1, k=i+1; j<arr2.length; j++,k++) {
// if we complete the iteration of the original array
// or if we find any two elements not equal we break
// we set then the boolean variable to false
if( k>=arr1.length || arr2[j] != arr1[k] ) {
found=false;
break;
}
}
if(found) break;
}
}
System.out.println(found);

Finding a duplication of an integer pattern in an array list

I have to find a pattern in the array that I am creating and then stop adding numbers to the array when the pattern is seen to be duplicated twice. The pattern that I am trying to find is 4-2-1, so when that is repeated twice in a row in this arithmetic sequence, the program is finished. Currently my output gives me one sequence of the pattern with an error following: [10, 5, 16, 8, 4, 2, 1] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 0
**YES I HAVE TRIED TO DEBUG USING ECLIPSE BUT I AM STILL STUCK So if someone could help me figure out why it is only printing the sequence with one repetition of the pattern at the end, that would help me profusely. Thanks. My code:
Scanner inData = new Scanner(new File("test.txt"));
ArrayList<Integer> list= new ArrayList<Integer>();
while (inData.hasNext())
{
int numA=inData.nextInt();
int var;
boolean done=false;
list.add(numA);
while(!done)
{
var=list.size();
for(int i=var;i>0;i--)
{
numA=list.get(var-1);
if(numA%2==0)
{
numA/=2;
list.add(numA);
}
else
{
numA=(numA*3)+1;
list.add(numA);
}
var=list.size();
if (var>6)
{
for(int j=1;j>=6;j++)
{
if(list.get(var-1)==1)
{
if(list.get(var-4)==1)
{
if(list.get(var-2)==2)
{
if(list.get(var-5)==2)
{
if(list.get(var-3)==4)
{
if(list.get(var-6)==4)
{
done=true;
}
}
}
}
}
}
}
System.out.print(list);
list.clear();
}
}
}Scanner inData = new Scanner(new File("test.txt"));
ArrayList<Integer> list= new ArrayList<Integer>();
while (inData.hasNext())
{
int numA=inData.nextInt();
int var;
boolean done=false;
list.add(numA);
while(!done)
{
var=list.size();
for(int i=var;i>0;i--)
{
numA=list.get(var-1);
if(numA%2==0)
{
numA/=2;
list.add(numA);
}
else
{
numA=(numA*3)+1;
list.add(numA);
}
var=list.size();
if (var>6)
{
for(int j=1;j>=6;j++)
{
if(list.get(var-1)==1)
{
if(list.get(var-4)==1)
{
if(list.get(var-2)==2)
{
if(list.get(var-5)==2)
{
if(list.get(var-3)==4)
{
if(list.get(var-6)==4)
{
done=true;
}
}
}
}
}
}
}
System.out.print(list);
list.clear();
}
}
}
The simplest approach is using Collections.indexOfSubList. Something like this.
int a [] = {4,2,1,4,2,1};
if(Collections.indexOfSubList(list, Arrays.asList(a))!=-1){
return true;
}
return false
Well, there appear to be a few errors with your code.
I'm going to enumerate some here: fix as many as possible, then check to see if your code works.
int i=var; i>0; i--. Since var is the size of your array, it is outside the bounds. Java uses 0-based arrays, meaning that valid indeces are in the range [0,size-1] (inclusive). Replace with int i=var - 1; i >= 0; i--
The j loop does nothing but prevent anything from happening (nothing can enter, since you start at 1 and immediately break the loop by imposing the restriction >=6 and j is never used. Remove the loop.

NullPointerException in the push() part of a stack implementation in a java program

My code is basically a program to check whether it is possible to use the ordered sequence 1,2,3..,n to generate a permutation of this sequence as specified by the user using a stack as temporary storage structure. The user has the option of entering n and the permutation he'd like to see generated using 2 methods; either through a text file or directly in the command line.
So, for example if the user enters 5 1 3 5 4 2, the n would be interpreted as the first number, i.e. 5 and then the rest of the digits is the permutation he'd like to see if it's possible to generate starting from 1 2 3 4 5 (Note that 1 2 3 4 5 is ordered and 1 is at the top of that stack). Here you'd have 1 being used directly, then 2 being stored in a stack, then 3 being used, then 4 stored on top of 2, then 5 being used, then 4 popped out followed by 2 being popped to generate the permutation.
The problem I'm having is my program faces a NullPointerException whenever I try to generate the starting stack of 1 2 3 ... n. It points to the last line of this block of code:
public static void main(String args[])
{
int[] arr;
arr = null;
try
{
if(args[0].charAt(0) == '2')
{
try
{
FileInputStream file = new FileInputStream(args[1]);
arr = input(file);
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
}
else if (args[0].charAt(0) == '1')
{
arr = input();
}
else
{
System.out.println("Please enter a valid input option.");
System.exit(0);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Please enter a valid input option.");
System.exit(0);
}
int x;
x = arr.length;
System.out.println(x);
ArrayPerm start = new ArrayPerm(x);
ArrayPerm temp = new ArrayPerm(x);
for (int i = 0; i < x; i++)
{
*start.push(x - i);*
}
And it also points to:
public void push(int j)
{
top++;
Stack[top] = j;
}
The ArrayPerm class is basically the stack implementation.
I tried doing this:
public void push(Integer j)
{
if (j == null)
{
throw new NullPointerException("NULL ELEMENT!");
}
else
{
top++;
Stack[top] = j;
}
}
But it's still showing the exception. If anyone could point me in the right direction I'd really appreciate it. I've spent an hour looking for the problem in my code without result.
So, thanks in advance!
EDIT: This is how the class is defined, so Stack shouldn't be initialized?
public class ArrayPerm
{
private int[] Stack;
private int top;
public int size;
public ArrayPerm(int n)
{
size = n;
int[] Stack = new int[n];
top = -1;
}
You're shadowing the variable Stack. Replace
int[] Stack = new int[n];
with
stackArray = new int[n];
You haven't initialized the 'Stack' member variable.

Categories