java print to file cuts last digit of number - java

i try to print values into a file but my results are cutted when longer then 4 digits:
import java.io.FileNotFoundException;
import java.math.BigInteger;
public class create_referencevalues {
/**
* #param args
*/
public static void main(String[] args) {
Long[] list = { 10L, 40L, 90L, 160L, 250L, 350L, 500L, 650L, 800L,
1000L };
try {
java.io.PrintStream p = new java.io.PrintStream(
new java.io.BufferedOutputStream(
new java.io.FileOutputStream(new java.io.File(
"C:/users/djdeejay/listall.csv"), false)));
for (long i = 0; i < 1024; i++) {
//p.print(Long.toBinaryString(i));
Long sum1 = 0L;
for (int j = 0; j < 10; j++) {
if (BigInteger.valueOf(i).testBit(j)) {
sum1 += (list[j]);
}
}
p.println( i + ";"+sum1);
}
p.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Here are the 5 last values as printed:
1018;3750
1019;3760
1020;3800
1021;3810
1022;3840
1023;3850
last should be: 38500
what do I miss here ???

There is nothing wrong with the println. Your code does exactly what I'd expect it to do. Consider the last line, which you claim isn't correct:
1023;3850
The decimal 1023 is 1111111111 in binary. Therefore when i=1023, the inner loop of your program would simply compute the sum of all numbers in list. These numbers add up to 3850, which is what gets printed.

The last one should actually be 3850 and not 38500. When i = 1023 all bits are set and the last line will be the same as if you add all numbers in list[] together.
1000+650+800+500+350+250+160+90+40+10 = 3850

Related

finding time complexity for the below java code

I have tried to find the time complexity for the below code but I am not sure whether it is right or not. can anyone help me on finding the time complexity for the below code. the code language is JAVA.
code:
// importing the necessary header files for the program
// header files are imported using the keyword import
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
//creating a class called "Partone". class can be created using the keyword class
public class Partone
{
public static void main(String[] args) throws IOException
{
// opening a file named "hikernet1"
File inputFile = new File("hikernet1.txt");
int maxTransmission = 0; //declaring maxTransmission as Integer data type and setting as 0
//reading the content of the file
Scanner reader = new Scanner(inputFile);
// inputCoordinatedAndTransmissionRange
String[] iCATR = reader.useDelimiter("\\A").next().replaceAll("\n", ",").replace("\r", "").split(",");
for (int i = 0; i < Integer.parseInt(iCATR[0]); i++)
{
int transmissions = 0; //declaring transmissions as integer data type and setting is as 0
String[] thisHiker = iCATR[i+1].split(" ");
int transMissionRange = Integer.parseInt(thisHiker[2]);
for (int j = 0; j < Integer.parseInt(iCATR[0]); j++)
{
int distance = (int) Math.sqrt(
Math.pow(Integer.parseInt(thisHiker[0])-Integer.parseInt(iCATR[j+1].split(" ")[0]), 2) + //x2-x1
Math.pow(Integer.parseInt(thisHiker[1])-Integer.parseInt(iCATR[j+1].split(" ")[1]), 2)); //y2-y1
if (distance<=transMissionRange)
{
transmissions++;
}
}
if (transmissions>maxTransmission) //checking the condition
{
maxTransmission = transmissions;
}
}
System.out.println(" The Maximum Transmission: "+maxTransmission);
//the outpit will be displayed in the hikernet1out file
FileWriter fw = new FileWriter("hikernet1out.txt"); //hikernet1out is the name of the output file
fw.write(""+maxTransmission);
fw.close(); //closing the file
reader.close(); //closing all the files
}
} //end of the program
any help would be appreciated much . thanks in advance.
Integer.parseInt(iCATR[0]); retruning any value let consider n.
The inner loop is running n times for every iteration of the outer loop.
The total number of nested loop itration = total number of iteration of outer loop . total number of iteration of inner loop = n * n = n^2
For each iteration nested loop doing O(1) operation.
Total time complexity = O(n^2)*O(1) = O(n^2).

Numbers missing from stack and linkedlist JAVA?

I am trying to implement code to convert decimal to binary with a certain precision, for that I use stack and linked list to add the non decimal and decimal parts calculated. I then use Stringbuilder to pop/poll element one by one to ge the final binary number. SOURCE : http://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/
When I push the elements onto stack/list I see they are being pushed(Using o/p stmts for that). For some reason I dont see them when popping out the elements.
Here is my code
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryToDecimal {
public String toBinary(float n, int p){
int non_dec = (int) Math.floor(n);
Stack<Integer> s_non_dec = new Stack<>();
LinkedList<Integer> q_dec = new LinkedList<>();
float dec = n - non_dec;
int quotient = 1;
while(quotient > 0){
quotient = non_dec/2;
int remainder = non_dec%2;
System.out.println("quotient"+quotient+"non_dec"+non_dec+"remainder"+remainder);
s_non_dec.push(remainder);
non_dec = quotient;
}
while(p>0){
System.out.println("before dec"+dec);
dec = dec*2;
System.out.println("after dec"+dec);
if(dec >=1){
System.out.println("add 1");
q_dec.add(1);
dec = dec - 1;
}
else{
System.out.println("add 0");
q_dec.add(0);
}
p--;
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<s_non_dec.size();i++){
System.out.println("pop"+s_non_dec.peek());
sb.append(s_non_dec.pop());
}
sb.append('.');
for(int i=0;i<q_dec.size();i++){
System.out.println("poll"+q_dec.peek());
sb.append(q_dec.poll());
}
return sb.toString();
}
public static void main (String args[]){
BinaryToDecimal btd = new BinaryToDecimal();
System.out.println(btd.toBinary(2.47f, 5));
}
}
My output :
quotient1non_dec2remainder0
quotient0non_dec1remainder1
before dec0.47000003
after dec0.94000006
add 0
before dec0.94000006
after dec1.8800001
add 1
before dec0.8800001
after dec1.7600002
add 1
before dec0.7600002
after dec1.5200005
add 1
before dec0.52000046
after dec1.0400009
add 1
pop1
poll0
poll1
poll1
1.011
as seen above, even tough I push 1 and 0 into my stack, my output has only 1 for the non decimal part instead of 1 and 0! The same happens for the decimal part!
Ive been looking at this code for hours, any help is appreciated!
Error is with your for loop.
for(int i=0;i<s_non_dec.size();i++){
System.out.println("pop"+s_non_dec.peek());
sb.append(s_non_dec.pop());
}
Here you are looping on stack size s_non_dec.size, which will keep on decreasing after every pop operation and "i" will keep on increasing after every iteration. You can better check if stack is empty or not. Use
while(!s_non_dec.isEmpty()) {
System.out.println("pop"+s_non_dec.peek());
sb.append(s_non_dec.pop());
}

how do I use insertion sort on a 2D array?

So, I made this code almost work, but I want to use insertion sort on the array and for the output to display results sorted by product ID only by insertion sort. Each product ID should have the same corresponding number of units. The units should not be sorted independently. The only order would be by product ID is what I'm basically implying.
import java.util.*;
import java.io.*;
class newversion {
public static int [][] table; // the output table
public static int numOfRows; //number of rows used up in the table
public static int lookfor(int productID){
int location = -1; //-1 an error
for(int i = 0; i < numOfRows; i++){
if (table[i][0] == productID){
location = i;
}
}
return location;
}
/*
here is my modified bubble sort code. I based it on this, but done differently:
http://stackoverflow.com/questions/23283655/bubble-sort-on-2d-array-java
public static void swap(int int1, int int2, int[] array) {
if(int1 == int2){
return;
}
else{
int temp = int2;
array[int2] = array[int1];
array[int2] = temp;
}
}
but it didn't work and I had to try something else
*/
public static boolean contains(int productID){
if (lookfor(productID) == -1){
return false;
}
return true;
}
public static void main(String[] args) {
File file = null;
Scanner scanner = null;
try{
file = new File("data.csv");
scanner = new Scanner( file );
}
catch(Exception e){
System.out.println("Error opening file!");
System.exit(1);
}
//citation of idea for sorting method in 2D array: http://stackoverflow.com/questions/23283655/bubble-sort-on-2d-array-java
//I'm using bubble sort on a 2D array
//this is his code
/*
private static void bubblesort(Integer[] array) {
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j].compareTo(array[j+1]) > 0) {
swap(j, j+1, array);
}
}
}
}
private static void swap(Integer int1, Integer int2, Integer[] array) {
if(int1 == int2)return;
Integer temp = new Integer(array[int2]);
array[index2] = array[int1];
array[int1] = temp;
}
*/
//here's my idea for bubble sort on a 2D array
/*
for (int i = 0; i < numOfRows; i++){
for(int j = 0; j < numOfRows - 1; j++) {
if(table[j][0].compareTo(array[j+1][0]) > 0) {
swap(j, j+1, table);
}
}
//this didn't work well either
//Now, I have to try another for-loop
*/
//Count the number of lines in the file
int size_of_file = 0;
while (scanner.hasNextLine()){
scanner.nextLine();
size_of_file++;
}
table = new int[size_of_file][2];
//reset scanner
try{
file = new File("data.csv");
scanner = new Scanner( file );
}
catch(Exception e){
System.out.println("Error opening file!");
System.exit(1);
}
//save the title
String titleLine = scanner.nextLine();
System.out.println(titleLine);
//for each line in the file, store and total it.
numOfRows=0;
while (scanner.hasNextLine()){
String ln = scanner.nextLine();
String[] row = ln.split(",");
System.out.println(row[0] + ", " + row[1]);
if (contains(Integer.parseInt(row[0]))){
//This is the location in the table where the product id exists already.
int location = lookfor(Integer.parseInt(row[0]));
//add the units to what we have in the table
table[location][1] += Integer.parseInt(row[1]);
}
else{
table[numOfRows][0]= Integer.parseInt(row[0]);
table[numOfRows][1]= Integer.parseInt(row[1]);
numOfRows++;
}
}
//output
try{
PrintWriter output = new PrintWriter("output.csv");
output.println(titleLine);
for(int i=0;i<numOfRows;i++){
output.println(table[i][0] + "," + table[i][1]);
}
output.close();
}
catch(Exception e){
System.out.println("Error writing file");
}
}
}
I want to understand how to use FileReader better. I read a little bit about it here:
https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html
https://bytes.com/topic/java/answers/585814-reading-data-into-array-file
Although I don't think I understand from that how to store it into an array. Could someone explain how I can store values from FileReader class into an array? I want it in a 2D array where the number of rows is just however many product IDs I have and there is always 2 columns.
Excel File to read from:
Product ID Units
10002 4
10004 6
10008 2
10010 3
10010 3
output I get right now:
Product ID Units
10002 20
10004 72
10008 12
10010 37
10007 28
20003 42
30019 56
30020 29
10006 36
20005 32
etc.
I apologize if this update should be posted as a different question. Let me know so I can go by community standards. The piece of output I posted, you'll notice isn't sorted by productID. That's the last thing I want to do. Other than that, it basically works. I am apologizing in case someone wants to vote me down for not posting the answer, since technically it would be the same answer to the initial question. If this update should be a different thread, again, let me know and I'll make the edit.

Change output after each run to one output after all runs

My program is pretty much all finished except for the output, I want it to display everything in one output rather than one after each run, it is supposed to run 500 times but made it only 10 until I have this problem fixed.
package assignment5;
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.text.*;
public class assignment5
{
public static void main(String[] args)
{
lottery pic=new lottery();for(int i = 0; i <10; i++)
{
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}
}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
double matchcount0=0;
double matchcount1=0;
double matchcount2=0;
double matchcount3=0;
double matchcount4=0;
double matchcount5=0;
int jackpot = 25000000;
int payout;
void Get_player_numbers ()
{
int temp,dupflag=0;
for(i=0;i<=4;++i)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
dupflag=0;
while(dupflag==0)
{
temp = (int)Math.round(Math.random()*99)+1;
dupflag=1;
for(c=0;c<=i;++c)
{
if(temp==picks[c])
{
dupflag=0;
}
}//inner for loop
if(dupflag==1)
picks[i]=temp;
}
}
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
}
void Check_winner ()
{
match=0;
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
if(match==0)
{
matchcount0=matchcount0+1;
payout=0;
jackpot=jackpot+25000;
}
else if(match==1)
{
matchcount1=matchcount1+1;
payout=100;
jackpot=jackpot+100000;
}
else if(match==2)
{
matchcount2=matchcount2+1;
jackpot=jackpot+250000;
payout=1000;
}
else if(match==3)
{
matchcount3=matchcount3+1;
jackpot=jackpot+500000;
payout=10000;
}
else if(match==4)
{
matchcount4=matchcount4+1;
jackpot=jackpot+1000000;
payout=100000;
}
else if(match==5)
{
matchcount5=matchcount5+1;
payout=jackpot;
jackpot=jackpot-jackpot+2500000;
}
System.out.println("Current Jackpot Player# Winner# #Matched Payout\n"+jackpot+" "+picks[0]+" "+picks[1]+" "+picks[2]+" "+picks[3]+" "+picks[4]+" "+cpick[0]+" "+cpick[1]+" "+cpick[2]+" "+cpick[3]+" "+cpick[4]+" "+match+" "+payout+"\nThe percent of plays where 0 numbers matched = "+matchcount0/i*100+"%\nThe percent of plays where 1 numbers matched = "+matchcount1/10+"%\nThe percent of plays where 2 numbers matched = "+matchcount2/10+"%\nThe percent of plays where 3 numbers matched = "+matchcount3/10+"%\nThe percent of plays where 4 numbers matched = "+matchcount4/10+"%\nThe percent of plays where 5 numbers matched = "+matchcount5/10+"%\n");
}
}
Use StringBuilder class. In each run you can just append new line two your StringBuilder instance.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; ++i) {
builder.append(System.getProperty("line.separator") + "Current Jackpot player...");
}
When everything is done you can use
builder.toString();
to get your output.

Reading double values from a file

I'm trying to read some numbers (double) from a file and store them in an ArrayList and an array (yes, I need both) with the code below:
try {
Scanner scan = new Scanner(file).useDelimiter("\\s*\\n");
while(scan.hasNextDouble())
{
tmp.add(scan.nextDouble());
}
Double[][] tmp2 = new Double[tmp.size()/2][2];
int tmp3 = 0;
for(int i = 0; i < tmp.size()/2; i++)
{
for(int j = 0; j < 2; j++)
{
tmp2[i][j] = tmp.get(tmp3);
tmp3++;
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
The file I'm trying to read is:
0.0 0.0
0.023 0.023
0.05 0.05
0.2 0.2
0.5 0.5
0.8 0.8
0.950 0.950
0.977 0.977
1.0 1.0
But well my code doesn't work, the hasNextDouble() function doesn't find anything, what am I doing wrong?
EDIT: ok so I edited the source a bit (changed from Object[][] to Double[][]) and added inserting values into the array after they were inserted into the ArrayList, but it still doesn't work - the 'while' loop isn't executed a single time.
I tried reducing the code down to only test the Scanner by itself. The following code works with your data file:
public static void main(String[] args) {
Scanner scan;
File file = new File("resources\\scannertester\\data.txt");
try {
scan = new Scanner(file);
while(scan.hasNextDouble())
{
System.out.println( scan.nextDouble() );
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
I got the following (expected) output:
0.0
0.0
0.023
0.023
0.05
0.05
0.2
0.2
0.5
0.5
0.8
0.8
0.95
0.95
0.977
0.977
1.0
1.0
Try this to make sure you're referencing the correct file.
I had the same problem (not working scanner) and the solution seems to be surprisingly easy.
You just need to set a locale for it.
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
taken from here: http://www.tutorialspoint.com/java/util/scanner_nextdouble.htm
Below is my rendition of your code, adapted to make it run. It immediately explodes with an array indexing exceptions.
So: Can you give us a little more framework? What's different from what I did?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Zenzen {
private static ArrayList<Double> tmp = new ArrayList<Double>();
private static File file = new File("Zenzen.dat");
public static void main(String[] args) {
Scanner scan;
try {
scan = new Scanner(file);
Object[][] tmp2 = new Object[tmp.size() / 2][2];
int tmp3 = 0;
while (scan.hasNextDouble()) {
tmp.add(scan.nextDouble());
System.out.println(Arrays.deepToString(tmp.toArray())); // debug print
for (int i = 0; i < tmp.size() / 2; i++) {
for (int j = 0; j < 2; j++) {
tmp2[i][j] = tmp.get(tmp3);
tmp3++;
}
}
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
}
[0.0]
[0.0, 0.0]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Zenzen.main(Zenzen.java:26)
Try setting the delimiter first:
scan.useDelimiter("\\s+");
JavaDoc

Categories