Selecting the files is not happening - java

I have this below program which is not selecting the files within specified period of time please update..whats wrong in it ..
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternFileFilter implements FileFilter {
public static String ITEM_TYPE_FILE = "File"; // for file
public static String ITEM_TYPE_FOLDER = "Folder"; // for folder
public static String ITEM_TYPE_FILE_AND_FOLDER = "FileAndFolder"; // for file and folder
private Pattern fileNamePattern;
public PatternFileFilter(Pattern fileNamePattern) {
this.fileNamePattern = fileNamePattern;
}
public boolean accept(File pathname) {
return fileNamePattern.matcher(pathname.getName()).find() || pathname.isDirectory();
}
public Pattern getPattern() {
return fileNamePattern;
}
public static void searchFile(File topFolderOrFile, String type, PatternFileFilter filter, long timeOut) throws IOException {
long startTimeStamp = Calendar.getInstance().getTimeInMillis();
if (topFolderOrFile.isDirectory()) {
File[] subFoldersAndFileNames = topFolderOrFile.listFiles(filter);
if (subFoldersAndFileNames != null && subFoldersAndFileNames.length > 0) {
for (File subFolderOrFile : subFoldersAndFileNames) {
if (ITEM_TYPE_FILE.equals(type) && subFolderOrFile.isFile()) {
System.out.println("File name matched ----- " + subFolderOrFile.getName());
}
if (ITEM_TYPE_FOLDER.equals(type) && subFolderOrFile.isDirectory()
&& filter.getPattern().matcher(subFolderOrFile.getName()).find()) {
System.out.println("Folder name matched ----- " + subFolderOrFile.getName());
}
if (ITEM_TYPE_FILE_AND_FOLDER.equals(type) && filter.getPattern().matcher(subFolderOrFile.getName()).find()) {
System.out.println("File or Folder name matched ----- " + subFolderOrFile.getName());
}
// You need to decide if you want to process the folders inline // or after you've processed the
// file list...
if (subFolderOrFile.isDirectory()) {
long timeElapsed = startTimeStamp - Calendar.getInstance().getTimeInMillis();
if (((timeOut * 1000) - timeElapsed) < 0) {
System.out.println("Could not complete operation-- timeout");
} else {
searchFile(subFolderOrFile, type, filter, (timeOut * 1000) - timeElapsed);
}
}
}
}
}
}
public static void searchFile(String topFolderName, String type, String fileNamePatternRegExp, long timeOut)
throws IOException {
File topFolderOrFile = new File(topFolderName);
Pattern fileNamePattern = Pattern.compile(fileNamePatternRegExp);
searchFile(topFolderOrFile, type, new PatternFileFilter(fileNamePattern), timeOut);
}
// ***************
public static void main(String[] str) throws Exception {
System.out.println("Type Item to Search ");
System.out.println("1 File");
System.out.println("2 Folder ");
System.out.println("3 Both");
System.out.println("0 Exit");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String searchType = br.readLine();
System.out.println("Enter top folder name ::");
String topFolderName = br.readLine();
System.out.println("Enter name of file to search ::");
String fileName = br.readLine();
System.out.println("Enter timeout period in seconds::");
String timeOutStr = br.readLine();
if (searchType == null || fileName == null || topFolderName == null || timeOutStr == null) {
throw new Exception("Error Occured::Provide both the input Parameters");
}
int searchTypeInd = Integer.parseInt(searchType);
switch (searchTypeInd) {
case 1:
searchFile(topFolderName, ITEM_TYPE_FILE, fileName, Long.parseLong(timeOutStr));
break;
case 2:
searchFile(topFolderName, ITEM_TYPE_FOLDER, fileName, Long.parseLong(timeOutStr));
break;
case 3:
searchFile(topFolderName, ITEM_TYPE_FILE_AND_FOLDER, fileName, Long.parseLong(timeOutStr));
break;
case 0:
System.exit(0);
}
}
}
Please advise if I have folder in D:\saral it should select the files from D: folder
The result I am getting is ...
Type Item to Search 1 File 2 Folder 3 Both 0 Exit 3 Enter top folder
name :: Test Enter name of file to search :: allMfile.txt Enter
timeout period in seconds:: 5

I suggest to invert the logic. Instead of passing in a timeout (and doing complex calculations), calculate the end time outside the method:
long timeOut = System.currentTimeMillis() + Long.parseLong(timeOutStr);
In the method, you can check for a timeout using:
if( System.currentTimeMillis() > timeOut ) { break; }
You also don't end the loop in your code (using break or return) so the check for timeout just prevents the recursive call.
Lastly, consider inverting your if() conditions instead of nesting them:
if (!topFolderOrFile.isDirectory()) { return; }
File[] subFoldersAndFileNames = topFolderOrFile.listFiles(filter);
if (subFoldersAndFileNames == null || subFoldersAndFileNames.length == 0) { return; }
...

I guess that this is wrong:
searchFile(subFolderOrFile, type, filter, (timeOut * 1000) - timeElapsed);
^^^^^^^
Looks like you mix time units: you expect seconds but pass a milliseconds value. In your case, the first timeout you pass is equal to 5 seconds, in the first recursion you pass 5000 seconds and 1000 times more in the next level...
Hint: rename the method parameter to timeOutInSeconds and read your code again.

Related

(Using BlueJ) In the terminal, when my code runs to a certain point, the user can continuously type in words but nothing will be done with it

I apologize in advance for my rudimentary code--I started coding a couple months ago.
I'm trying to code a text-based baking game where there's a limited number of combos/recipes (16), and the user has to try to unlock all of the cake combos in order to finish the game. When I try to run the code, when asked for the topping the user wants, no matter what input I type in, the code doesn't run past this part. The expected result would be to take both the flavor and topping and add them together to become the new string of cake.
[A screenshot of the described problem][1]
[1]: https://i.stack.imgur.com/bphyO.png
Another problem I had, but can't check if I still have it because the code won't run past the "topping user input" section, is that when the code runs to the section where it checks if the cake combo has already been found or not, inside the terminal it prints out the combo the user first found infinitely.
I'd really appreciate any help, thank you so much.
The code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class Bakery
public ArrayList<String> aList = new ArrayList();
public static int achievements = 0;
static ArrayList<String> foundCakes = new <String>ArrayList();
public static String[] f = {"chocolate", "vanilla", "strawberry", "banana"};
public static String[] t = {"sprinkles", "fruit", "frosting", "nothing"};
public static void main (String[]args) throws InterruptedException {
Scanner sc = new Scanner(System.in);
System.out.println("(To quit the game, type in 'quit')");
delay("Hi, what's your name?", 60L);
String playerName = sc.nextLine();
delay("Your name is: " + playerName, 60L);
delay("Welcome to this Bakery!", 40L);
delay("This Bakery has been without an owner for so long...",40L);
delay("Most of it's recipies have been lost.", 40L);
delay("It's up to you to collect all of the lost recipies!", 40L);
delay("These are the ingredients provided: ", 60L);
delay("Base flavors: " + Arrays.toString(f), 60L);
delay("Toppings: " + Arrays.toString(t), 60L);
while (achievements != 16){
System.out.println("Pick a flavor");
String flavor = sc.nextLine();
if (flavor.equalsIgnoreCase("quit")){
delay("Thanks for playing!", 40L);
System.exit(0);
}
String cuFlavor = flavor.toLowerCase();
boolean oo = false;
while (oo){
if(Arrays.asList(f).contains(cuFlavor)){
oo = true;
}
}
if (Arrays.asList(f).contains(cuFlavor) == false){
delay("Not an option, please pick again.", 40L);
flavor = sc.nextLine();
}
System.out.println("Pick a topping");
String topping = sc.nextLine();
if (topping.equalsIgnoreCase("quit")){
delay("Thanks for playing!", 40L);
System.exit(0);
}
String cuTopping = topping.toLowerCase();
boolean tt = false;
while (tt==false){
if(Arrays.asList(t).contains(cuTopping) == true){
tt = true;
}
}
if (Arrays.asList(t).contains(cuTopping) == false){
delay("Not an option, please pick again.", 40L);
topping = sc.nextLine();
}
String cake = cuFlavor+cuTopping;
boolean bb = false;
while (bb == false){
if(foundCakes.contains(cake)){
delay("Previously found recipe!", 40L);
delay(getRandomResponse(), 40L);
bb = true;
}
}
boolean nc = true;
while(nc == true){
if(foundCakes.contains(cake) == false){
delay("You found a new cake!", 40L);
delay("Unlocked: "+cake, 40L);
foundCakes.add(cake);
achievements++;
delay("Number of recipes found: " + achievements, 40L);
nc = false;
}
}
}
System.exit(0);
}
public int getAchievements(){
return achievements;
}
private static String getRandomResponse()
{
final int NUMBER_OF_RESPONSES = 4;
double r = Math.random();
int whichResponse = (int)(r * NUMBER_OF_RESPONSES);
String response = "";
if (whichResponse == 0)
{
response = "Don't worry! Still delicious.";
}
else if (whichResponse == 1)
{
response = "What a classic cake!";
}
else if (whichResponse == 2)
{
response = "Yummy :)";
}
else if (whichResponse == 3)
{
response = "Smells nice!";
}
return response;
}
public String toString(){
return "Flavors: "+Arrays.toString(f)+" Topping: "+Arrays.toString(t);
}
public static void delay(String s, long delay) throws InterruptedException {
for ( int i= 0; i < s.length(); i++) {
// for loop delays individual String characters
System.out.print(s.charAt(i));
Thread.sleep(delay); //time is in milliseconds
}
System.out.println(""); // this is the space in between lines
}
}
Take a look at your while loops. First:
boolean oo = false;
while (oo){
if (Arrays.asList(f).contains(cuFlavor)) {
oo = true;
}
}
This loop is never entered since oo == false.
Next:
boolean tt = false;
while (tt == false) {
if (Arrays.asList(t).contains(cuTopping) == true) {
tt = true;
}
}
This loop does execute, but what happens if t does not contain cuTopping? In that case, tt never get sets to true and the loop goes on forever.
The next two loops have the same issue.
You need to ensure the loops will end at some point. Example:
while (tt == false) {
if (Arrays.asList(t).contains(cuTopping) == true) {
tt = true;
}
else {
// Do something to change cuTopping
System.out.println("Pick a topping");
cuTopping = sc.nextLine();
// etc....
}
}
You can combine the loops with the gathering of the input:
String cuTopping = null;
do {
if (cuTopping != null) { // Only true after first iteration
System.out.println("That topping is not in the list!");
}
System.out.println("Pick a topping");
cuTopping = sc.nextLine().toLowerCase();
if (cuTopping.equalsIgnoreCase("quit")) {
delay("Thanks for playing!", 40L);
System.exit(0);
}
} while (!Arrays.asList(t).contains(cuTopping));

Use JLine to Complete Multiple Commands on One Line

I was wondering how I could implement an ArgumentCompleter such that if I complete a full and valid command, then it would begin tab completing for a new command.
I would have assumed it could be constructed doing something like this:
final ConsoleReader consoleReader = new ConsoleReader()
final ArgumentCompleter cyclicalArgument = new ArgumentCompleter();
cyclicalArgument.getCompleters().addAll(Arrays.asList(
new StringsCompleter("foo"),
new StringsCompleter("bar"),
cyclicalArgument));
consoleReader.addCompleter(cyclicalArgument);
consoleReader.readLine();
However right now this stops working after tab completeing the first foo bar
Is anyone familiar enough with the library to tell me how I would go about implementing this? Or is there a known way to do this that I am missing? Also this is using JLine2.
That was quite a task :-)
It is handled by the completer you are using. The complete() method of the completer has to use for the search only what comes after the last blank.
If you look for example at the FileNameCompleter of the library: this is not done at all, so you will find no completion, because the completer searches for <input1> <input2> and not only for <input2> :-)
You will have to do your own implementation of a completer that is able to find input2.
Additionally the CompletionHandler has to append what you found to what you already typed.
Here is a basic implementation changing the default FileNameCompleter:
protected int matchFiles(final String buffer, final String translated, final File[] files,
final List<CharSequence> candidates) {
// THIS IS NEW
String[] allWords = translated.split(" ");
String lastWord = allWords[allWords.length - 1];
// the lastWord is used when searching the files now
// ---
if (files == null) {
return -1;
}
int matches = 0;
// first pass: just count the matches
for (File file : files) {
if (file.getAbsolutePath().startsWith(lastWord)) {
matches++;
}
}
for (File file : files) {
if (file.getAbsolutePath().startsWith(lastWord)) {
CharSequence name = file.getName() + (matches == 1 && file.isDirectory() ? this.separator() : " ");
candidates.add(this.render(file, name).toString());
}
}
final int index = buffer.lastIndexOf(this.separator());
return index + this.separator().length();
}
And here the complete()-Method of the CompletionHandler changing the default CandidateListCompletionHandler:
#Override
public boolean complete(final ConsoleReader reader, final List<CharSequence> candidates, final int pos)
throws IOException {
CursorBuffer buf = reader.getCursorBuffer();
// THIS IS NEW
String[] allWords = buf.toString().split(" ");
String firstWords = "";
if (allWords.length > 1) {
for (int i = 0; i < allWords.length - 1; i++) {
firstWords += allWords[i] + " ";
}
}
//-----
// if there is only one completion, then fill in the buffer
if (candidates.size() == 1) {
String value = Ansi.stripAnsi(candidates.get(0).toString());
if (buf.cursor == buf.buffer.length() && this.printSpaceAfterFullCompletion && !value.endsWith(" ")) {
value += " ";
}
// fail if the only candidate is the same as the current buffer
if (value.equals(buf.toString())) {
return false;
}
CandidateListCompletionHandler.setBuffer(reader, firstWords + " " + value, pos);
return true;
} else if (candidates.size() > 1) {
String value = this.getUnambiguousCompletions(candidates);
CandidateListCompletionHandler.setBuffer(reader, value, pos);
}
CandidateListCompletionHandler.printCandidates(reader, candidates);
// redraw the current console buffer
reader.drawLine();
return true;
}

why cant my function keep a total amount of int values within file?

I am making a program that reads a file of mixed values (int and string), prints only the integer values and keeps a running total of the amount of integer values within the file. Everything is working except for my running total of integer values within a given file and i am very confused on why it keeps printing 0 when i know there are more then 0 integer values within the file.
Here is my code:
package davi0030_a03;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MyFile {
private String fileName; // name of the file
private int count = 0; // number of valid integers in the file
private final int MAX_SIZE = 10; // the size of the array
private Scanner inputStream = null;
private int[] theArray = new int[MAX_SIZE];
private boolean strangeInt = false;
private int total = 0;
// constructor to set the file name
public MyFile(String theName) { // constructor to set the file name
this.fileName = new String(theName);
// you may or may not want to do other stuffs here
}
public void openFile() {
System.out.println("opening file: " + fileName);
try {
inputStream = new Scanner(new FileInputStream("src/davi0030_a03/"
+ fileName));
} catch (FileNotFoundException e) {
System.out.println("File was not found or could not be opened");
}
}
// log a message on whether two ints in the file add to target
public void findPair(int target) {
openFile();
fileToArray();
findStrangeInt();
findTotal();
}
public void findTotal(){
inputStream.reset();
while(inputStream.hasNext()){
if(inputStream.hasNextInt()){
total +=1;
}
inputStream.next();
}
System.out.println(total);
}
public void findStrangeInt() {
inputStream.reset();
while (inputStream.hasNext()) {
try {
Integer.parseInt(inputStream.next());
} catch (NumberFormatException nfe) {
strangeInt = true;
}
}
if (strangeInt = true) {
System.out.println("File contains an incorrectly written int");
}
}
public void fileToArray() {
inputStream.reset();
while (inputStream.hasNext() && count < MAX_SIZE) {
if (inputStream.hasNextInt()) {
theArray[count] = inputStream.nextInt();
count++;
}
}
}
// print the content of the file
public void printFile() {
openFile();
inputStream.reset();
System.out.println("Printing content of file " + fileName);
while (inputStream.hasNext()) {
try {
int convert = Integer.parseInt(inputStream.next());
System.out.println(convert);
} catch (NumberFormatException nfe) {
System.out.println("xxx");
}
}
}
}
content of file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
a
b
d
EDIT: My solution below most likely solves the logic issue regarding your searching the file. However, I suggest you read some of the other comments the question has gotten. The IO handling here especially needs some improvement.
I believe your issue lies in your while statement. According to java documentation on the Scanner class,here, the method .hasNextInt() is returning based on the next element scanned. I think you are assuming it will return true as long as there are ints in the file. This is not the case. If the first thing the scanner hits is not an int, it is returning false and exiting your while loop. This would explain the returned 0, the value you initialize your variable 'total' to. I would suggest you do something like the following:
while(scanner.hasNext()){
if(scanner.hasNextInt()){
total +=1;
}
scanner.next();
}

Cannot Run *.java downloaded file

I have downloaded a java file needed for a coursework at college. However I find it impossible to run it. Eclipse won't give me the chance to even run it (only ant build), and if I use netbeans I get this exception :
Exception in thread "main"
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Uncompilable source code - class Hangman is public, should be declared in a file named Hangman.java
at Hangman. < clinit > (hangman(Case Conflict).java: 20)
Java Result: 1
If someone is kind enough to read through the code, I really do not know what to do next. I figure there has to be something wrong with the main class. Thanks!
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
class Hangman {
Scanner userInput;
private Set < Character > wrongGuesses;
private String[] answers = {
"leverets", "hatchlings", "puppies",
"kittens", "pullets", "goslings"
};
private String answer;
private String guessed;
private int maxTurns;
private int currentTurns;
private boolean inProgress;
private char nextGuess;
private boolean gameWin;
public Hangman() {
userInput = new Scanner(System.in);
wrongGuesses = new HashSet < Character > ();
inProgress = false;
gameWin = false;
maxTurns = 14;
currentTurns = 0;
// set answer somehow
answer = answers[0];
// set guessed to the correct number of dashes
StringBuilder sb = new StringBuilder();
for (int i = 0; i < answer.length(); i++) {
sb.append('-');
}
guessed = sb.toString();
}
/* start a new game */
public void startGame() {
inProgress = true;
startGameLoop();
}
/* the game loop. this method is the heart of the game */
private void startGameLoop() {
printInstructions();
while (inProgress) {
printStatus();
acceptGuess();
checkStatus();
}
printWinOrLose();
}
private void printInstructions() {
System.out
.println("Guess the word one letter at a time until you win or run out of turns. Good luck!");
}
private void printWinOrLose() {
if (gameWin) {
System.out.println("You win! The answer was " + answer);
} else {
System.out.println("You lose.");
}
}
private void printStatus() {
System.out.println("Guesses left: " + (maxTurns - currentTurns));
System.out.println("Current status: " + guessed);
System.out.println("Wrong guesses: " + getWrongAnswers());
}
/* get the next character from the player */
private void acceptGuess() {
System.out.println("Next guess: ");
String temp = userInput.next();
nextGuess = temp.charAt(0);
}
/* check what state the game is in */
private void checkStatus() {
// if already guessed, say already guessed.
if (wrongGuesses.contains(nextGuess)) {
System.out.println("You already guessed that!");
return;
}
// if guess is not in answer, update number of turns played and add
// guess to wrong guesses
// otherwise update the guessed variable
if (answer.indexOf(nextGuess) < 0) {
++currentTurns;
wrongGuesses.add(nextGuess);
} else {
updateGuessStatus();
}
// check to see if the player has won or lost
if (answer.equals(guessed)) {
gameWin = true;
inProgress = false;
}
if (currentTurns == maxTurns) {
inProgress = false;
}
}
/* update the guessed variable when there is a correct guess made */
private void updateGuessStatus() {
// replace - with nextGuess where appropriate
int index = answer.indexOf(nextGuess);
int lastIndex = answer.lastIndexOf(nextGuess);
StringBuilder sb = new StringBuilder(guessed);
if (index != lastIndex) { // more than one instance of the guess in the
// answer
// swap out in a loop
while (index != -1) {
sb.setCharAt(index, nextGuess);
int i = answer.indexOf(nextGuess, (index + 1));
index = i;
}
} else { // letter only appears once
// swap out just that one
sb.setCharAt(index, nextGuess);
}
guessed = sb.toString();
}
/* build a text representation of all the incorrect guesses */
private String getWrongAnswers() {
if (wrongGuesses.size() > 0) {
StringBuilder sb = new StringBuilder();
sb.append('(');
for (Character c: wrongGuesses) {
sb.append(c + ",");
}
sb.deleteCharAt(sb.length() - 1); // delete trailing comma
sb.append(')');
return sb.toString();
} else {
return "<none>";
}
}
public static void main(String[] args) {
Hangman h = new Hangman();
h.startGame();
}
}
The exception says everything you need to know. Rename the class FILE to Hangman.java.
Caused by: java.lang.RuntimeException: Uncompilable source code - class Hangman is public, should be declared in a file named Hangman.java
You should save your downloaded file in Hangman.java and not hangman.java (see it needs 'H' in caps same as your class name).
Change the class to public class Hangman. It allows outside methods to access it.
EDIT: I downloaded the file, changing the class to public worked. I also found an issue in the code itself, the word is always "Leverets".
To change this, edit the getAnswer() method and change it to
private int getAnswer() {
int i = (int) (Math.random() * 6) + 0;
return i;
}

Returning a double from a method

I am currently writing a program that will read through a designated text file that checks the transaction values of each buy/sell/summary and checks the arithmetic such that if the transactions from the buy and sell statements do not equal the total transaction amount that was given in the summary then it outputs an error and closes the program. But currently my method scanMoneyValue has an error that says it's not returning a double, when in fact it is. Is there a different way I should go about returning the values from my method? Here is my code for reference:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class RecurrsionFileChecker {
public static void main(String[] args) {
int result;
//File Chooser Window
JFileChooser chooser = new JFileChooser("/home/nick/workspace/CS 1410-001/src/assignment03");
chooser.setDialogTitle("Please choose a file to be checked");
result = chooser.showOpenDialog(null);
//User Cancelled the chooser
if (result == JFileChooser.CANCEL_OPTION)
return;
File inputfile = chooser.getSelectedFile();
try
{
Scanner in = new Scanner(inputfile);
//Call Method to look at next transaction
scanNextTransaction(in);
}
catch (IOException e)
{
System.out.println("Could not read file: " + inputfile);
}
}
/**
* Returns double if the parameter Scanner has an error that does,
* not match the summary before it.
*
* #param s Any scanner
* #return double if Summaries don't match.
*/
public static double scanNextTransaction(Scanner s)
{
String buy, sell, summary, date;
double amount = 0, referenceValue, total = 0;
summary = s.next();
date = s.next();
referenceValue = scanMoneyValue(s);
while (s.hasNext())
{
if (s.next() == "Buy")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Sell")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Summary")
{
amount = scanSubSummary(s);
}
//add the transactions
total = total + amount;
}
return total;
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
public static double scanSubSummary(Scanner sub)
{
String summaryDate, transDate, transType;
int summarySubEntries, count = 0;
double transValue, summaryValue = 0, totalValue = 0, summaryAmount;
summaryDate = sub.next();
summaryAmount = scanMoneyValue(sub);
summarySubEntries = sub.nextInt();
while (count != summarySubEntries)
{
transType = sub.next();
if (transType == "Summary")
{
summaryValue = scanSubSummary(sub);
}
transValue = scanMoneyValue(sub);
totalValue = transValue + totalValue + summaryValue;
count++;
}
if (totalValue != summaryAmount)
{
System.out.print("Summary error on " + summaryDate + ".");
System.out.println("Amount is $" + summaryAmount + ", " + "should be $" + totalValue + ".");
}
return totalValue;
}
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
If the if condition fails then there's no return statement. You have a return inside of the condition but not outside. You'll need to add a return statement at the end, or throw an exception if not having a dollar sign is an error.
Okay, looking at the only relevant part of your code:
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
You do return a value if dollar starts with a $... but what do you expect to happen if it doesn't start with $? Currently you reach the end of the method without returning anything, which isn't valid.
You should probably throw an exception, if this is unexpected data that you can't actually handle.
Additionally, you shouldn't really use double for currency values anyway, due to the nature of binary floating point types. Consider using BigDecimal instead.
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
//NEED RETURN STATEMENT HERE
}
The error you get is because when you write a function all branches of that function must return a value of the correct type. In your case, if the if-statement fails it hits the end of the function without returning anything.
Its better to change it on
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
String amount = dollar.replaceAll("[^\\d.]+", "")
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
link on explain - Parsing a currency String in java

Categories

Resources