It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
public class ReaderWriter extends Bank {
private final String FILENAME = "clients.txt";
public void writeToFile() {
int i = 0;
boolean repeat = true;
Formatter output = null; // Used to write to file
try {
output = new Formatter(FILENAME);
// Open the file
while ((i <= accounts.length - 1) && (accounts[i] != null)) {
output.format("%s\n", accounts[i].getAccountHolder());
output.format("%d%n", accounts[i].getAccountNumber());
output.format("%d%n", accounts[i].getAmount());
i = i + 1;
}catch (Exception ex) {
ex.printStackTrace();
} finally {
output.close(); // Make sure to close the resource after usage.
}
}
And this is Bank class:
public class Bank {
public final int MAX_NUMBER_OF_ACCOUNTS = 10;
public int max = 0;
String name1;
int money1;
int number1;
Scanner input = new Scanner(System.in);
BankAccount[] accounts = new BankAccount[MAX_NUMBER_OF_ACCOUNTS];
public void greateAccount() {
int i = 0;
boolean repeate2 = true;
System.out.println("You have chosen to create a new account.");
System.out.println("Enter the name of the account holder: ");
name1 = input.next();
System.out.println("Enter the account no.");
number1 = input.nextInt();
System.out.println("Enter the initiating amount: ");
money1 = input.nextInt();
while (repeate2 == true) {
if (accounts[i] == null) {
if (i < 1) {
accounts[i] = new BankAccount();
accounts[i].setAccountHolder(name1);
accounts[i].setAccountNumber(number1);
accounts[i].setAmount(money1);
repeate2 = false;
} else {
if (ifAccountExist(number1) != true) {
accounts[i] = new BankAccount();
accounts[i].setAccountHolder(name1);
accounts[i].setAccountNumber(number1);
accounts[i].setAmount(money1);
repeate2 = false;
} else {
System.out.println("****This account ALREADY EXIST!****");
System.out.println("*************************************");
System.out.println();
max = max - 1;
repeate2 = false;
}
}
}
i = i + 1;
}
max++;
}
Now I want to write to text file account number, name and money.
My code doesn't work. I does not write it can not retrieve values from array I don't know why?
Can you help me?
The code is not going to compile, for many reasons...
For example:
Why this line:
ex.printStackTrace();
is floating in your class ReaderWriter (line 21) and away a catch block?
Why you don't have include declarations?
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have two classes, MarathonAdmin and Runner.
I want to sort list (runners) holding objects of Runner class. I have done all
the coding up to the method sortRunnerList, which says sort the list. I have created
a compareTo method in Runner class and when I compare objects of Runner, they pick the default time values not the ones which I have assigned to objects generating random numbers (done in MarathonAdmin class).
Can someone help with this issue?
class Marathon
import java.util.*;
import java.io.*;
import ou.*;
import java.util.Random;
public class MarathonAdmin
{
// instance variables - replace the example below with your own
private List<Runner> runners;
private String ageGroup;
private String age;
private Random randomNumber;
private String result;
String ageRunner;
String ageGrouprunners;
Scanner lineScanner;
int ans ;
Runner runnerobj = new Runner();
Runner obj2 = new Runner();
public MarathonAdmin()
{
runners = new ArrayList<>();
}
public void readInRunners(){
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
String nameRunner;
BufferedReader bufferedFileReader = null;
try
{
bufferedFileReader = new BufferedReader(new FileReader(aFile));
String currentLine = bufferedFileReader.readLine();
while ( currentLine != null){
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
nameRunner = lineScanner.next();
ageRunner = lineScanner.next();
if (Integer.parseInt(ageRunner) < 18)
{
result = "junior";
System.out.println(currentLine +" category" + " : Junior");
}
if (Integer.parseInt(ageRunner) > 55)
{
result = "senior";
System.out.println(currentLine +" category"+ " : Senior");
}
if (Integer.parseInt(ageRunner) > 18 && Integer.parseInt(ageRunner) < 55)
{
result = "standard";
System.out.println(currentLine +" category"+ " : Standard");
}
ageGrouprunners = result;
Runner runnerobj = new Runner();
runnerobj.setName(nameRunner);
runnerobj.setAgeGroup(ageGrouprunners);
System.out.println(runnerobj); //rough test
runners.add(runnerobj);
currentLine = bufferedFileReader.readLine();
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
public void runMarathon(){
int size = runners.size();
// for ( int runnersIndex = 0; runnersIndex <= size; runnersIndex ++ ){
for( Runner nameRunner : runners){
this.randomNumber = new Random();
ans = randomNumber.nextInt(190 - 80 +1 ) + 90 ;
System.out.println(ans);
nameRunner.setTime(ans);
}
}
public void sortRunnerList(){
for(Runner nameRunner : runners){
int time = nameRunner.getTime();
System.out.println(time);
Runner obj = new Runner();
obj.setTime(ans);
int res = nameRunner.compareTo(obj);
System.out.println(res);
}
}
}
//(This is method of class Runner)
Class Runner
Method compareTo()
#Override
public int compareTo(Runner anotherRunner)
{
return this.getTime()-(anotherRunner.getTime());
}
Try replacing
return this.getTime()-(anotherRunner.getTime());
with
return Integer.valueOf(this.getTime()).compareTo(anotherRunner.getTime());
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Java {
public static int numberOfLoops;
public static int numberOfIterations;
public static int[] loops;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("N = ");
numberOfLoops = input.nextInt();
System.out.print("K = ");
numberOfIterations = input.nextInt();
input.close();
loops = new int[numberOfLoops];
System.out.println("main START");
nestedLoops(0);
System.out.println("main END");
}
public static void nestedLoops(int currentLoop) {
System.out.println("nestedLoops");
System.out.println("currentLoop " + currentLoop);
if (currentLoop == numberOfLoops) {
printLoops();
return;
}
for (int counter = 1; counter <= numberOfIterations; counter++) {
System.out.println("nestedLoops in LOOP");
System.out.println("currentLoop in LOOP " + currentLoop);
loops[currentLoop] = counter;
nestedLoops(currentLoop + 1);
}
}
public static void printLoops() {
System.out.println("printLoops");
for (int i = 0; i < numberOfLoops; i++) {
System.out.printf("%d", loops[i]);
}
System.out.println();
}
}
Hi all. I'm new here and this is my first post.
My question is:
If i put for N = 2 and K = 4 why after first return currentLoop continue with 1 we pass to the method 0 ?
Thanks , Nikola
I'm not sure if I understand your question completely..but
When you call
nestedLoops(0);
You go into the nestedLoops function with currentLoop = 0.
Within this function, you call
nestedLoops(currentLoop + 1);
And that's why you get a
nestedLoop(1)
called while you're in your
nestedLoop(0)
Let me know if I misunderstood your question.
Edited:
When
nestedLoops(1)
is called, we call
nestedLoops(2)
right?
When we compare currentLoop and numberOfLoops inside of nestedLoops(2), they are both 2,
so we go into
printLoops();
Once printLoops is done, we return into
nestedLoops(2)
However, after printLoops(), we have a
return;
Therefore, we return out of
nestedLoops(2)
and we come back into
nestedLoops(1)
where nestedLoops(2) was called from.
Does that make sense?
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've looked over the code a few times and I'm not sure what is affecting this and forcing it to only use the default constructor. For example if I try to put in 2000 for the amount invested it will still default to 1000.
public class Investment {
private double moneyInvested;
private double yearsInvested;
public final static double AMOUNT_DEFAULT = 1000;
public final static double YEARS_DEFAULT = 5;
public final static double RATE = 0.12;
public Investment() {
moneyInvested = AMOUNT_DEFAULT;
yearsInvested = YEARS_DEFAULT;
}
public Investment(double AMOUNT_DEFAULT, double YEARS_DEFAULT) {
if (moneyInvested <= 0) {
moneyInvested = AMOUNT_DEFAULT;
}
if (yearsInvested <= 0) {
yearsInvested = YEARS_DEFAULT;
}
}
public double getMoneyInvested() {
return moneyInvested;
}
public double getYearsInvested() {
return yearsInvested;
}
public void setMoneyInvested(double inputMoney) {
moneyInvested = inputMoney;
if (inputMoney <= 0) {
inputMoney = 1000;
}
}
public void setYearsInvested(double inputYears) {
yearsInvested = inputYears;
if (inputYears <= 0) {
inputYears = 1;
}
}
public static String returnValue(double inputYears, double inputMoney) {
double returnInvestment;
int initYears = 1;
String returnValue = "";
while (initYears <= inputYears) {
returnInvestment = Math.pow(1.12, initYears) * inputMoney;
int investReturn = (int) returnInvestment;
returnValue = "The amount at end of year " + initYears + " is "
+ investReturn;
JOptionPane.showMessageDialog(null, returnValue);
initYears++;
}
return returnValue;
}
}
public class MakeInvestment {
public static void main(String[] args) {
Investment otherClass = new Investment();
double yA = otherClass.YEARS_DEFAULT;
double mA = otherClass.AMOUNT_DEFAULT;
while (inputAmount() == false) {
inputAmount();
}
while (inputYears() == false) {
inputYears();
}
otherClass.returnValue(yA, mA);
}
public static boolean inputAmount() {
String amountAmount = "";
amountAmount = JOptionPane.showInputDialog(null,
"Enter the amount to invest (9999).", "Investment Amount",
JOptionPane.QUESTION_MESSAGE);
if (amountAmount == null || amountAmount.length() == 0) {
JOptionPane
.showMessageDialog(
null,
"Nothing entered - You must enter a number for amount invested.",
"Investment Amount Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
for (int i = 0; i < amountAmount.length(); i++) {
if (!Character.isDigit(amountAmount.charAt(i))) {
JOptionPane.showMessageDialog(null,
"You must enter a number for amount invested.",
"Investment Amount Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
double dblAmount = Double.parseDouble(amountAmount);
return true;
}
public static boolean inputYears() {
String yearAmount = "";
yearAmount = JOptionPane.showInputDialog(null,
"Enter the number of years to invest.", "Investment Years",
JOptionPane.QUESTION_MESSAGE);
if (yearAmount == null || yearAmount.length() == 0) {
JOptionPane
.showMessageDialog(
null,
"Nothing entered - You must enter a number for years to invest.",
"Investment Years Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (int i = 0; i < yearAmount.length(); i++) {
if (!Character.isDigit(yearAmount.charAt(i))) {
JOptionPane.showMessageDialog(null,
"You must enter a number of years to invest.",
"Investment Years Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
double dblYear = Double.parseDouble(yearAmount);
return true;
}
}
Nothing is "forcing it to use the default constructor". You're just only ever calling the default constructor
Investment otherClass = new Investment()
To use the 2-argument constructor, pass in arguments
new Investment(2000.0D, 5.0D)
I would guess that the lines:
public final static double AMOUNT_DEFAULT = 1000;
public Investment(double AMOUNT_DEFAULT, double YEARS_DEFAULT)
are the problem. You're declaring that AMOUNT_DEFAULT=1000 and declaring it as final. Therefore, it will always equal 1000. Try using a different variable name in your constructor.
Edit: I tested this quickly out of interest and it seems that the code will actually work as you intended. It would still be to your advantage to avoid that kind of variable naming however.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm trying to write a program that gets a .txt file that only has something like 10000010000010000010001
I'm trying to count the number of zeros and output it like 5 5 5 3. I thought if I convert a string into a double or int I could write an if or for loop.
import java.util.Scanner;
public class test1{
public static void main(String[] args) {
java.io.File test2 = new java.io.File("test3.txt");
try
{
Scanner input = new Scanner(test2);
while(input.hasNext())
{
String num = input.nextLine();
System.out.println(num);
double n = Double.parseDouble(num);
System.out.println(n);
}
}
catch (Exception e){
System.out.println("could not find file");
}
}
}
Here you go:
char[] numArray = num.toCharArray();
int counter=0;
for(int i=0;i<numArray.length;i++) {
if(numArray[i]=='0') {
counter++;
}
if((i==numArray.length-1&&counter>0)||(counter>0&&numArray[i]!='0')) {
System.out.println("Number of Zeroes: "+counter);
counter=0;
}
}
Some important points:
1) It's best to use an array of char values here, instead of operating using a double, because a char array can store many more values- the example you posted is too long for a double to handle.
2) Most of this should be self-explanatory (at least, if you study it bit-by-bit), but in case the i==numArray.length-1 part is confusing, this ensures that if the string ends with a 0, the final count of 0's will be printed out as well.
This should work for any string you can throw at it- including values besides 0 and 1, if you need support for it!
where is your effort?
you can simply try (if your string contains only 1s and 0s):
String[] splitArr = num.split("1");
String countStr = "";
for (int i = 0; i < splitArr.length; i++) {
if( ! splitArr[i].isEmpty() )
countStr += splitArr[i].length();
}
System.out.println(countStr);
import java.util.*;
import java.io.*;
public class ZeroCounter {
ArrayList <Integer> listOfNumbers = new ArrayList <Integer> ();
DataInputStream inStream;
long inFileSize;
long outFileSize;
// Track how many bytes we've read. Useful for large files.
int byteCount;
public ZeroCounter() {
}
//read the file and turn it into an array of integers
public void readFile(String fileName) {
try {
// Create a new File object, get size
File inputFile = new File(fileName);
inFileSize = inputFile.length();
// The constructor of DataInputStream requires an InputStream
inStream = new DataInputStream(new FileInputStream(inputFile));
}
// Oops. Errors.
catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
// Read the input file
try {
// While there are more bytes available to read...
while (inStream.available() > 0) {
// Read in a single byte and store it in a character
int c = (int)inStream.readByte();
if ((++byteCount)% 1024 == 0)
System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");
// Print the integer to see them for debugging purposes
//System.out.print(c);
// Add the integer to an ArrayList
fileArray.add(c);
}
// clean up
inStream.close();
System.out.println("File has been converted into an ArrayList of Integers!");
}
// Oops. Errors.
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
//Print the ArrayList contents for debugging purposes
//System.out.println(fileArray);
}
public void countZeroes() {
int zeroCounter = 0;
for (int i = 0; i < listOfNumbers.size(); i++) {
if (listOfNumbers.get(i) == 0) {
zeroCounter++;
}
else if (listOfNumbers.get(i) != 0 && zeroCounter > 0) {
//this only prints the number of zeroes if the zero counter isn't zero
System.out.println(zeroCounter + " ");
zeroCounter = 0;
}
else {
//do nothing
}
}
}
public static void main(String[] args) {
ZeroCounter comp = new ZeroCounter();
comp.readFile("test3.txt");
comp.countZeroes();
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I'm using this code to sort a number array but it gives me an error that I need a "}".
Am I missing some "}"?
Any help would be appreciated!
double Median()
{
int k,Hide;
boolean IsThereASwap;
IsThereASwap = false;
while(IsThereASwap == false )
{
for ( k = 0 ; k < TheArrayAssingment.length - 1; k++)
{
if( TheArrayAssingment[k] > TheArrayAssingment[k+1] )
{
Hide = TheArrayAssingment[k+1];
TheArrayAssingment[k+1] = TheArrayAssingment[k];
TheArrayAssingment[k] = Hide;
IsThereASwap = true;
}
}
if ( IsThereASwap == true)
{
IsThereASwap = false;
}
else
{
IsThereASwap = true;
}
}
}
You're failing to return a value. The method is declared to return a double, but you're falling off the end of your method without returning anything.
I see too many problems with your code to bother answering your question.
Start by learning and following the Sun Java coding standards.
A good IDE will make errors like mismatched parentheses and failure to return a value a thing of the past. Try IntelliJ; it's the best there is.
This will work much better than yours:
package cruft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* StatisticsUtil has statistics utility methods
* #author Michael
* #link
* #since 7/21/12 7:30 PM
*/
public class StatisticsUtil {
public static void main(String[] args) {
List<Double> values = new ArrayList<>();
for (String arg : args) {
values.add(Double.valueOf(arg));
}
System.out.println(String.format("median: %10.4f", getMedian(values)));
}
public static double getMedian(List<Double> values) {
double median = 0.0;
if (values != null) {
int numValues = values.size();
if (numValues > 0) {
Collections.sort(values);
if ((numValues%2) == 0) {
median = (values.get((numValues/2)-1)+values.get(numValues/2))/2.0;
} else {
median = values.get(numValues/2);
}
}
}
return median;
}
public static double getMedian(double [] values) {
double median = 0.0;
if (values != null) {
int numValues = values.length;
if (numValues > 0) {
Arrays.sort(values);
if ((numValues%2) == 0) {
median = (values[(numValues/2)-1]+values[numValues/2])/2.0;
} else {
median = values[numValues/2];
}
}
}
return median;
}
}
You declare the method "Median()" to return a double, but you don't return anything.