This question already has answers here:
Write int to text file using Writer
(8 answers)
Closed 5 years ago.
This is my code and I want b[i] will be write to the file name test.txt but it is not working. It's just write something like symbols. Thanks for helping.
public class btl {
public static boolean IsPrime(int n) {
if (n < 2) {
return false;
}
int squareRoot = (int) Math.sqrt(n);
for (int i = 2; i <= squareRoot; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanIn = new Scanner(System.in);
int first = 0;
int second = 0;
try {
System.out.println("Input First Number");
first = scanIn.nextInt();
System.out.println("Input Second Number");
second= scanIn.nextInt();
}
catch(Exception e) {
System.out.println("Something wrong!");
}
int x = first;
int y = second;
int a;
int[] b = new int[y];
Thread threadA = new Thread(new Runnable() {
#Override
public void run() {
int c=0;
for(int i=x; i<y; i++) {
if(IsPrime(i)) {
b[c] = i;
System.out.println(b[c]);
c++;
}
}
}
});
threadA.start();
try(FileWriter fw = new FileWriter("test.txt")){
for(int i =0; i<y; i++)
{
fw.write(b[i]);
}
}
catch(IOException exc) {
System.out.println("EROR! " + exc);
}
}
}
This is my display console
And this is file "test.txt"
I don't know why FileWriter writes symbols in file text.txt. I want it's number of array b[i].
FileWriter.write(int) writes a single character.
You likely want FileWriter.write(String)as in:
fw.write(Integer.toString(b[i]));
Related
A short flight of stairs will be called a construction of cubes in which each next level consists of a strictly larger number of cubes than the previous level, if we count the levels from top to bottom. You need to count the number of ladders that can be built exactly from n cubes.
My solution to this task doesn't pass the time test. To fix this, I decided to try to rewrite the recursive function to the usual one, but so far it has not worked out very well.
public class main {
int n;
public static int counts(int prev_level, int n) {
if (n == 0){
return 1;
}
int count = 0;
for (int level =1; level<prev_level; level++){
if((n-level)<0)
break;
count += counts(level,n-level);
}
return count;
}
public static void main(String[] args) {
int n;
int res = 0;
int count = 0;
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
n = Integer.parseInt(sc.nextLine());
res = counts(n+1,n);
}
} catch(IOException e) { System.out.println("Input error"); }
try{
FileOutputStream writer = new FileOutputStream("output.txt");
PrintStream p = new PrintStream(writer);
p.println(res);
writer.close();
} catch(IOException e) { System.out.println("Output error"); }
}
}
I am learning how to implement basic algorithms in Java, so i am a newbie in this environment. I am trying to implement Merge Sort algorithm using ArrayList where program will read data (Integer in each line) from file and produce sorting result using Merge Sort. However, my code is showing same result as it has not sorted anything out! I would be very glad if someone can identify where did I do my mistake. As i am a beginner, the code is very simple, not optimized and not very fast in performance probably.
Here is my code:
public class MergeSortExp1 {
public static void main(String[] args) {
ArrayList<Integer>number = new ArrayList<Integer>();
Scanner myScanner = null;
try {
myScanner = new Scanner(new File("/Users/Sabbir/Desktop/workload.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(myScanner.hasNextInt()){
number.add(myScanner.nextInt());
}
System.out.println("Before sorting" +number);
number=mergeSort(number);
System.out.println("Sorted Array =" +number);
}
public static ArrayList<Integer> mergeSort( ArrayList<Integer> Input)
{
if (Input.size() ==1){
return Input;
}
else {
int mid= Input.size()/2;
ArrayList<Integer> left= new ArrayList<Integer>(mid);
ArrayList<Integer> right=new ArrayList<Integer>(Input.size()-mid);
for (int i = 0; i < mid; i++) {
left.add(Input.get(i));
}
for (int i = 0; i < Input.size()-mid; i++) {
right.add(Input.get(i));
}
left=mergeSort(left);
right=mergeSort(right);
merge(left,right,Input);
}
return Input;
}
public static void merge (ArrayList<Integer>left,ArrayList<Integer>right,ArrayList<Integer>Input)
{
int i1=0;// left Index
int i2=0;// right Index
int InputIndex=0;
for (int i = 0; i < Input.size(); i++) {
if (i2>=right.size() || (i1<left.size() && left.get(i)<=right.get(i)))
{
Input.set(InputIndex,left.get(i1));
InputIndex++;
}
else {
Input.set(InputIndex, right.get(i2));
InputIndex++;
}
}
}
}
If your merge method is Ok (I don't test it), you forget to merge left and right to input, edit your code as shown below and re-try:
// This is called recursion. Calling a method again within the
//method until the value of left and right becomes 1.
left=mergeSort(left);
right=mergeSort(right);
merge(left,right,Input);
hope helped you!
One more variant:
private static <T extends Comparable<T>> List<T> mergeSort(List<T> unsortedList) {
if (unsortedList.size() <= 1) {
return unsortedList;
}
List<T> sortedList = new ArrayList<>(unsortedList.size());
List<T> leftList = mergeSort(unsortedList.subList(0, unsortedList.size() / 2));
List<T> rightList = mergeSort(unsortedList.subList(unsortedList.size() / 2, unsortedList.size()));
int leftIdx = 0;
int rightIdx = 0;
int resultIdx = 0;
while (leftIdx < leftList.size() && rightIdx < rightList.size()) {
if (leftList.get(leftIdx).compareTo(rightList.get(rightIdx)) <= 0) {
sortedList.add(resultIdx, leftList.get(leftIdx));
leftIdx++;
} else {
sortedList.add(resultIdx, rightList.get(rightIdx));
rightIdx++;
}
resultIdx++;
}
while (leftIdx < leftList.size()) {
sortedList.add(resultIdx, leftList.get(leftIdx));
leftIdx++;
resultIdx++;
}
while (rightIdx < rightList.size()) {
sortedList.add(resultIdx, rightList.get(rightIdx));
rightIdx++;
resultIdx++;
}
return sortedList;
}
import java.util.ArrayList;
import java.io.*;
import java.util.*;
public class Mergesort1 {
public static void main(String[] args) {
ArrayList<Integer> values = new ArrayList<Integer>();
int zeilen = 0;
try{
FileInputStream in = new FileInputStream(args[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null){
values.add(Integer.parseInt(line));
zeilen++;
}
try{
FileOutputStream out = new FileOutputStream(args[1]);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
sort(values); //sortien array list
for (int i=0; i<values.size(); i++){
writer.write("" + values.get(i));
writer.newLine();
}
writer.close();
}
catch(Exception e){
System.out.println(e);
}
}
catch(Exception e){
System.out.println(e);
}
}
public static ArrayList<Integer> sort( ArrayList<Integer> values)
{
if (values.size() ==1){
return values;
}
else {
int mid= values.size()/2;
ArrayList<Integer> left= new ArrayList<Integer>(mid);
ArrayList<Integer> right=new ArrayList<Integer>(values.size()-mid);
for (int i = 0; i < mid; i++) {
left.add(values.get(i));
}
for (int i = mid; i < values.size(); i++) {
right.add(values.get(i));
}
left=sort(left);
right=sort(right);
merge(left,right,values);
}
return values;
}
public static void merge (ArrayList<Integer>left,ArrayList<Integer>right,ArrayList<Integer>values)
{
int i1=0;// left Index
int i2=0;// right Index
int InputIndex=0;
for (int i = 0; i < values.size(); i++) {
if(i1==left.size()){
values.set(i, right.get(i2));
i2++;
}
else{
if (i2==right.size()){
values.set(i,left.get(i1));
i1++;
}
else{
if (left.get(i1)<=right.get(i2)) {
values.set(i,left.get(i1));
i1++;
}
else {
if (left.get(i1)>=right.get(i2)) {
values.set(i, right.get(i2));
i2++;
}
}
}
}
}
}
}
I'm making a program that reads some data from a text file and then takes that data and finds the minimum, maximum, and average of the numbers. For some reason I'm getting a lot of ridiculous errors I've never seen before. Here is my code:
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
public class Lab1 {
static int count = 0;
static int[] newData2 = new int[count];
// Method for reading the data and putting it into different arrays
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
}
static int min(int[] newData2) {
int min = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] < min) {
min = newData2[i];
}
}
return min;
}
static int max(int[] newData2) {
int max = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] > max) {
max = newData2[i];
}
}
return max;
}
static double average(int[] newData2) {
double average = 0;
int sum = 0;
for (int i = 0; i < newData2.length; i++) {
sum = newData2[i];
}
average = sum / newData2.length;
return average;
}
/*
* static int stddev(int[] newData2) { int[] avgDif = new
* int[newData2.length]; for(int i = 0; i < newData2.length; i++) {
* avgDif[i] = (int) (average(newData2) - newData2[i]); }
*
* }
*/
void write(String newdata, int min, int max, double average, int stddev) {
try {
File file = new File("stats.txt");
file.createNewFile();
FileWriter writer = new FileWriter("stats.txt");
writer.write("Minimum: " + min + "Maximum: " + max + "Average: " + average);
writer.close();
}catch(Exception e) {
System.out.println("Unable to write to the file.");
}
public static void main(String[] args) {
}
}
}
I have an error in my readData method, and it tells me that:
This method must return a result type of int[].
I'm literally returning an int array so I don't understand what the problem here is.
Then in my main method it says void is an invalid type for the variable main.
Here are some pointers:
each exit point of a method returning something must return something, if the line new Scanner(f); throws an exception, the first return is not reached, so you need a default one, like this:
private int[] readData() {
File f = new File("data.txt");
int count = 0;
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt(); // maybe you should handle the case where your input is too large for the array "newData"
}
return Arrays.copyOf(newData, count);
} catch (Exception e) {
System.out.println("Could not read the file.");
}
return null;
}
To reduce the size of an array, you should use Arrays.copyOf (see below)
You should avoid static fields (and in your case none are required)
Your method min and max are assuming there are elements in the array (at least one), you should not do that (or test it with an if):
private int min(int[] data) {
int min = Integer.MAX_VALUE; // handy constant :)
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
private int max(int[] data) {
int max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
In your average method there are a few mistakes:
private double average(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i]; // here if you want a sum it's += not =
}
return (1.0 * sum) / data.length; // you want a double division, local "average" was useless
}
arrays are iterables so you can use "new style" for loops:
for (int value : newData) {
// use value
}
Some reading:
Java Integer division: How do you produce a double?
“Missing return statement” within if / for / while
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
//TODO: return something here if there is some kind of error
}
Because of the try-catch block you need to account for every possibility that could occur. When you return the array when the program succeeds you are expecting a return, but when there is an exception the program still expects a return value, but you did not provide one.
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 8 years ago.
Improve this question
When I create a new array element, it gets stored into the array index, then the array index increments to the next.
However, I am getting a different result. The array element copies down to all previous array indexes.
import java.util.Scanner;
import java.io.*;
public class VectorOfContacts implements ProjTwo
{
private int size;
private int capacity;
private int incrementCapacity;
Contact[] contacts;
File file = new File("contacts.txt");
Scanner input = new Scanner(System.in);
public VectorOfContacts()
{
size = 0;
capacity = 10;
incrementCapacity = capacity;
contacts = new Contact[capacity];
}
public int getSize()
{
return size;
}
public int getCapacity()
{
return capacity;
}
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
//public VectorOfContacts(int inCapacity)
//{
//inCapacity = 100;
//incrementCapacity = inCapacity;
//}
public void readInitialFromFile()
{
Contact c = new Contact();
String temp = null;
try{
Scanner input = new Scanner(file);
for (int i = 0 ; i < size; i++)
{
temp = input.nextLine();
String[] part = input.nextLine().split(":");
System.out.println(part);
String name = part[0];
long number = Long.parseLong(part[1]);
String comment = part[2];
c.setName(name);
c.setPhoneNumber(number);
c.setComment(comment);
contacts[i] = c;
contacts[size] = contacts[i];
}
input.close();
}catch(FileNotFoundException e){
System.out.println("File not found.");
System.exit(0);
}
}
public void writeFinalToFile()
{
try{
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < size; i++)
{
output.println(contacts[i]);
}
output.close();
}catch(FileNotFoundException a){
System.out.println("Something is wrong.");
System.exit(0);
}
System.exit(0);
}
public void addContact(Contact c)
{
addElement(c);
}
public void deleteContact(String nm)
{
System.out.println("Delete which name?");
nm = input.nextLine();
for(int i = 0; i < size; i++)
{
if(contacts[i].getName() == nm);
{
contacts[i] = contacts[i+1];
}
}
System.out.println("Deletion confirmed");
}
public void showByName(String nm)
{
nm = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (nm.startsWith(contacts[i].getName()))
{
System.out.println(contacts[i]);
}
}
}
public void showByPhoneNumber(long pN)
{
pN = input.nextLong();
for ( int i = 0; i < size; i++)
{
if (contacts[i].getPhoneNumber() == pN)
{
System.out.println(contacts[i]);
}
}
}
public void showByComment(String c)
{
c = input.nextLine();
for ( int i = 0; i < size; i++)
{
if (c.startsWith(contacts[i].getComment()))
{
System.out.println(contacts[i]);
}
}
}
public boolean isFull()
{
if (size == capacity)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
public void addElement(Contact item)
{
if (isFull() == true)
incrementCapacity();
contacts[size] = item;
size++;
System.out.println("size" + size);
for (int i = 0; i < size; i++)
{
System.out.println(contacts[i]);
}
}
public void incrementCapacity()
{
Contact[] temp_contacts = new Contact[capacity + incrementCapacity];
for(int i = 0; i < size; i++)
{
temp_contacts[i] = contacts[i];
}
capacity = capacity + incrementCapacity;
contacts = temp_contacts;
}
}
These are the end results
size1
test:1234:1
size2
no:5555:2
no:5555:2
size3
jaja:1666:test
jaja:1666:test
jaja:1666:test
You print one object for all indexes, you need to use next:
for (int i = 0; i < size; i++){
System.out.println(contacts[i]);
}
You could improve a lof of things.
Don't expose everything as public
The class VectorOfContacts does a lot of things. You should split it into many classes.
Use the Java Framework (Array.copy(), ArrayList, ...)
Don't do if (true) return true else return false
Write tests
In readInitialFromFile you're creating the contact outside of the loop. So you reusing the same object of all contacts.
Those setters dont do anything, you missing an argument. But they shouldn't be public anyway so you don't need them.
public void setSize()
{
this.size = size;
}
public void setCapacity()
{
this.capacity = capacity;
}
isFull and isEmpty shouldn't be public and can be a lot shorter
private boolean isFull() {
return size == capacity;
}
private boolean isEmpty() {
return size == 0;
}
Please clean up your code first.
I am trying to make a program where I read all of the integers in 2 files and put them into 2 separate arraylist. Then I have to merge the lists together and sort the merged list. I keep getting the following error when I run my program and I can't figure out why
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Does anyone know how I would go about fixing this?
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class ArraySort{
ArrayList<Integer> numberList = new ArrayList<Integer>();
ArrayList<Integer> numberList2 = new ArrayList<Integer>();
ArrayList<Integer> numberList3 = new ArrayList<Integer>();
public static void main(String[] args){
ArraySort x = new ArraySort();
x.merge();
x.splitList(9);
}
public void ArraySort(){
Scanner s = new Scanner(System.in);
try {
s = new Scanner (new File ("list1.txt")).useDelimiter("\\s+");
} catch(FileNotFoundException fnfe) {
System.out.println("file not found");
}
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is an int
numberList.add(s.nextInt());
} else {
s.next(); // else read the next token
}
}
try {
s = new Scanner (new File ("list2.txt")).useDelimiter("\\s+");
} catch(FileNotFoundException fnfe) {
System.out.println("file not found");
}
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is an int
numberList2.add(s.nextInt());
} else {
s.next(); // else read the next token
}
}
}
public void ArraySort(String x, String y){
Scanner s = new Scanner(System.in);
try {
s = new Scanner (new File (x)).useDelimiter("\\s+");
} catch(FileNotFoundException fnfe) {
System.out.println("file not found");
}
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is an int
numberList.add(s.nextInt());
} else {
s.next(); // else read the next token
}
}
try {
s = new Scanner (new File (y)).useDelimiter("\\s+");
} catch(FileNotFoundException fnfe) {
System.out.println("file not found");
}
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is an int
numberList2.add(s.nextInt());
} else {
s.next(); // else read the next token
}
}
}
public void bubbleSort() {
for (int pass = 0; pass < numberList.size()-1; pass++) {
for (int i = 0; i < numberList.size()-1; i++) {
if (numberList.get(i) > numberList.get(i+1)) {
int temp = numberList.get(i);
numberList.set(i,numberList.get(i+1));
numberList.set(i+1,temp);
}
}
}
}
public void merge(){
int currentPosition = 0;
for( int i = 0; i < numberList.size(); i++) {
numberList3.set(currentPosition, numberList.get(i));
currentPosition++;
}
for( int j = 0; j < numberList2.size(); j++) {
numberList3.set(currentPosition, numberList.get(j));
currentPosition++;
}
}
public void splitList(int x){
int count1 = 0;
int count2 = 0;
for(int i=0;i<numberList.size();i++){
if(numberList.get(i)>=x){
numberList2.set(count1,numberList.get(i));
count1++;
}
else{
numberList3.set(count2,numberList.get(i));
count2++;
}
}
System.out.println();
for (int i = 0; i < numberList2.size(); i++){
System.out.print(numberList2.get(i) + " ");
}
System.out.println();
for (int i = 0; i < numberList3.size(); i++){
System.out.print(numberList3.get(i) + " ");
}
System.out.println();
}
}
It should be
public static void main
not
public void main
(Also, congratulations, you've found a bug in Rice University's system for running Java code. Report it to them!)
It looks like you are using a non-standard Java compiler. Try compiling this with Sun's/Oracle or IBM's javac to see if it gives you a different trace. If it does then it might just be an error with your university's implementation of javac.
I mention this as the use of the JavacCompiler class is suspicious for your code's runtime execution.