Unreported IOException? What is wrong with this code? - java

I am working on some code for homework and for the life of me can't figure out why this won't run. It ran until I added in the methods for file reading, which I know worked in another program. I took the code directly from some of my other work. So, can someone much better at Java than I tell me what I am doing wrong to have this problem? As this is homework please don't tell me how to fix any other problems, but I wouldn't discourage hints about them.
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class vowels_r_us {
//for file reading
private static FileInputStream inFile;
private static InputStreamReader inReader;
private static BufferedReader reader;
//pasrsing input from file
private static StringTokenizer strTkn;
public static void main(String[] args)
{
initFile(); //prepare file for reading
while (reader.ready())//iterate as long as there is more avaliable data
{
String word, suffix, line;
line = getWordSuffix();
word = line.substring(0, line.indexOf(' '));
suffix = line.substring(line.indexOf(' '));
}
}
/*CONJUGATION METHODS*/
static String pluralize(String s)
{
String pluralForm;
switch (classifyEnding(s))
{
case 'c':
pluralForm = s.concat("GH");
break;
case 'v':
pluralForm = s.substring(0, s.length() - 1).concat("G");//drop last letter add G
break;
case 'd':
pluralForm = s + s.charAt(s.length() - 1) +"H";//double last letter, then add H
break;
default:
pluralForm = "If you are getting this something is broken, have fun debugging.";
break;
}
return pluralForm;
}
static String addSuffix(String word, String suffix)
{
String suffixAdded;
switch (classifyEnding(word))
{
case 'c':
suffixAdded = word + suffix;
break;
case 'v':
if(isVowel(suffix.charAt(0)))
{
suffixAdded = word + suffix.substring(1);//word + drop first letter of suffix then add suffix
}
else
{
suffixAdded = word + suffix.charAt(0) + suffix;//word + first letter of suffix + suffix
}
break;
case 'd':
if(isVowel(suffix.charAt(0)))
{
suffixAdded = word + suffix.charAt(0) + suffix;//word + first letter of suffix + suffix
}
else
{
suffixAdded = trimRepeatSequence(word) + suffix;
}
break;
default:
suffixAdded = "If you are getting this something is broken, have fun debugging.";
break;
}
return suffixAdded;
}
/*END CONJUGATION METHODS*/
/*STRING MODIFICATION AND TESTING METHODS*/
//removes lefmost vowel or consonant from sequence
static String trimRepeatSequence(String s)
{
String editedString = "";
boolean vBasedEnding = isVowel(s.charAt(s.length() - 1));
for (int i = s.length() - 1; i >= 0; i--)
{
if (isVowel(s.charAt(i)) != vBasedEnding)
{
editedString = s.substring(0, i+1) + s.substring(i+2, s.length());
break;
}
}
return editedString;
}
/* classify endings in to three grammatical categories, single vowel ending 'v', single consonant ending 'c', double type ending 'd'
*/
static char classifyEnding(String s)
{
char grammaticalClass;
if (isVowel(s.charAt(s.length()- 1)) == isVowel(s.charAt(s.length()- 2)))
{
grammaticalClass = 'd';
}
else
{
grammaticalClass = isVowel(s.charAt(s.length()- 1)) == true? 'v' : 'c';
}
return grammaticalClass;
}
static boolean isVowel(char c)
{
boolean b;//rename
switch (Character.toLowerCase(c))
{
case 'a': case 'c':
case 's': case 'l':
b = true;
break;
default:
b = false;
break;
}
return b;
}
/*END STRING MODIFICATION AND TESTING METHODS*/
/*FILE READER METHODS*/
//read file for input
public static void initFile() throws IOException
{
inFile = new FileInputStream ("C:\\Users\\Tom\\Dropbox\\!!VHSAPCSData\\VHSP35data.txt");
inReader = new InputStreamReader(inFile);
reader = new BufferedReader(inReader);
}
public static String getWordSuffix() throws IOException
{
String line;
line = reader.readLine();
return line;
}
}

You need to wrap your IO code in a try / catch:
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
taken from: http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Related

Improvise the code against test cases where code fails

I wrote below code and i want to identify the test cases where my code fails.I want to identify the possible test cases where my test case failed. so i will improvise the same, in addition I also want to enhance it, meaning,also suggest me the best practice to improve performance.
At last, In the below code I have one method returnFinalComplement(String reverseStr) which return the complement, for calculating complement I have two Approaches, both are doing the same job, I am currenlty using approach-1, but i want to know about approach-2, which approach can pass all the test cases .
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
class DNAString {
private final static Character[] DATASET = {'A', 'C', 'G', 'T'};
private final static int MIN_RANGE = 0;
private final static int MAX_RANGE = 1000;
private final static String INVALID_CHAR = "Invalid input,not matched
with dataset";
private final static String CHAR_LENGTH_EXCEEDS = "Input does not
allow to be exceeds more than " + MAX_RANGE + " characters";
private static String returnFinalComplement(String reverseStr) {
//APPROACH-1
StringBuilder finalStr = new StringBuilder();
for (char c : reverseStr.toCharArray()) {
finalStr.append(
c == 'G' ? 'C'
: c == 'C' ? 'G'
: c == 'T' ? 'A'
: c == 'A' ? 'T'
: c
);
}
return finalStr.toString();
//APPROACH-2
char[] charlist = list.toCharArray();
for (int i = 0; i < charlist.length; i++) {
switch (charlist[i]) {
case 'A': {
charlist[i] = 'T';
}
break;
case 'T': {
charlist[i] = 'A';
}
break;
case 'G': {
charlist[i] = 'C';
}
break;
case 'C': {
charlist[i] = 'G';
}
break;
}
}
return new String(charlist);
}
public static boolean validateInput(String input) {
List<Character> chars = new ArrayList<>();
for (char c : input.toCharArray()) {
chars.add(c);
}
boolean result = false;
SortedSet<Character> mySet = new TreeSet<>(chars);
for (int i = 0; i <= mySet.size();) {
for (Character c : mySet) {
result = Objects.equals(c, DATASET[i]);
i++;
if (!result) {
break;
}
}
if (result) {
return result;
} else {
break;
}
}
return result;
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}
return dest.toString();
}
public static void main(String[] args) throws IOException {
BufferedReader readInput = new BufferedReader(new
InputStreamReader(System.in));
String source = readInput.readLine();
if (source.length() > MIN_RANGE && source.length() <= MAX_RANGE) {
boolean validateInput = validateInput(source);
if (validateInput) {
// String reverseString = reverseIt(source);
String reverseString = reverseIt(source);
System.out.println(returnFinalComplement(reverseString));
// String revereStringComplement =
returnFinalComplement(reverseString);
} else {
System.out.println(INVALID_CHAR);
}
} else {
System.out.println(CHAR_LENGTH_EXCEEDS);
}
}
}

Clean string method for a recusrion palindrome java program?

This is a recursion program to test whether or not a sentence is a palindrome. It will run correctly if I write "bob" but not for "Madam I'm Adam" because of the caps and symbols. We are required to use a clean string method(?) to eliminate the spaces, symbols, and caps. This is what I have but I don't believe I've implemented it correctly. Could someone tell me how to improve/fix this? (Yes, I've looked all over the internet)
import java.util.Scanner;
public class Palindromes {
public static boolean isaPalindrome(String s) {
String cleanedString = clean(s);
if (s.length() == 0 || s.length() == 1)
return true;
if (s.charAt(0) == s.charAt(s.length() - 1))
return isaPalindrome(s.substring(1, s.length() - 1));
return false;
}
public static void main(String[] args) {
System.out.print("Enter a palindrome to test: ");
Scanner console = new Scanner(System.in);
String inStr = console.nextLine();
if (isaPalindrome(inStr)) {
System.out.printf("The input string, %s, is a palindrome.\n",
inStr);
reverseStr(inStr); // must be recursive!
System.out.println();
} else {
System.out.printf("The input string, %s, is not a palindrome.\n",
inStr);
}
}
private static String clean(String s) {
String cleaned = "";
return cleaned;
}
private static String reverseStr(String inStr) {
if ((null == inStr) || (inStr.length() <= 1)) {
return inStr;
}
return reverseStr(inStr.substring(1)) + inStr.charAt(0);
}
}
Your recursive method isaPalindrome is correct. If you want to further improve it, I would suggest you to avoid using subString to create parameters for your recursive call, this will create too many strings.
Instead, keep track of the positions of the characters in the original string that you are comparing:
public static boolean isaPalindrome(String s, int leftIndex, int rightIndex) {
if (leftIndex == rightIndex) return true;
if (s.charAt(leftIndex) == s.charAt(rightIndex))
return isaPalindrome(s, leftIndex + 1, rightIndex - 1);
return false;
}
You would invoke the method as: isaPalindrome(inStr, 0, inStr.length() - 1)
As for your clean method, you can use toLowerCase and Character.isLetter method to process the original string.
private static String clean(String s) {
String lowerCaseString = s.toLowerCase();
StringBuffer result = new StringBuffer();
for (int i = 0; i < lowerCaseString.length(); ++i) {
if (Character.isLetter(lowerCaseString.charAt(i))) {
result.append(lowerCaseString.charAt(i));
}
}
return result.toString();
}
Try this:
public static void main(final String[] args) {
final String unclean = "Madam I'm Adam";
final String clean = cleanString(unclean);
System.out.println("Clean string is: " + clean);
}
static private String cleanString(final String pTheString) {
final StringBuilder sb = new StringBuilder(pTheString.length());
for (final char c : pTheString.toCharArray()) {
switch (c) {
// ignore all those
case ' ':
case '\'':
case '.':
break;
// write the rest
default:
sb.append(c);
}
}
return sb.toString().toLowerCase();
}

infix to postfix in java using stack class

I'm trying to write infix to postfix program in java using stack. Here is my code:
import java.io.*;
import java.util.*;
public class ONP{
public static void main(String args[]) throws java.io.IOException, NumberFormatException ,EmptyStackException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringBuilder out= new StringBuilder();
Stack st=new Stack();
for(int i=0;i<n;i++){
String input=br.readLine();
char in[]=input.toCharArray();
int len=input.length();
for (int j=0;j<len;j++){
if (in[j]>='a' && in[j]<='z'){
out.append(in[j]);
}
else if(in[j]=='('){
st.push(new Character(in[j]));
}
else if(in[j]=='+' || in[j]=='-' || in[j]=='*' || in[j]=='/' || in[j]=='^'){
st.push(new Character(in[j]));
}
else if(in[j]==')'){
int k=j;
while(in[k]!='(' && !st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch!='('&&ch!=')')
out.append(ch);
k--;
}
}
}
out.append("\n");
}
System.out.print(out);
}
}
Input:
((a+t)*((b+(a+c))^(c+d)))
Output:
at+bac++*cd+^
"*" should come after "+^" but it comes after "++". I can't find the bug.
It's just a small error.
In this code you look for '(' in the "in" array which makes no sense. You only want to look for it on the stack.
else if(in[j]==')'){
int k=j;
while(in[k]!='(' && !st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch!='('&&ch!=')')
out.append(ch);
k--;
}
}
Just change it to this
else if(in[j]==')'){
while(!st.empty() ){
char ch=st.pop().toString().charAt(0);
if(ch == '(') break;
out.append(ch);
}
}
That should fix the error. But there are a lot of other details you could improve. e.g. put part of the code into another method and make use of generics and autoboxing. Use Strings instead of chars to allow operators with more then one character and also implement operator precedence so you don't need so many parentheses.
Look at this.
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class ONP {
private static int precedence(String operator) {
switch(operator) {
case "(": return 0;
case "+": case "-": return 1;
case "*": case "/": return 2;
case "^": return 3;
case "sin": case "cos": return 4;
default: return -1;
}
}
private static List<String> tokenize(String input) {
ArrayList<String> tokens = new ArrayList<>();
Pattern p = Pattern.compile("\\(|\\)|[A-Za-z]+|\\d*\\.\\d*|\\d+|\\S+?");
Matcher m = p.matcher(input);
while(m.find()) {
tokens.add(m.group());
}
return tokens;
}
private static List<String> toPostfix(List<String> infix) {
Stack<String> st = new Stack<>();
ArrayList<String> out = new ArrayList<>();
for(String s: infix) {
if(s.equals("(")){
st.push(s);
} else if(s.equals(")")){
while(!st.empty() ){
String s2 = st.pop();
if(s2.equals("(")) break;
out.add(s2);
}
} else if(precedence(s) > 0) {
int p = precedence(s);
while(!st.isEmpty() && precedence(st.peek()) >= p) out.add(st.pop());
st.push(s);
} else {
out.add(s);
}
}
while(!st.isEmpty()) out.add(st.pop());
return out;
}
public static void main(String args[]) throws java.io.IOException, NumberFormatException ,EmptyStackException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++){
String input=br.readLine();
List<String> tokens = tokenize(input);
System.out.println("tokens: " + tokens);
List<String> postfix = toPostfix(tokens);
System.out.print("postfix: ");
for(String s: postfix) System.out.print(s + " ");
System.out.println();
}
}
}
Well you need to implement operator precedence, and you haven't. You need to look up the Dijkstra Shunting-yard algorithm.

How to translate English into PigLatin with java (using boolean and string)

I'm trying to write a program that checks a user supploed sentence and converts it to Pig Latin. I'm trying to have the program check to see if the first letter is a vowel or not and return that using a boolean expression. Next I'm trying to get the program to cut off the first letter from the word and add it to the end of the word. Finally its supposed to add way if it is a vowel and ay if it not a vowel. Any help or advice will be greatly appreciated.
public class PigLatin {
public static void main(String[] argv) {
if (argv.length > 0) {
for (int i = 0; i < argv.length; i++) {
char firstLetter = aStringVariable.charAt(0);
}
}
public static boolean isVowel(char c) {
char[] vowels = new char[] {'a', 'e', 'i', 'o', 'u', 'y'};
for(int i = 0; i < vowels.length; i++) {
if(Character.toString(vowels[i]).equalsIgnoreCase(Character.toString(c))) {
return true;
}
}
return false;
}
public static String makePigLatin(boolean vowel, String word)
{
String everythingButTheFirstLetter = word.substring(1);
String n = everythingButTheFirstLetter + firstLetter;
if (true)
{
System.out.println(n + "way");
}
if (false)
{
System.out.println(n + "ay");
}
}
}
Try something like this -
public static class PigLatin {
public static boolean isVowel(char c) {
switch (Character.toLowerCase(c)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
return true;
}
return false;
}
public static String makePigLatin(String word) {
char firstLetter = word.charAt(0);
String everythingElse = word.substring(1);
String n = everythingElse + firstLetter;
if (isVowel(firstLetter)) {
return n + "way";
}
return n + "ay";
}
}
public static void main(String args[]) {
String[] words = { "fair", "away", "test" };
for (String word : words) {
String s = PigLatin.makePigLatin(word);
System.out.println(word + " is " + s);
}
}
Output is
fair is airfay
away is wayaway
test is esttay
You can also try something like:
public static string PigLatin(string sentence)
{
const string vowels = "AEIOUaeiou";
sentence = sentence.ToLower();
var returnSentence = "";
foreach (var word in sentence.Split())
{
var firstLetter = word.Substring(0, 1);
var restOfWord = word.Substring(1, word.Length - 1);
var currentLetter = vowels.IndexOf(firstLetter, StringComparison.Ordinal);
if (currentLetter == -1)
{
returnSentence += restOfWord + firstLetter + "ay ";
}
else
{
returnSentence += word + "way ";
}
}
returnSentence = returnSentence.TrimEnd();
return returnSentence;
}
The output for the sentence "The Quick Brown Fox Jumped Over The Lazy Dog" will be :
hetay uickqay rownbay oxfay umpedjay veroay hetay azylay ogday

Using the same values in separate if statements in java

I am working on a problem where I have a menu option 1. to shuffle the word, 2 to take the shuffle word and try to fix it by changing the array index numbers.
I did this part if (input==1) shuffle the word.
I now have to take that the same shuffle word in in if (input==2) section and try to fix it. Can anybody guide me how can I use the same values in this block if(input==1)?
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
while (true) {
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
String team;
String mix_word;
char orig_team[];
char mix_team[];
boolean Result;
// System.out.println(input);
if (input == 1) {
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
int arg_length = mix_team.length;
}
if (input == 2) {
}
if (input == 3) {
break;
}
if (input > 3 || input <= 0) {
System.out.println("input accurate numbers 1 or 2 or 3");
}
}
}
static String mix(String Team) {
String word = shuffle(Team);
return word;
}
static String shuffle(String input) {
List<Character> characters = new ArrayList<Character>();
for (char c : input.toCharArray()) {
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while (characters.size() != 0) {
int randPicker = (int) (Math.random() * characters.size());
output.append(characters.remove(randPicker));
}
return output.toString();
}
static String orig()
{
String[] lines = new String[1000];// Enough lines.
int counter = 0;
try {
File file = new File("input.txt");// The path of the File
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
boolean flag = true;
while (true) {
try {
lines[counter] = buffer.readLine();// Store a line in the
// array.
if (lines[counter] == null) {// If there isn't any more
// lines.
buffer.close();
fileReader1.close();
break;// Stop reading and close the readers.
}
counter++;
} catch (Exception ex) {
break;
}
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println("Exception ocurred.");
}
int pick;
Random rand = new Random();
pick = rand.nextInt(counter) + 0;
return (lines[pick]);
}
}
In every loop cycle (which handles a single user input) you declare your variables, so their scope (the access range) is limited to that cycle.
If you declare your variables outside the while-loop, their scope will stretch over the whole loop (until the end of the method):
public static void main(String[] args) {
String team = "";
String mix_word = "";
char orig_team[] = null;
char mix_team[] = null;
boolean Result = false;
while (true) {
// ** your usual input handling here **
}
}
Also be sure to initialize them (e.g. with a default value), or else the program will not compile.
Another way would be to create member- or class-variables, which would have the advantage of automatic initialization and a larger scope.
This is a rather pathological use case of the switch statement but you can take advantage of the drop-through and do the following:
switch(input) {
case 1:
team = orig();
System.out.println(team);
mix_word = mix(team);
System.out.println(mix_word);
orig_team = team.toCharArray();
mix_team = mix_word.toCharArray();
arg_length = mix_team.length;
// No break; here!
case 2:
// do the rest of your thing as if it were case 2
break;
case 3:
break;
default:
System.out.println("input accurate numbers 1 or 2 or 3");
}

Categories