Here I was trying to get two keyboard inputs from the user into a single array index position.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tour;
import java.util.Scanner;
import tour.City;
/**
*
* #author dp
*/
public class Tour {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
City[] city = new City[9];
Scanner in = new Scanner(System.in);
for(int i=0;i<city.length;i++)
{
int no = in.nextInt();
String name = in.nextLine();
city[i]= new City(no,name);
}
}
}
When I run this code it'll give me the following exception.
I'm very new to java and don't know how to solve this.
Since 12 and NY are on different lines, when you do
String name = in.nextLine();
the String that you get back is empty. This is because the Scanner's "reading point" is positioned after 12, but before the end-of-line marker that follows it.
You can fix this by adding another nextLine, and dropping its result:
in.nextLine(); // Skip to end-of-line after the number
String name = in.nextLine();
You are using nextInt() and nextLine() methods to read user inputs, these methods read the next available token, so this is how the existing code is working:
It reads a number using nextInt() and assigns it to no
User then hits return and control reads an empty line (as next line is empty) and assigns it to name
City object gets created with 12 as no and <empty_string> as name. For loop starts it's second execution.
By this time, user has typed NY and hits return
As it expects the token to be an int (by calling nextInt()), it fails and throws an Exception.
If you want the control to read the two inputs separately (and wait until user hits return), use:
int no = Integer.parseInt(in.next());
String name = in.next();
just need to read the int to the last of line
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tour;
import java.util.Scanner;
import tour.City;
/**
*
* #author dp
*/
public class Tour {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
City[] city = new City[9];
Scanner in = new Scanner(System.in);
for(int i=0;i<city.length;i++)
{
int no = in.nextInt();
in.nextLine();//read to the end of line
String name = in.nextLine();
city[i]= new City(no,name);
}
}
}
Related
Well as you can read, when i use the replace function in my code it prints out:
Hey, I'm.
Hey, (name).
When it should only print out Hey, (name).
And i dont understand why. Here is the code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fiestaaburrida;
import java.util.Scanner;
/**
*
* #author xBaco
*/
public class FiestaAburrida {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner teclado = new Scanner(System.in);
int times = teclado.nextInt();
int index = 0;
while (index < times){
String greeting = teclado.next();
String newgreeting = greeting.replace("I'm ","");
System.out.println("Hey, "+newgreeting+".");
}
}
}
Scanner.next() will read your input up to the next delimeter, which by default is a space. Because of this, you are getting two inputs, I'm Joe, rather than the one input I'm Joe.
If you want to take in an entire line at once, you should use Scanner.nextLine(). (Though you should watch out for this quirk which will affect you because of your first nextInt.)
It is because teclado.next(); fetches the next value in the console that is separated by a space. You want to use teclado.nextLine();. Although this is not a complete fix. If you were to follow up with this approach and enter "I'm Jake", than the program would print "Hey, ." followed by "Hey, Jake". This is because you are using teclado.nextInt();, which works, but it will not cause Scanner#nextLine() to read "I'm Jake" immediately. Thus you must also replace nextInt(); with nextLine(); and parse it:
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int times = Integer.parseInt(teclado.nextLine());
int index = 0;
while (index < times){
String greeting = teclado.nextLine();
String newgreeting = greeting.replace("I'm ","");
System.out.println("Hey, " + newgreeting + ".");
}
}
Java's String.replace method find one string and replace the one.
So, I recommend you use String.replaceAll
// ....
while (index < times){
String greeting = teclado.next();
String newgreeting = greeting.replaceAll("I'm ","");
System.out.println("Hey, "+newgreeting+".");
}
// ....
I'm working on a application that reads strings from a document and replaces every occurance of a given word with another word (by user input).
The program runs with three seperate threads ,one for reading data from file to the buffer, one for modifying the strings and one for writing the output.
However, if a checkbox is marked as notify-user then I need to ask the user if he wants to replace the substring at a given 'hit'. Now here is the problem, when I try to use JOptionPane.showConfirmDialog(...) from the modify-thread then the window doesn't contain any content (blank white box).
I also tried to use SwingUtilities.InvokeLater(new Runnable(){ ...logic...} which did work for showing the confirm-box but the other threads continued running in pararell (I need them to stop and wait for user input).
/**
* Checks the status of the string at each position in the buffer. If the status = Status.New and the String-object
* matches to the string to replace then it will be replaced with the String-object replaceString.
* <p>
* If the Status of the object is anything other than Status.New then the thread will be blocked.
* <p>
* When done, the status of the modified object is changed to Status.Checked.
*/
public synchronized void modify() {
try {
while (status[findPos] != Status.New) {
wait();
}
String oldString = buffer[findPos];
if (buffer[findPos].equals(findString)) {
buffer[findPos] = replace(findString, replaceString, start, findString.length());
}
start += oldString.length() + 1;
status[findPos] = Status.Checked;
findPos = (findPos + 1) % maxSize;
} catch (InterruptedException e) {
e.printStackTrace();
}
notify();
}
/**
* Replaces the strSource with strReplace and marks the word in the source-tab JTextPane. The start argument
* represents the index at position to replace the substring, the size argument represents the substring's
* length.
*
* TODO : if notifyUser -> ask for user prompt before replacing.
*
* #param strSource : String
* #param strReplace : String
* #param start : int
* #param size : int
* #return s : String
*/
public String replace(String strSource, String strReplace, int start, int size) {
String s = strSource;
DefaultHighlighter.DefaultHighlightPainter highlightPainter =
new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
//Ask user if he wants to replace the substring at position 'start'.
if (notifyUser) {
int x= JOptionPane.showConfirmDialog(null, "TEST", "TEST", JOptionPane.YES_NO_OPTION);
} else {
try {
textPaneSource.getHighlighter().addHighlight(start, start + size,
highlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
s = strReplace;
nbrReplacement++;
}
return s;
}
I think you need a ThreadLocal variable which is shared between threads. then you must check it in every thread you want to suspend it.
I don't want any codes. I really want to learn the logic myself but I need pointing to the right direction. Pseudocode is fine. I basically need to create a spell checker using hash tables as my primary data structure. I know it may not be the best data structure for the job but that it what i was tasked to do. The words with correct spellings will come from a text file. Please guide me on how to approach the problem.
The way I'm thinking of doing it:
I'm guessing I need to create a ADT class that takes the string words.
I need a main class that reads the dictionary text file and takes a sentence inputted by a user. This class then scans that string of words then places each word into an ArrayList by noting the spaces in between the words. A boolean method will then pass each word in the Arraylist to the class that will handle misspellings and return if the word is valid or false.
I believe I need to create a class that generates the misspellings from the word list and stores them into the hash table? There will be a boolean method that takes a string parameter that checks in the table if the word is valid and return true or false.
In generating the misspellings, the key concepts I will have to look out for will be:
(Take for example the word: "Hello")
Missing characters. E.g. "Ello", "Helo"
Jumbled version of the word. E.g. "ehllo", "helol"
Phonetic misspelling. E.g. "fello" ('f' for 'h')
How can I improve on this thinking?
EDIT! This is what I came up with using HashSet
/**
* The main program that loads the correct dictionary spellings
* and takes input to be analyzed from user.
* #author Catherine Austria
*/
public class SpellChecker {
private static String stringInput; // input to check;
private static String[] checkThis; // the stringInput turned array of words to check.
public static HashSet dictionary; // the dictionary used
/**
* Main method.
* #param args Argh!
*/
public static void main(String[] args) {
setup();
}//end of main
/**
* This method loads the dictionary and initiates the checks for errors in a scanned input.
*/
public static void setup(){
int tableSIZE=59000;
dictionary = new HashSet(tableSIZE);
try {
//System.out.print(System.getProperty("user.dir"));//just to find user's working directory;
// I combined FileReader into the BufferReader statement
//the file is located in edu.frostburg.cosc310
BufferedReader bufferedReader = new BufferedReader(new FileReader("./dictionary.txt"));
String line = null; // notes one line at a time
while((line = bufferedReader.readLine()) != null) {
dictionary.add(line);//add dictinary word in
}
prompt();
bufferedReader.close(); //close file
}
catch(FileNotFoundException ex) {
ex.printStackTrace();//print error
}
catch(IOException ex) {
ex.printStackTrace();//print error
}
}//end of setUp
/**
* Just a prompt for auto generated tests or manual input test.
*/
public static void prompt(){
System.out.println("Type a number from below: ");
System.out.println("1. Auto Generate Test\t2.Manual Input\t3.Exit");
Scanner theLine = new Scanner(System.in);
int choice = theLine.nextInt(); // for manual input
if(choice==1) autoTest();
else if(choice==2) startwInput();
else if (choice==3) System.exit(0);
else System.out.println("Invalid Input. Exiting.");
}
/**
* Manual input of sentence or words.
*/
public static void startwInput(){
//printDictionary(bufferedReader); // print dictionary
System.out.println("Spell Checker by C. Austria\nPlease enter text to check: ");
Scanner theLine = new Scanner(System.in);
stringInput = theLine.nextLine(); // for manual input
System.out.print("\nYou have entered this text: "+stringInput+"\nInitiating Check...");
/*------------------------------------------------------------------------------------------------------------*/
//final long startTime = System.currentTimeMillis(); //speed test
WordFinder grammarNazi = new WordFinder(); //instance of MisSpell
splitString(removePunctuation(stringInput));//turn String line to String[]
grammarNazi.initialCheck(checkThis);
//final long endTime = System.currentTimeMillis();
//System.out.println("Total execution time: " + (endTime - startTime) );
}//end of startwInput
/**
* Generates a testing case.
*/
public static void autoTest(){
System.out.println("Spell Checker by C. Austria\nThis sentence is being tested:\nThe dog foud my hom. And m ct hisse xdgfchv!## ");
WordFinder grammarNazi = new WordFinder(); //instance of MisSpell
splitString(removePunctuation("The dog foud my hom. And m ct hisse xdgfchv!## "));//turn String line to String[]
grammarNazi.initialCheck(checkThis);
}//end of autoTest
/**
* This method prints the entire dictionary.
* Was used in testing.
* #param bufferedReader the dictionary file
*/
public static void printDictionary(BufferedReader bufferedReader){
String line = null; // notes one line at a time
try{
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}catch(FileNotFoundException ex) {
ex.printStackTrace();//print error
}
catch(IOException ex) {
ex.printStackTrace();//print error
}
}//end of printDictionary
/**
* This methods splits the passed String and puts them into a String[]
* #param sentence The sentence that needs editing.
*/
public static void splitString(String sentence){
// split the sentence in between " " aka spaces
checkThis = sentence.split(" ");
}//end of splitString
/**
* This method removes the punctuation and capitalization from a string.
* #param sentence The sentence that needs editing.
* #return the edited sentence.
*/
public static String removePunctuation(String sentence){
String newSentence; // the new sentence
//remove evil punctuation and convert the whole line to lowercase
newSentence = sentence.toLowerCase().replaceAll("[^a-zA-Z\\s]", "").replaceAll("\\s+", " ");
return newSentence;
}//end of removePunctuation
}
This class checks for misspellings
public class WordFinder extends SpellChecker{
private int wordsLength;//length of String[] to check
private List<String> wrongWords = new ArrayList<String>();//stores incorrect words
/**
* This methods checks the String[] for spelling errors.
* Hashes each index in the String[] to see if it is in the dictionary HashSet
* #param words String list of misspelled words to check
*/
public void initialCheck(String[] words){
wordsLength=words.length;
System.out.println();
for(int i=0;i<wordsLength;i++){
//System.out.println("What I'm checking: "+words[i]); //test only
if(!dictionary.contains(words[i])) wrongWords.add(words[i]);
} //end for
//manualWordLookup(); //for testing dictionary only
if (!wrongWords.isEmpty()) {
System.out.println("Mistakes have been made!");
printIncorrect();
} //end if
if (wrongWords.isEmpty()) {
System.out.println("\n\nMove along. End of Program.");
} //end if
}//end of initialCheck
/**
* This method that prints the incorrect words in a String[] being checked and generates suggestions.
*/
public void printIncorrect(){//delete this guy
System.out.print("These words [ ");
for (String wrongWord : wrongWords) {
System.out.print(wrongWord + " ");
}//end of for
System.out.println("]seems incorrect.\n");
suggest();
}//end of printIncorrect
/**
* This method gives suggestions to the user based on the wrong words she/he misspelled.
*/
public void suggest(){
MisSpell test = new MisSpell();
while(!wrongWords.isEmpty()&&test.possibilities.size()<=5){
String wordCheck=wrongWords.remove(0);
test.generateMispellings(wordCheck);
//if the possibilities size is greater than 0 then print suggestions
if(test.possibilities.size()>=0) test.print(test.possibilities);
}//end of while
}//end of suggest
/*ENTERING TEST ZONE*/
/**
* This allows a tester to look thorough the dictionary for words if they are valid; and for testing only.
*/
public void manualWordLookup(){
System.out.print("Enter 'ext' to exit.\n\n");
Scanner line = new Scanner(System.in);
String look=line.nextLine();
do{
if(dictionary.contains(look)) System.out.print(look+" is valid\n");
else System.out.print(look+" is invalid\n");
look=line.nextLine();
}while (!look.equals("ext"));
}//end of manualWordLookup
}
/**
* This is the main class responsible for generating misspellings.
* #author Catherine Austria
*/
public class MisSpell extends SpellChecker{
public List<String> possibilities = new ArrayList<String>();//stores possible suggestions
private List<String> tempHolder = new ArrayList<String>(); //telps for the transposition method
private int Ldistance=0; // the distance related to the two words
private String wrongWord;// the original wrong word.
/**
* Execute methods that make misspellings.
* #param wordCheck the word being checked.
*/
public void generateMispellings(String wordCheck){
wrongWord=wordCheck;
try{
concatFL(wordCheck);
concatLL(wordCheck);
replaceFL(wordCheck);
replaceLL(wordCheck);
deleteFL(wordCheck);
deleteLL(wordCheck);
pluralize(wordCheck);
transposition(wordCheck);
}catch(StringIndexOutOfBoundsException e){
System.out.println();
}catch(ArrayIndexOutOfBoundsException e){
System.out.println();
}
}
/**
* This method concats the word behind each of the alphabet letters and checks if it is in the dictionary.
* FL for first letter
* #param word the word being manipulated.
*/
public void concatFL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=97;i<123;i++){
cur=(char)i;//assign ASCII from index i value
tempWord+=cur;
//if the word is in the dictionary then add it to the possibilities list
tempWord=tempWord.concat(word); //add passed String to end of tempWord
checkDict(tempWord); //check to see if in dictionary
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of concatFL
/**
* This concatenates the alphabet letters behind each of the word and checks if it is in the dictionary. LL for last letter.
* #param word the word being manipulated.
*/
public void concatLL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=123;i>97;i--){
cur=(char)i;//assign ASCII from index i value
tempWord=tempWord.concat(word); //add passed String to end of tempWord
tempWord+=cur;
//if the word is in the dictionary then add it to the possibilities list
checkDict(tempWord);
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of concatLL
/**
* This method replaces the first letter (FL) of a word with alphabet letters.
* #param word the word being manipulated.
*/
public void replaceFL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=97;i<123;i++){
cur=(char)i;//assign ASCII from index i value
tempWord=cur+word.substring(1,word.length()); //add the ascii of i ad the substring of the word from index 1 till the word's last index
checkDict(tempWord);
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of replaceFL
/**
* This method replaces the last letter (LL) of a word with alphabet letters
* #param word the word being manipulated.
*/
public void replaceLL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=97;i<123;i++){
cur=(char)i;//assign ASCII from index i value
tempWord=word.substring(0,word.length()-1)+cur; //add the ascii of i ad the substring of the word from index 1 till the word's last index
checkDict(tempWord);
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of replaceLL
/**
* This deletes first letter and sees if it is in dictionary
* #param word the word being manipulated.
*/
public void deleteFL(String word){
String tempWord=word.substring(1,word.length()-1); // stores temp made up word
checkDict(tempWord);
//print(possibilities);
}//end of deleteFL
/**
* This deletes last letter and sees if it is in dictionary
* #param word the word being manipulated.
*/
public void deleteLL(String word){
String tempWord=word.substring(0,word.length()-1); // stores temp made up word
checkDict(tempWord);
//print(possibilities);
}//end of deleteLL
/**
* This method pluralizes a word input
* #param word the word being manipulated.
*/
public void pluralize(String word){
String tempWord=word+"s";
checkDict(tempWord);
}//end of pluralize
/**
* It's purpose is to check a word if it is in the dictionary.
* If it is, then add it to the possibilities list.
* #param word the word being checked.
*/
public void checkDict(String word){
if(dictionary.contains(word)){//check to see if tempWord is in dictionary
//if the tempWord IS in the dictionary, then check if it is in the possibilities list
//then if tempWord IS NOT in the list, then add tempWord to list
if(!possibilities.contains(word)) possibilities.add(word);
}
}//end of checkDict
/**
* This method transposes letters of a word into different places.
* Not the best implementation. This guy was my last minute addition.
* #param word the word being manipulated.
*/
public void transposition(String word){
wrongWord=word;
int wordLen=word.length();
String[] mixer = new String[wordLen]; //String[] length of the passed word
//make word into String[]
for(int i=0;i<wordLen;i++){
mixer [i]=word.substring(i,i+1);
}
shift(mixer);
}//end of transposition
/**
* This method takes a string[] list then shifts the value in between
* the elements in the list and checks if in dictionary, adds if so.
* I agree that this is probably the brute force implementation.
* #param mixer the String array being shifted around.
*/
public void shift(String[] mixer){
System.out.println();
String wordValue="";
for(int i=0;i<=tempHolder.size();i++){
resetHelper(tempHolder);//reset the helper
transposeHelper(mixer);//fill tempHolder
String wordFirstValue=tempHolder.remove(i);//remove value at index in tempHolder
for(int j=0;j<tempHolder.size();j++){
int inttemp=0;
String temp;
while(inttemp<j){
temp=tempHolder.remove(inttemp);
tempHolder.add(temp);
wordValue+=wordFirstValue+printWord(tempHolder);
inttemp++;
if(dictionary.contains(wordValue)) if(!possibilities.contains(wordValue)) possibilities.add(wordValue);
wordValue="";
}//end of while
}//end of for
}//end for
}//end of shift
/**
* This method fills a list tempHolder with contents from String[]
* #param wordMix the String array being shifted around.
*/
public void transposeHelper(String[] wordMix){
for(int i=0;i<wordMix.length;i++){
tempHolder.add(wordMix[i]);
}
}//end of transposeHelper
/**
* This resets a list
* #param thisList removes the content of a list
*/
public void resetHelper(List<String> thisList){
while(!thisList.isEmpty()) thisList.remove(0); //while list is not empty, remove first value
}//end of resetHelper
/**
* This method prints out a list
* #param listPrint the list to print out.
*/
public void print(List<String> listPrint){
if (possibilities.isEmpty()) {
System.out.print("Can't seem to find any related words for "+wrongWord);
return;
}
System.out.println("Maybe you meant these for "+wrongWord+": ");
System.out.printf("%s", listPrint);
resetHelper(possibilities);
}//end of print
/**
* This returns a String word version of a list
* #param listPrint the list to make into a word.
* #return the generated word version of a list.
*/
public String printWord(List<String> listPrint){
Object[] suggests = listPrint.toArray();
String theWord="";
for(Object word: suggests){//form listPrint elements into a word
theWord+=word;
}
return theWord;
}//end of printWord
}
Instead of generating all possible misspellings of the words in your dictionary and adding them to the hash table, consider performing all possible changes (that you already suggested) to the user-entered words, and checking to see if those words are in the dictionary file.
It sounds like what you want is a quick way to verify that a word is spelled correctly, or to find the correct spelling. If this is what your trying to do you can use a HashMap<String,String> (i.e. a hash table with String keys and String values). Whenever you find a word in your dictionary you enter a key for it with a null value indicating that the word is not to be changed (i.e. a correct spelling). You can then compute and add keys for possible misspellings and give the correct word for the value.
You'd have to devise a way to do this very carefully, because if your dictionary has two similar words "clot" and "colt" computed misspellings of one may replace the correct spelling (or misspellings) of the other. Once your done you can look up a word to see if it is in the dictionary, if it is a misspelling of a dictionary word (and which word), or if it is not found at all.
I believe this is a bad design though, because your table has to be exponentially larger than your (I assume, already quite large) dictionary. And because you spent a lot of time calculating many misspelling for every word in the dictionary (very big overhead if you only check a few lines which may contain a few of these words). Given a only a little liberty I would opt for a HashSet<String> (which is a hash table but without values) filled only with dictionary words. This is allows you to check quickly if a word is in the dictionary or not.
You can dynamically compute other ways to spell words when you encounter ones not in your dictionary. If your doing this for only a line or two it should not be slow at all (certainly faster than computing alternatives for everything in your dictionary). But if you wanted to this for every for a whole file you may want to keep a much smaller HashMap<String,String> separate from your dictionary to store any corrections you find since the author may misspell the word the same way in future. Checking this before computing alternatives keeps you from duplicating your efforts several times over.
How do I go about asking for a string input, then extracting the 0 character?
I was using "fstream.next()" and it would input whatever, not just a string.
I just need a character, which I can later use in a loop where the program only accepts char inputs of T, D, and E.
Then the program reads the double. Then the program calls the instance method with the parameters (char, double). The instance method later does it's thing and saves the inputs. The program later loops back and does it all over again.
Currently I am receiving an error "java.util.InputMismatchException". If you could offer suggestions, I'd greatly appreciate it! If clarification is needed, please let me know. Thank you in advance! :)
Here is my code:
/** holds answer of whether user has more inputs or not */
String answer;
/** holds the results when calling inLetter() */
char letter;
/** holds the results when checking for types/strings in txt file */
String inType = "";
/** holds double results when searching line by line the text file */
double inAmount = 0;
/** holds the results when calling inAmount() */
double amount;
/** initiates infile to null */
File infile = null;
/** count system for how many valid lines were read and used */
int count = 0;
/** calls description method */
description();
/** initiates new Object */
GironEventClass newInput = new GironEventClass();
try{
/** defines new variable linked to .dat file */
infile = new File("GironEvent.dat");
/** calls fstream scanner - for use on file */
Scanner fstream = new Scanner(infile);
/** calls while loop. As long as there is a line, the loop continues */
while(fstream.hasNext())
{
/** inputs first string in line of file to variable inType */
inType = fstream.nextLine();
char a_char = inType.charAt(0);
/** inputs first int in line of file to variable inAmount */
inAmount = fstream.nextDouble();
try{
/** calls instance method with two parameters */
newInput.donations(a_char, inAmount);
/** count ticket increases */
count+=1;
}
catch(IllegalArgumentException a){
/** prints out error if exception is caught*/
System.out.println("Just caught an illegal argument exception. ");
}
}
/** closes stream between program and fiel */
fstream.close();
/** outputs line count, and totals per type */
System.out.println("\n" + count + " number of valid lines were read!\n");
System.out.println("Total Sales: " + newInput.getSale());
System.out.println("Donations: " + newInput.getDonated());
System.out.println("Expenses: " + newInput.getExpenses());
}
catch (FileNotFoundException e){
/** Outputs error if file cannot be opened. */
System.out.println("\nGironEvent.dat could not be opened. ");
}
do{
/** loop asks user if there is more that needs to be added to the totals. N exits loop. */
System.out.print("\nAre there any more items to add that were not in the text file? (Type 'Y' or 'N'): ");
answer = keyboard.next();
if (("Y".equals(answer)) || ("y".equals(answer)))
{
letter = inLetter();
amount = inAmount();
newInput.donations(letter, amount);
}
}while (("Y".equals(answer)) || ("y".equals(answer)));
/** calls instance method to display totals in a fancy manner */
newInput.display();
}
/** inLetter - displays types to user. Asks user to input type. Converts input into uppercase letter.
*
* #return resultTwo - Uppercase form of result. Result is the type the user inputted.
*/
public static char inLetter(){
Scanner keyboard = new Scanner(System.in);
String result;
String resultTwo;
System.out.println("T = Tiket Sales");
System.out.println("D = Donations");
System.out.println("E = Expenses");
System.out.print("Please input an identifier ");
result = keyboard.nextLine();
resultTwo = result.toUpperCase();
return resultTwo;
}
/** inAmount - asks user for amount. Tests that amount isn't a negative number or a zero.
*
* #return result - the amount the user inputed. regardless if it was the first or tenth time.
*/
public static double inAmount(){
Scanner keyboard = new Scanner(System.in);
double result;
System.out.println("Please input an amount ");
result = keyboard.nextDouble();
if(result <= 0){
System.out.print("Please input a positive and non-zero amount ");
result = keyboard.nextDouble();
}
return result;
}
/** description - displays a description of what the program does
* void.
*/
public static void description(){
System.out.println("The program will ask you what amount is being spent on what.");
System.out.println(" ex: expenses, ticket sales, and profts.");
System.out.println("This program will help determine whether the event generated or lost money.");
}
I need assistance with the following block:
/** inputs first string in line of file to variable inType */
inType = fstream.nextLine();
char a_char = inType.charAt(0);
/** inputs first int in line of file to variable inAmount */
inAmount = fstream.nextDouble();
Your fstream is having a combination of String and Double.
So when you use fstream.nextDouble() it throws java.util.InputMismatchException
Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextDouble()
You can first check whether the next character is double or not with the method hasNextDouble()
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextDouble()
I am using a 'ConsoleSupport' class which handles the receiving and validation of input from the user. One problem I noticed was that if I asked for an integer (menu option) in my console UI first, then asked for a couple of Strings, the first String would be empty. The dreaded newline character strikes again! I used the following in my getType methods before returning the value to make it work:
if(in.hasNextLine())
in.nextLine();
Does anyone have an alternative, more 'elegant' solution to dealing with input that is not wanted?
The (abbreviated) class is below for reference
import java.util.Scanner;
/**
* This class will reliably and safely retrieve input from the user
* without crashing. It can collect an integer, String and a couple of other
* types which I have left out for brevity
*
* #author thelionroars1337
* #version 0.3 Tuesday 25 September 2012
*/
public class ConsoleSupport
{
private static Scanner in = new Scanner(System.in);
/**
* Prompts user for an integer, until it receives a valid entry
*
* #param prompt The String used to prompt the user for an int input
* #return The integer
*/
public static int getInteger(String prompt)
{
String input = null;
int integer = 0;
boolean validInput = false;
while(!validInput)
{
System.out.println(prompt);
input = in.next();
if(input.matches("(-?)(\\d+)"))
{
integer = Integer.parseInt(input);
validInput = true;
}
else
{
validInput = false;
System.out.println("Sorry, this input is incorrect! Please try again.");
}
}
if(in.hasNextLine())
in.nextLine(); // flush the Scanner
return integer;
}
/**
* Prompts the user to enter a string, and returns the input
*
* #param prompt The prompt to display
* #return The inputted string
*/
public static String getString(String prompt)
{
System.out.println(prompt);
return in.nextLine();
}
}
Input from System.in isn't available to be read until the user hits enter. Because of that, there's an extra newline in the Scanner's buffer after the integer. So when you call Scanner.nextInt() you read the integer, but the next time you call Scanner.nextLine(), you'll read up to the newline in the buffer and it would return a blank String.
One way to deal with it is to just always call nextLine() and use Integer.parseInt() like you're doing above. You could probably skip the regex match and instead just catch the NumberFormatException:
while(!validInput)
{
System.out.println(prompt);
input = in.nextLine();
try {
integer = Integer.parseInt(input.trim());
validInput = true;
}
catch(NumberFormatException nfe) {
validInput = false;
System.out.println("Sorry, this input is incorrect! Please try again.");
}
}
And you wouldn't need to check if there's an extra line at the end and flush the scanner.