BlueJ - BlueJ freezes when reading in from a text file - java

So for my computer science class we had to create a program that will read in from a text file named "compact.txt" and have the integers inside stored into an int[]. After that we have to print the numbers to the terminal with the 0s contained in the text file and then without the 0s contained in the text file. The code compiles and runs, but when it runs it does not print anything to the terminal and it completely freezes all of BlueJ. After the freeze I can't even copy the code from inside the main and have to force close it from task manager. FileInput is what my class uses to read in files. Here is my code:
import chn.util.*;
public class compact
{
public static void main(String [] args)
{
FileInput fI = new FileInput("compact.txt");
int[] ar = new int[100];
String line = fI.readLine();
fI.close();
System.out.println(line);
int count = 0;
int x = 0;
while(x < line.length())
{
if(!line.substring(x, x+1).equals(" "))
{
if(!line.substring(x + 1, x + 2).equals(" ") && !
(line.length() - 1 == x))
{
ar[count] = Integer.parseInt(line.substring(x + 1, x+2));
}
else
{
ar[count] = Integer.parseInt(line.substring(x, x+1));
}
count++;
}
x++;
}
System.out.print("Before: " + ar[0]);
for(int i = 1; i < count; i++)
{
System.out.print(", " + ar[i]);
}
System.out.print("\n");
System.out.println("After: ");
for(int i = 0; i < count; i++)
{
if(ar[i] == 0)
{
System.out.print("");
}
else
{
if(i == count - 1)
{
System.out.print(ar[i]);
}
System.out.print(ar[i] + ", ");
}
}
}
}
And this is what is contained inside of the "compact.txt" file:
0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0

So, I get a StringIndexOutOfBoundsException because when x is equal to line.length() - 1, x + 1 or x + 2 exceeds the length of the String.
This generally means your logic is broken. While you could go back with pen a paper and nut it out, a better approach might be to use:
java.util.Scanner...
String line = "0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0";
Scanner scan = new Scanner(line);
while (scan.hasNextInt()) {
System.out.println(scan.nextInt());
}
This will allow you to get each individual int element from the original String
Or String#split...
String line = "0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0";
String[] parts = line.split(" ");
which will give you an array of Strings split by the space.
From there you can decide how best to approach separating the 0s (or, simply filter the output using a if statement)

Related

How can I print out 1-50 even numbers only, but the it start a new line every multiples of 10. (JAVA)

I'm a newbie, but I'm willing to learn how to code.
I tried using this code:
int n = 50;
int counter = 0;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
counter++;
if (counter == 2) {
System.out.println(i + " ");
counter = 0;
%10== 0
to find all even numbers between 1 to 50 and make a new line at multiples of 10 just follow these steps -
Make one loop which will go 1 to 50
Check if the number is even by checking the remainder after diving it with 2, if YES print that number.
Check if the number is a multiple of 10 by checking the remainder after dividing it by 10, if YES make a new line
The code will look something like this -
int i = 1;
while(i<=50){
if(i%2 == 0) System.out.print(i + " ");
if(i%10 == 0) System.out.println();
i++;
}
Output -
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
It's up to you which looping method you want to use for me While loop looks cleaner.
I hope this solves all your queries.
PFB Snippet:
public class Main
{
public static void main(String[] args) {
for(int i=1;i<=50;i++){
if (i%2 == 0) //Check whether number is even
{
System.out.print(i+" ");
if (i%10 == 0) // Check if it is multiple of 10
{
System.out.print("\n");
}
}
}
}
}
Output:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"\n" is a Escape Sequence which means new line

How do I print out only 10 elements per line for my array?

I created an array with 50 elements.
The first 25 elements are equal to the square of the index and the last 25 elements are equal to the index times 3.
This is my current output: 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147
My desired output is this:
0 1 4 9 16 25 36 49 64 81
100 121 144 169 196 225 256 289 324 361
400 441 484 529 576 75 78 81 84 87
90 93 96 99 102 105 108 111 114 117
120 123 126 129 132 135 138 141 144 147
I have tried using the formatting feature (printf), but I can't seem to get it to work. I've also tried using an if statement, but that gave me a "cannot convert int to boolean" error.
I've searched some similar questions but their solutions are either too complex for me to understand or they don't work for my specific code since I am already using for loops.
Does anybody have an easy way to achieve this? This is for a homework assignment. I have the logic part down, which ironically should be the hard part but this formatting part has me stumped lol
I appreciate any help!
This is my code right now:
int [] Number = new int [50];
for(int i = 0; i < Number.length/2; i++) {//first loop
System.out.print(i * i + " ");
}
for(int i = 25; i < Number.length; i++) {//second loop
System.out.print(i * 3 + " ");
}
You don't need an array. What you want to do is:
Loop 50 times
1st time, set i to 0
2nd, set i to 1
50th time, set i to 49
Each time:
if i < 25 print i * i
if i >= 25 print i * 3
Every 10th time, print a new line.
Here is how you can do it without an array:
int size = 50;
for (int i = 0; i < size; i++) {
// Print a newline after every 10 elements
if (i != 0 && i % 10 == 0) {
System.out.println();
}
// Print i * i for 0 up to but excluding 25
// Print i * 3 after that
if (i < size / 2) {
System.out.print(i * i + " ");
} else {
System.out.print(i * 3 + " ");
}
}
If you really wanted to loop over the elements of an array:
int[] myArr = new int[50];
for (int i = 0; i < myArr.length; i++) {
if (i != 0 && i % 10 == 0) {
System.out.println();
}
if (i < size / 2) {
System.out.print(i * i + " ");
} else {
System.out.print(i * 3 + " ");
}
}
Also it is not a good idea to name a variable as Number, because:
There is already a class in Java called Number and that can confuse readers.
Variables in Java by convention should be in camelCase. Class names in PascalCase (see here).
Try this:
int[] Number = new int[50];
for (int i = 0; i < Number.length / 2; i++) {//first loop
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(i * i + " ");
}
for (int i = 25; i < Number.length; i++) {//second loop
if (i % 10 == 0) {
System.out.println();
}
System.out.print(i * 3 + " ");
}
Does the array require to store the correct values?
int[] numbers = new int[50];
for (int i=0; i<numbers.length; ++i) { //calculating correct value into the array
numbers[i] = (i < 25) ? i * i : i * 3;
}
for (int i=0; i<numbers.length; ++i) { //displaying data
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
I hope this helps
int[] arrNum = new int[50];
for (int i = 0; i < numbers.length; ++i) { //First loop to enter the data
numbers[i] = ((i < 25) ? i * i : i * 3);
}
for (int i = 0; i < numbers.length; ++i) { //Second loop to output data
if (i % 10 == 0) System.out.println;
System.out.print(numbers[i] + " ");
}
int[] array = new int[50];
int count = 0; // To print 10 elements per line
for(int I = 0; I < array.length; I++) {
if (count == 10) {
System.out.println();
count = 0;
}
System.out.print(a1[i] + " ");
count++;
}

How to check duplicate numbers and print out the read input numbers in the same order that they were read (excluding all duplicates.)

I'm trying to write a code. There I'll get max 1000 (int)inputs from an user (it has to be array[1000]) and it'll print out the ints in the same order as they were written.
Reading can be stopped by ctrl+z if the user wants that. The program will not write out duplicate numbers.
Example;
Input: 45 77 -22 3 45 0 21 -1 3
Output: 45 77 -22 3 0 21 -1
So far I've coded(within 2 days):
static int i = 0;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] array = new int[1000];
int[] arrayCopy = new int[1000];
int k=0,j=0;
System.out.println("enter your integer numbers");
while(input.hasNext())
{
array[i] = input.nextInt();
for(j =0 ; j< array.length; j++)
{
arrayCopy[j] = array[j];
}
for( k =1; k<arrayCopy.length; k++)
{
int aV = arrayCopy[k];
}
i++;
}
input.close();
}
}
Use a HashMap to keep track of numbers already seen. Only add to your output string if it is a new number. You can modify your code with the following:
int[] array = new int[1000];
Scanner input = new Scanner(System.in);
int index = 0;
while(input.hasNext()) {
array[index] = input.nextInt();
index++;
}
HashMap<Integer, Boolean> seenNumbers = new HashMap<Integer, Boolean>();
String result = "";
for (int i = 0; i < index; i++) {
int value = array[i];
if (!seenNumbers.containsKey(value)) {
result += " " + value;
seenNumbers.put(value, true);
}
}
System.out.println(result);
The simplest solution is for me to use LinkedHashSet - will not allow duplicates and preserves insertion order
Set <Integer> set = new LinkedHashSet<>(1000);
while (input.hasNext()) {
int next = input.nextInt();
set.add(next);
}
input.close();
for (Integer number : set) {
System.out.print(number+" ");}
Should work
Provided you can resolve a sort order, and use arrays:
Below pseudocode and data. It's written as arrays, but you can ofc always loop where required. I also write the data without commas, as that's what my language Dyalog APL outputs ;-), but the data below are simply 9-element 1-dimensional arrays. The result seems to hold 7 elements.
You have
A = 45 77 -22 3 45 0 21 -1 3
Resolve the ascending sort order for A:
order = 3 8 6 4 9 7 1 5 2 // A[3] is smallest, then A[8], A[6], etc.
Write:
B = A[order] // B now holds: -22 -1 0 3 3 21 45 45 77
Loop through all but first element of B, check if next element is same as current. Write the result to C, which is a same-length vector of zeroes, however first element of C must be 1:
C = 1 0 0 0 0 0 0 0 0
s = 2
:While (s <= [length of C])
C[s] = (B[s-1] == B[s]) // C[s] is 0 or 1
s += 1
:End
Now C holds:
1 1 1 1 0 1 1 1 0
Create an empty variable D (or just copy from A or B - you will overwrite it):
D = A
Assign the elements of D as follows:
D[order] = C // D now holds: 1 1 1 1 0 1 1 1 0
Take only D elements of A (you pick elements of A and append them to a Result, which is initially empty - ie. has zero length):
s = 1
:While (s <= [lenght of A])
:if D[s] // Means: If (D[s] == 1)
[append A[s] to Result]
s += 1
:End
:End
Result now contains
45 77 -22 3 0 21 -1
Use Set instead of array. Set wont add duplicates.

longest common subsequence function does not work for all examples

EDIT: UP
The code does not work properly with the strings below.
"1 11 23 1 18 9 15 23 5"
"11 1 18 1 20 5 11 1"
EDIT: I noticed, that if I change 20 to 40 in second string, the function works properly...
For strings:
"12 4 55 11 8 43 22 90 5 88 15"
"15 66 4 36 43 22 78 88 32"
it works properly. Where is the problem?
Here is my code:
int[][] tabelka = new int[linia1.length()+1][linia2.length()+1];
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
if ( linia1.charAt(i) == linia2.charAt(j) ) {
tabelka[i+1][j+1] = tabelka[i][j] + 1;
}
else {
tabelka[i+1][j+1] = Math.max(tabelka[i+1][j], tabelka[i][j+1]);
}
}
}
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
System.out.println(tabelka[i][j]);
}
}
StringBuffer podciag = new StringBuffer();
for(int x = linia1.length(), y = linia2.length(); x != 0 && y != 0; ) {
if( tabelka[x][y] == tabelka[x-1][y] ) {
licznik++;
x--;
}
else if( tabelka[x][y] == tabelka[x][y-1] ) {
licznik++;
y--;
}
else {
licznik++;
assert linia1.charAt(x-1) == linia2.charAt(y-1);
podciag.append(linia1.charAt(x-1));
x--;
y--;
}
}
String buff = podciag.reverse().toString();
The output of this code (for the first two strings) is:
11 1 18 1 2 5
However, the output should be:
11 1 18 5
For a full / better explanation, please refer to:
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
http://www.geeksforgeeks.org/printing-longest-common-subsequence/
I think that you are constructing the array correctly. However, I am not sure about the way the table is being read in order to construct the LCS.
The idea is to start at the end of the 2D array solution[str1.length()][str2.length()] and if:
The last characters of str1 and str2 are equal then the last character is part of the LCS and decrement both indexes
If they are not equal, compare solution[i-1][j] and solution[i][j-1] and go in direction of greater value.
Repeat until either of the indexes are 0.

Pascal Triangle Not Printing Correctly in Java?

I got an assignment that requires us to print out pascal's triangles based on the user entered value of N. We were provided a main that allows the user to calculate Pascal’s Triangle based on a value of n. In this case if n is 0, then Pascal’s Triangle is 1. Otherwise for n being greater than 0, the appropriate Pascal’s Triangle will be created and displayed. Here is the main:
public class CSCD210Lab13
{
public static void main(String[] args)
{
int n = 0;
int [][] pascal = null;
do
{
n = Lab13Methods.readN();
pascal = Lab13Methods.createPascalsTriangle(n);
Lab13Methods.printPascals(pascal);
}while(MyUtil.goAgain());
}// end main
}// end class
Here is my Methods file:
import java.util.*;
public class Lab13Methods
{
public static int readN()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter N: ");
int n = kb.nextInt();
while(n < 0)
{
System.out.println("Number Below 1. Re-Enter: ");
n = kb.nextInt();
}
return n;
}
public static int[][] createPascalsTriangle(int n)
{
int[][]pascalTri = new int[n + 1][(n + 1) * 2];
int sideOne, side;
pascalTri[0][n - 1] = 1;
sideOne = side = n - 1;
for (int y = 1; y < n; y++)
{
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
sideOne--;
side++;
for (int k = 1; k <= y; k++)
{
int left = pascalTri[y - 1][sideOne + (2 * k) - 1];
int right = pascalTri[y - 1][sideOne + (2 * k) + 1];
pascalTri[y][sideOne + (2 * k)] = left + right;
}
}
return pascalTri;
}
public static void printPascals(int[][]pascal)
{
for (int f = 0; f < pascal.length; f++)
{
for (int v = 0; v < pascal[f].length; v++)
{
if (pascal[f][v] == 0)
{
System.out.print("");
}
else
{
System.out.print(pascal[f][v]+" ");
}
}
System.out.println();
}
}
}
Here is my goAgain file:
public static boolean goAgain()
{
boolean goAgain = false;
String answer;
Scanner kb = new Scanner(System.in);
System.out.println();
System.out.print("Do you want to go again? ");
answer = kb.nextLine();
while(!answer.equalsIgnoreCase("yes") && !answer.equalsIgnoreCase("no"))
{
System.out.print("Invalid Input. Do you want to go again? ");
answer = kb.nextLine();
}
if(answer.equalsIgnoreCase("yes"))
{
goAgain = true;
}
else if(answer.equalsIgnoreCase("no"))
{
goAgain = false;
}
return goAgain;
}
}
My question is about how it's printing. If I enter 10 to be the value of N, this is how it is supposed to print:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
However, this is how mine prints:
1
1 1 1 1
1 1 2 1 1
1 1 3 3 1 1
1 1 4 6 4 1 1
1 1 5 10 10 5 1 1
1 1 6 15 20 15 6 1 1
1 1 7 21 35 35 21 7 1 1
1 1 8 28 56 70 56 28 8 1 1
What am I doing wrong?
I think your error may be here:
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
sideOne--;
side++;
Your program is designed to fill in the cells of the array in a checkerboard pattern:
for any two adjacent rows, one row will have non-zero entries only
in even-numbered locations, and the other will have non-zero entries
only in odd-numbered locations.
Notice that right after you do pascalTri[y][sideOne] = 1;, you decrement sideOne.
That means if you are in a row that should be using odd-numbered cells,
sideOne now is odd, but when you did pascalTri[y][sideOne] = 1;,
sideOne was still even. So you have put an even-numbered entry in a row that
should have only odd-numbered entries.
That is where all the extra 1s are coming from in your output.
Just delete these lines:
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
All they are doing is creating those extra, unwanted 1 values. All the correct values
are being written in the array by other statements.
I don't know if you know what a pascal triangle is let me explain to you what it is.
11^0 = 1
11^1 = 11
11^2 = 121
11^3 = 1331
11^4 = 14641
11^5 = 161051
I don't know why have you done some much code all when you need was
public static void printPascalsTriangle(int n)
{
long number=11l;
for(int i=0;i<=n;i++)
{
System.out.println(new Double(Math.pow(number,i)).longValue());
}
}
You would need a case more that five which can be handled like this link.
Refer this short pascal code i have written which is depend on user input:
public class Pascal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner= new Scanner(System.in);
System.out.println("Enter the Number of levels of Pascal");
int levelCount = scanner.nextInt();
for(int i =0;i<levelCount;i++) {
int value = 1;
for(int j=0;j<=i;j++) {
System.out.println(value);
value = value * (i - j) / (j + 1);
}
System.out.println("\n");
}
}
}
Enjoy..!!

Categories