Reading numbers from a txt file and comparing them - java

With this program I want to read and compare the numbers that I'm given in a text file and print out
"buy" whenever the number goes up three consecutive time and "sell" whenever the number goes down three consecutive times.
The problem with my program is that it only reads 13 of the 15 lines of the "numbers.txt" and the buy-sell is at wrong places.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.text.DecimalFormat;
public class Practise {
public static void main(String[] args) throws IOException {
int num = 0;
int up = 0;
int down = 0;
int same = 0;
FileInputStream file = new FileInputStream("numbers.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextDouble()) {
Double[] array = new Double[15];
for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextDouble();
}
for (int a = 0; a < array.length && a + 1 < array.length - 1; a++) {
num++;
System.out.print(num + " " + (array[a]));
if (array[a] < array[a + 1]) {
up++;
} else if (array[a] > array[a + 1]) {
down++;
} else {
same++;
}
if ((up >= 3 && (down > 1 || same >= 1))) {
System.out.print(" " + "sell");
up = 0;
same = 0;
} else if ((down >= 3 && (up > 1 || same >= 1))) {
System.out.print(" " + "buy");
down = 0;
same = 0;
}
System.out.println();
}
}
}
}
The file numbers.txt:
26.375
25.500
25.125
25.000
25.250
27.125
28.250
26.000
25.500
25.000
25.125
25.250
26.375
25.500
25.500
Expected output:
1 26.375
2 25.500
3 25.125
4 25.000
5 25.250 buy
6 27.125
7 28.250
8 26.000 sell
9 25.500
10 25.000
11 25.125 buy
12 25.250
13 26.375
14 25.500 sell
15 25.500

You use a + 1 < array.length - 1, which can be transformed to a < array.length - 2. I guess you understand that the second operand in && limits your iteration to 13.
a < array.length && a < array.length - 2 = a < 15 && a < 13 = a < 13
I did some minor changes on your code for it to work; you could refactor it a lot, but I stick to your style, so you can better understand the logic.
int num = 1;
//print the 1st element
System.out.println(num + " " + array[0]);
for (int a = 1; a < array.length; a++) {
num++;
System.out.print(num + " " + (array[a]));
//plz note that we check with the before, not after
if (array[a] < array[a - 1]) {
down++;
} else if (array[a] > array[a - 1]) {
up++;
} else {
same++;
}
//changed down > to down ==
if ((up >= 3 && (down == 1 || same >= 1))) {
System.out.print(" " + "sell");
up = 0;
same = 0;
}
//changed up > to up ==
else if ((down >= 3 && (up == 1 || same >= 1))) {
System.out.print(" " + "buy");
down = 0;
same = 0;
}
System.out.println();
}
Answering to OPs comment: if you want to support more than 15 records you can keep adding to a list:
List<Double> list = new ArrayList<>();
while (scanner.hasNextDouble()) {
list.add(scanner.nextDouble());
}
//if you want to work with array
Double[] array = new Double[list.size()];
array = list.toArray(array);

Here's a working example (had to change array to list)
int num = 0, up = 0, down = 0, same = 0;
FileInputStream file = new FileInputStream("numbers.txt");
Scanner scanner = new Scanner(file);
List<Double> list = new ArrayList<>();
while (scanner.hasNextDouble()) {
list.add(scanner.nextDouble());
}
int position = 0;
while (position + 2 < list.size()) {
Double[] nums = new Double[3];
System.out.println(nums[0] = list.get(position));
System.out.println(nums[1] = list.get(position + 1));
System.out.println(nums[2] = list.get(position + 2));
if (nums[1] > nums[0] && nums[2] > nums[1]) {
System.out.println("buy");
up++;
} else if (nums[1] < nums[0] && nums[2] < nums[1]) {
System.out.println("sell");
down++;
} else {
same++;
}
position += 2;
}
System.out.println("Ups total: " + up);
System.out.println("Downs total: " + down);
System.out.println("Same total: " + same);

Related

How to print a 2D array in java

Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it.
When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed.
`Random rand = new Random();
int min = 2, max = 10;
// a random number of rows and columns
int a = (int)(Math.random() * (max - min + 1)) + min;
// the location of the starting point.
int row_start = rand.nextInt(a);
int col_start = rand.nextInt(a);
// the location of the ending point.
int row_end = rand.nextInt(a);
int col_end = rand.nextInt(a);
int [][] M = new int [a][a];
public void create() {
//empty: 0; grass: 1; sand: 2; water: 3; wall: 4.
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
M[i][j] = rand.nextInt(5);
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
System.out.print(" " +M[i][j] + "\t");
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
}
if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
}
}
System.out.print("\n");
}
}`
the output looks like this:
1 0 4 0
2 {S} 1 2 2
4 4 {E} 0 3
2 0 3 3
the 2 and 3 shouldn't appear there.
The problem is that you always print m[i][j].
What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print m[i][j].
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
} else if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
} else {
System.out.print(" " +M[i][j] + "\t");
}

Why is null appearing in my output? - Java

I am writing this program and all of a sudden null appears in the output:
1-10 |null**********
11-20 |null**********
21-30 |null
31-40 |null
41-50 |null
it should be like this:
1-10 |**********
11-20 |**********
21-30 |
31-40 |
41-50 |
This is my code:
import java.util.Arrays;
public class Ex4Method {
public void Average(int[] a) {
int total = 0;
for (int i = 0; i < a.length; i++) {
total = total + a[i];
}
int average = total / a.length;
System.out.println(" ");
System.out.println("Average: " + average);
}
public void MaxAndRange(int[] b) {
int min = b[0];
int max = b[0];
for (int i = 0; i <= 19; i++) {
//System.out.println(i);
if (b[i] < min) {
min = b[i];
}
if (b[i] > max) {
max = b[i];
}
}
int range = max - min;
System.out.println("Maximum Number: " + max);
System.out.println("Range: " + range);
}
public void Median(int[] c) {
Arrays.sort(c);
double median = 0;
System.out.println("Median: " + median);
}
public void findMedian(int a[]) {
// First we sort the array
Arrays.sort(a);
double median;
if (a.length % 2 == 0) {
median = ((double) a[a.length / 2] + (double) a[a.length / 2 - 1]) / 2;
} else {
median = (double) a[a.length / 2];
}
System.out.println("Median: " + median);
}
public void Mode(int[] d) {
int maxValue = 0, maxCount = 0;
for (int i = 0; i < d.length; i++) {
int count = 0;
for (int j = 0; j < d.length; j++) {
if (d[j] == d[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = d[i];
}
}
System.out.println("Mode: " + maxValue);
}
public void Histogram(int[] f) {
String[] asterisk = new String[6];
System.out.println("Histogram: ");
System.out.println(" ");
for (int i = 0; i <= f.length - 1; i++) {
if (f[i] >= 1 && f[i] <= 10) {
asterisk[1] += "*";
}
if (f[i] >= 11 && f[i] <= 20) {
asterisk[2] += "*";
}
if (f[i] >= 21 && f[i] <= 30) {
asterisk[3] += "*";
}
if (f[i] >= 31 && f[i] <= 40) {
asterisk[4] += "*";
}
if (f[i] >= 41 && f[i] <= 50) {
asterisk[5] += "*";
}
}
System.out.println(" 1-10 |" + asterisk[1]);
System.out.println("11-20 |" + asterisk[2]);
System.out.println("21-30 |" + asterisk[3]);
System.out.println("31-40 |" + asterisk[4]);
System.out.println("41-50 |" + asterisk[5]);
}
}
MAIN CLASS-
import TurtleGraphics.KeyboardReader;
public class ArrayEx4 {
public static void main(String[] args) {
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int[] nums = new int[20];
int i = 0;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
while (nums[i] >= 1 && nums[i] <= 50 && i < 19) {
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
//occurences[nums[i]]++;
}
//for(int x=0;x<=4;x++) {
//System.out.println(occurences[x]);
//}
object.Average(nums);
object.MaxAndRange(nums);
object.findMedian(nums);
object.Mode(nums);
object.Histogram(nums);
}
}
Any suggestions? Thanks
This is the code right here:
public void Histogram(int[] f) {
String[] asterisk = new String[6];
System.out.println("Histogram: ");
System.out.println(" ");
for (int i = 0; i <= f.length - 1; i++) {
if (f[i] >= 1 && f[i] <= 10) {
asterisk[1] += "*";
}
if (f[i] >= 11 && f[i] <= 20) {
asterisk[2] += "*";
}
if (f[i] >= 21 && f[i] <= 30) {
asterisk[3] += "*";
}
if (f[i] >= 31 && f[i] <= 40) {
asterisk[4] += "*";
}
if (f[i] >= 41 && f[i] <= 50) {
asterisk[5] += "*";
}
}
System.out.println(" 1-10 |" + asterisk[1]);
System.out.println("11-20 |" + asterisk[2]);
System.out.println("21-30 |" + asterisk[3]);
System.out.println("31-40 |" + asterisk[4]);
System.out.println("41-50 |" + asterisk[5]);
}
More specifically, this part:
asterisk[i] += "*";
In Java, + operator for strings means concatenation, and both operands are converted to strings beforehand.
At the very beginning, new String[6] is filled with default values for String type, which, for any type inherited from java.lang.Object is a null value. When you concatenate using operators, the very first pass over any slot in the array will always encounter a null value.
And
String.valueOf(null) + "*"
will output "null*"

In Java Why can't I get 9 characters from decimal numbers over 255? Is it the sign bit?

This is for the headstails java homework assignment that you can find a few places online (like http://www.javaproblems.com/2013/01/medium-problem-tricky-heads-and-tails.html)
The idea is to input a decimal 0 to 511 and have it output a 3 x 3 matrix of H or T for 0 or 1's (mine works 0 to 255)
Here's my attempt though, that I couldn't get working:
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
//System.out.println("Please enter a number between 0 and 511: ");
//int num = keyboard.nextInt();
int num = 458;
String binNum = "";
int temp;
String[][] coinArr = new String[3][3]; // = [][];
while(num > 0)
{
temp = (int) (num % 2);
binNum = binNum + "" + temp;
num = (int) (num / 2);
}
System.out.println("binNum length is " + binNum.length());
System.out.println("binNum is " + binNum);
binNum = String.format((binNum.length() < 9 ? ("%0"+ (9 - binNum.length())+"d%s") : "%0$d%s"), 0 ,binNum);
System.out.println("binNum length is " + binNum.length());
System.out.println("binNum is " + binNum);
int k=0;
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
binNum = binNum.replaceAll("0", "H");
binNum = binNum.replaceAll("1", "T");
coinArr[i][j] = binNum.substring(k, k+1);
k++;
System.out.print(coinArr[i][j]);
}
System.out.println();
}
}
Your conversion from decimal to binary is wrong, the correct one is :
while(num > 0)
{
temp = (int) (num % 2);
binNum = temp + "" + binNum;
num = (int) (num / 2);
}
Then you only need 9 characters in your binNum :
binNum = binNum.length() < 9 ? String.format("%0"+ (9 - binNum.length())+"d%s", 0 ,binNum) : binNum;
// You don't need this inside your loop
binNum = binNum.replaceAll("0", "H");
binNum = binNum.replaceAll("1", "T");
int k=0;
for(int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
coinArr[i][j] = String.valueOf(binNum.charAt(k));
k++;
System.out.print(coinArr[i][j]);
}
System.out.println();
}
There are 2 issues:-
1) Change
binNum = binNum + "" + temp;
to
binNum = temp + binNum;
2) Change
binNum = String.format((binNum.length() < 9 ? ("%0"+ (9 - binNum.length())+"d%s") : "%0$d%s"), 0 ,binNum);
to
binNum = String.format("%09d", Integer.parseInt(binNum));

Stars.java arrayindexoutofbounds

I have been trying to figure out why I have been getting this error for almost 3 hours and I need some help to get this before my computer pays the price.
I keep getting this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
at StarsTable.checkIfStar(StarsTable.java:102)
at Stars.main(Stars.java:20)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class StarsTable
{
private ArrayList<Integer> a = new ArrayList<Integer>();
private String title;
private String readLine = null;
private int rows = 0;
private Integer array[][];
public StarsTable( String fileName)
{
try
{
BufferedReader br = new
BufferedReader(new FileReader( fileName));
title = br.readLine();
while(( readLine = br.readLine()) != null)
{
System.out.println(readLine);
addArray(readLine);
rows++;
}
br.close();
}
catch(IOException e)
{
System.err.println("File Not Found. Please "
+ "enter filename in command line.");
System.exit(1);
}
}
public String title()
{
return title;
}
public void addArray(String readLine)
{
int i = 0;
String[] splitLine = readLine.split("\\s+");
for(i = 0; i < splitLine.length; i++)
{
a.add(Integer.valueOf(splitLine[i].trim()));
}
}
public Integer[][] getArray()
{
toArray();
return array;
}
public void toArray()
{
array = new Integer[rows][a.size() / rows];
int g = 0;
for (int i = 0; i < rows; i++)
{
System.out.println();
for (int k = 0; k < (a.size() / rows); k++)
{
array[i][k] = a.get(g);
System.out.print(array[i][k] + " ");
g++;
}
}
}
public int checkIfStar(int i, int k)
{
Integer check = 0;
// Top Left Corner
if (i == 0 && k == 0)
check = array[i][k] + array[i+1][k] + array[i][k+1];
// Top Right Corner
else if (i == a.size() / rows && k == 0)
check = array[i][k] + array[i-1][k] + array[i][k+1];
// Bottom Left Corner
else if (i == 0 && k == array.length)
check = array[i][k] + array[i][k-1] + array[i+1][k];
// Bottom Right Corner
else if (i == array[0].length && k == array.length)
check = array[i][k] + array[i-1][k] + array[i][k-1];
// Top Row
else if ((i != 0 && i != array[k].length) && k == 0)
check = array[i][k] + array[i-1][k] + array[i+1][k] + array[i][k+1 ];
// Bottom Row
else if ((i != 0 && i != array[k].length) && k == array.length)
check = array[i][k] + array[i-1][k] + array[i][k-1] + array[i+1][k];
// Left Side
else if(i == 0 && k != 0 && k != array.length)
{
System.out.println(i + " " + k);
This is where the error is. check = array[i][k] + array[i+1][k] + array[i][k-1] + array[i][k+1];
}
// Right Side
else if(i == array[k].length && k != 0 && k !=array.length)
check = array[i][k] + array[i-1][k] + array[i][k-1] + array[i][k+1];
else
check = array[i][k] + array[i+1][k] + array[i-1][k] + array[i][k+1] + array[i][k-1];
check = check / 5;
if (check < 5)
return 0;
else
return 1;
}
}
The type of file being read in looks like the following
Title Line
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
The number of lines and the number of lines per line is not known for each file and the file is read in thru the command line with a main program.
You probably want == array.length -1 rather than == array.length, since array.length is 1 more than the largest index. This might apply to a.size() too, not sure.
array.length give you the length of your array. However an array start at index 0, so the last index of your array will be array.length - 1.
Therefore your test should be :
k == array.length - 1
in your checkIfStar method

Creating a random colour grid with all adjacent colours different

So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}

Categories