This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am writing a program where it takes a file and tries to use data from the file in order to create an output.
this is the program:
import java.util.Scanner;
import java.io.*;
public class WebberProjectTest
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("portlandvip.txt"));
while (scanner.hasNext())
{
String firstName = scanner.next();
String lastName = scanner.next();
Integer number = scanner.nextInt();
String ticketType = scanner.next();
if(ticketType == "Court")
{
Integer a = 75 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
scanner.nextLine();
}
if(ticketType == "Box")
{
Integer a = 50 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
scanner.nextLine();
}
if(ticketType == "Club")
{
Integer a = 40 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
scanner.nextLine();
}
}
}
}
This is the data file:
Loras Tyrell 5 Club
Margaery Tyrell 8 Box
Roslin Frey 2 Box
Sansa Stark 2 Club
Jon Snow 5 Club
Edmure Tully 3 Box
Joffrey Baratheon 20 Court
Stannis Baratheon 4 Club
Jaime Lannister 2 Box
Cersei Lannister 1 Court
Beric Dondarrion 8 Court
Balon Greyjoy 16 Box
Olenna Tyrell 4 Court
Mace Tyrell 5 Box
Tyrion Lannister 2 Club
Sandor Clegane 2 Court
Gregor Clegane 6 Club
Samwell Tarly 3 Club
Petyr Baelish 6 Court
The purpose of this program is to that the input File and output for example.
Input: Loras Tyrell 5 Court
Output: Loras Tyrell $375.00
However, when i run the program, nothing happens. I have a few ideas on why this is happening, but i dont know how to fix it, any help would be appreciated.
I also have another question about printf statements. I altered the program so that it prints correctly, but now i have to change the println statements to printf statements. this is what i changed the program to look like now:
import java.util.Scanner;
import java.io.*;
public class WebberProjectTest
{
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(new File("portlandvip.txt"));
while(scanner.hasNext())
{
String line = scanner.nextLine();
String[] words = line.split(" ");
if(words[3].equals("Court"))
{
int a = 75 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n ", a);
}
if(words[3].equals("Box"))
{
int a = 50 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n", a);
}
if(words[3].equals("Club"))
{
int a = 40 * Integer.parseInt(words[2]);
System.out.printf(" " + words[0] + " " + words[1] + " $%.2f\n", a);
}
}
}
}
and this is what prints out:
Loras Tyrell Loras Tyrell $java.util.IllegalFormatConversionException: f != java.lang.Integer
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at WebberProjectTest.main(WebberProjectTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I dont know what i did wrong in the printf statement, thank you for any assistance.
Try reading line at once and then split the elements.. Something like this
while(inp.hasNext()) {
String line = inp.nextLine();
String[] words = line.split(" ");
if(words[3].equals("Court")) {
int a = 75 * Integer.parseInt(words[2]);
System.out.println(" " + words[0] + " " + words[1] + " " + a);
}
// ....other if conditions
if(inp.hasNext()) //to skip over empty line
inp.nextLine();
}
Strings should be compared with the equals() method instead of the == operator. e.g.,
ticketType.equals("Court") //instead of ==> ticketType == "Court"
Try this code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext()){
String string = scanner.useDelimiter("\n").next();
if(!string.equals(" ") && !string.equals("\n") && !string.equals("") && !string.equals("\r") ){
StringTokenizer st = new StringTokenizer(string," ");
String firstName = "";
String lastName = "";
Integer number = 0;
String ticketType = "";
while (st.hasMoreElements()) {
firstName = st.nextElement().toString();
lastName = st.nextElement().toString();
number = Integer.parseInt(st.nextElement().toString());
ticketType = st.nextElement().toString().trim();
System.out.println(" " + firstName + " " + lastName + " " + number + " " +ticketType);
}
if(ticketType.equalsIgnoreCase("Court"))
{
Integer a = 75 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
}
else if(ticketType.equalsIgnoreCase("Box"))
{
Integer a = 50 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
}
else if(ticketType.equalsIgnoreCase("Club"))
{
Integer a = 40 * number;
System.out.println(" " + firstName + " " + lastName + " " + a);
}
}//if(!string.equals(" "))
}//while
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
So for this assignment, it asks the user to enter a phone number, then it splits the number up into a category of each set of integers. What I'm attempting to do is to throw a simple exception that if they do not enter the parenthesis for the area code that it throws the exception but doesn't crash the program and asks them to re-enter using the correct format
public class App{
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String inputNum;
String token1[];
String token2[];
String areaCode;
String preFix;
String lineNum;
String fullNum;
System.out.print("Enter a phone number in (123) 123-4567 format: ");
inputNum = input.nextLine();
System.out.println();
token1 = inputNum.split(" ");
areaCode = token1[0].substring(1, 4);
if (token1[0].substring(0, 3) != "()"){
throw new Exception("Enter a phone number in (123) 123-4567 format: ");
}
token2 = token1[1].split("-");
preFix = token2[0];
lineNum = token2[1];
fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
}
}
No need to throw. Just keep asking in a loop.
String areaCode;
String preFix;
String lineNum;
while (true) {
System.out.print("Enter a phone number in (123) 123-4567 format: ");
String inputNum = input.nextLine();
System.out.println();
String [] token1 = inputNum.split(" ");
if (token1.length == 2 && token1[0].length() == 5
&& token1[0].charAt(0) == '(' && token1[0].charAt(4) == ')') {
areaCode = token1[0].substring(1, 4);
String [] token2 = token1[1].split("-");
if (token2.length == 2 && token2[0].length() == 3 && token2[1].length() == 4) {
preFix = token2[0];
lineNum = token2[1];
// If we reach this line all is ok. Exit the loop.
break;
}
}
}
String fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I am extremely new to Java programming and have run into a roadblock for a school assignment. My program works in JGRASP and does not produce any errors. I get all the correct outputs. But when I submit the assignment I get the following error. I can't figure out what is wrong.
A run-time error occurred when running the SpaceTicket program:
java.lang.StringIndexOutOfBoundsException: String index out of range:
-23. Please test your program at home and fix the error before resubmitting. (2 occurrences)
The desired input is supposed to be:
12579500s15300701209817DSpaceX-001 Earth to Mars
Code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Random;
public class SpaceTicket
{
static final double STUDENT_DISCOUNT = 0.25;
static final double CHILD_DISCOUNT = 0.35;
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
String ticketCode = "";
String price = "";
String spaceTicket = "";
double priceParse = 0;
double cost = 0;
int ranNum = 0;
System.out.print("Enter ticket code: ");
ticketCode = userInput.nextLine();
ticketCode = ticketCode.trim();
if (ticketCode.length() < 25) {
System.out.println("*** Invalid ticket code ***");
System.out.println("Ticket code must have at least 25
characters.");
}
else {
price = ticketCode.substring(0, 6);
priceParse = Double.parseDouble(price);
if (ticketCode.charAt(8) == 's') {
cost = priceParse - (priceParse * STUDENT_DISCOUNT);
}
else if (ticketCode.charAt(8) == 'c') {
cost = priceParse - (priceParse * CHILD_DISCOUNT);
}
else {
cost = priceParse;
}
}
spaceTicket = ticketCode.substring(24, ticketCode.length());
System.out.println("Space Ticket: " + spaceTicket);
System.out.println("");
System.out.println("Date: " + ticketCode.substring(13, 15) + "/"
+ ticketCode.substring(15, 17) + "/" + ticketCode.substring(17,
21)
+ " Time: " + ticketCode.substring(9, 11) + ":"
+ ticketCode.substring(11, 13) + " Seat: "
+ ticketCode.substring(21, 24));
DecimalFormat df = new DecimalFormat("$#,##0.00");
priceParse = Double.parseDouble(price);
System.out.println("Price: " + df.format(priceParse)
+ " Category: " + ticketCode.charAt(8)
+ " Cost: " + df.format(cost));
Random generator = new Random();
ranNum = generator.nextInt(999999) + 1;
System.out.print("Prize Number: " + ranNum);
}
}
Your error is based on substring method. Before calling ticketCode.substring method, you control length of the ticketCode. If ticketCode's length is smaller than 24, you take following error:String index out of range: -23
Stop your program if ticketCode.length() < 25
if (ticketCode.length() < 25) {
System.out.println("*** Invalid ticket code ***");
System.out.println("Ticket code must have at least 25
characters.");
return;
}
else the statement
spaceTicket = ticketCode.substring(24, ticketCode.length());
throws the exception
in your case looks like the ticket length is 1 so ticketCode.substring(24,1); is called
I am new to programming, first year college of BSIT and we were tasked to code a SimpleArithmetic where it will ask your name first and after that you will be asked to enter the first and the second integer.
After giving what is asked it must show "Hello (the name that was entered)" then what follows next is the sum, difference, product and the mod of the two integers and lastly it will show "Thank You!".
I tried a lot of codes but I will not run, so can someone help me? I would appreciate it really because I really want to learn how would that happen.
This was my code
public class SimpleArithmetic{
public static void main(String[] args){
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
System.out.print("Enter your name: ");
name = in.next(); // <---- HERE
System.out.printf("\nEnter first integer: ");
System.out.printf("\nEnter second integer: ");
System.out.printf("\nnum 1 + num 2");
System.out.printf("\nnum 1 - num 2");
System.out.printf("\nnum 1 * num 2");
System.out.printf("\nnum 1 % num 2");
System.out.print("Hello \n + name");
System.out.println("num 1" + "+" + "is" + "sum");
System.out.println("num 1" + "-" + "is" + "difference");
System.out.println("num 1" + "*" + "is" + "product");
System.out.println("num 1" + "%" + "is" + "mod");
System.out.print("Thank You!");
}
}
The bold one was the error when I tried to compile the java file
Use the class Scanner as below to read input:
Scanner scanner = new Scanner(System.in); // Init scanner
String name = scanner.nextLine(); // Reads a full line
int a = scanner.nextInt(); // Reads one integer
int b = scanner.nextInt(); // Reads another integer
Check documentation here if you like to know more about the class Scanner.
Basically Scanner is a useful class to read input from a stream (System.in) in that case. From javadoc
A simple text scanner which can parse primitive types and strings
using regular expressions.
The following will work for you...
package com.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SimpleArithmetic{
public static void main(String[] args){
try{
//1: Declare name as symbol
//2: num 1, num 2, sum, difference, product, mod to 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = in.readLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
String str1 = in.readLine();
int number1 = Integer.parseInt(str1);
System.out.printf("\nEnter second integer: ");
String str2 = in.readLine();
int number2 = Integer.parseInt(str2);
System.out.print("Hello \n "+ name);
System.out.println("num 1" + "+" + "is" + (number1 + number2));
System.out.println("num 1" + "-" + "is" + (number1 - number2));
System.out.println("num 1" + "*" + "is" + (number1 * number2));
System.out.println("num 1" + "%" + "is" + (number1 % number2));
System.out.print("Thank You!");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Remove all the double qoutes on variables.
change System.out.print("Hello \n + name"); to
System.out.print("Hello \n + name);
System.out.println("num 1" + "+" + "is" + "sum"); to System.out.println("num 1" + "+" + "is" + sum);
System.out.println("num 1" + "-" + "is" + "difference"); to `System.out.println("num 1" + "-" + "is" + difference);`
System.out.println("num 1" + "*" + "is" + "product"); to System.out.println("num 1" + "*" + "is" + product);
System.out.println("num 1" + "%" + "is" + "mod"); to `System.out.println("num 1" + "%" + "is" + mod);`
Use Scanner and try catch block:
There is no declaration of variables which is listed in assignment comments.
You should have done something similar to this:
import java.util.Scanner;
public class SimpleArithmetic {
int num1 = 0, num2 = 0, sum = 0, difference = 0, product = 0, mod = 0;
String name = null;
Scanner in = null;
public static void main(String[] args) {
SimpleArithmetic sa = new SimpleArithmetic();
try {
sa.doSimpleArithmetic();
} catch (Exception e) {
e.printStackTrace();
}
}
void doSimpleArithmetic() throws Exception {
in = new Scanner(System.in);
System.out.print("Enter your name: ");
name = in.nextLine();
System.out.printf("\nEnter first integer: ");
num1 = Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
num2 = Integer.parseInt(in.nextLine());
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
mod = num1 / num2;
System.out.println("\n" + "Hello " + name + "\n");
System.out.println(num1 + " + " + num2 + " is :" + sum);
System.out.println(num1 + " - " + num2 + " is :" + difference);
System.out.println(num1 + " * " + num2 + " is :" + product);
System.out.println(num1 + " % " + num2 + " is :" + mod);
System.out.println("\n" + "Thank You!");
in.close();
}
}
try {
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine(); // <---- HERE
System.out.printf("\nEnter first integer: ");
int nnum1=Integer.parseInt(in.nextLine());
System.out.printf("\nEnter second integer: ");
int nnum2=Integer.parseInt(in.nextLine());
System.out.println("Hello \n" + name);
System.out.println("num 1" + "+" + "is " + (nnum1 + nnum2));
System.out.println("num 1" + "-" + "is " + (nnum1 - nnum2));
System.out.println("num 1" + "*" + "is " + (nnum1 * nnum2));
System.out.println("num 1" + "%" + "is " + (nnum1 % nnum2));
System.out.print("Thank You!");
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("Please enter valid number");
e.printStackTrace();
}
I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
next();
}
public static void next() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
next3(expression);
}
public static void next3(String expression) {
while (!expression.equals("quit")) {
next2(expression);
next();
}
}
public static void next2(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static boolean QuitFunction(String expression) {
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return false;
}
else {
return true;
}
}
}
Take a look at this code. I think this might help you in the right direction. It's similar to what you have already written except it eliminates the need for method calls in your while loop.
Scanner input = new Scanner(System.in);
while (!input.hasNext("quit")) {
String expression = input.nextLine(); // gets the next line from the Scanner
next2(expression); // process the input
}
// once the value "quit" has been entered, the while loop terminates
System.out.println("Goodbye");
Writing it this way drastically cleans up your code and prevents a new declaration of Scanner kb = new Scanner(System.in); each time an input is processed.
I need help, obviously. Our assignment is to retrieve a file and categorize it and display it in another file. Last name first name then grade. I am having trouble with getting a loop going because of the error "java.util.NoSuchElementException" This only happens when I change the currently existing while I loop I have. I also have a problem of displaying the result. The result I display is all in one line, which I can't let happen. We are not allowed to use arraylist, just Bufferedreader, scanner, and what i already have. Here is my code so far:
import java.util.;
import java.util.StringTokenizer;
import java.io.;
import javax.swing.*;
import java.text.DecimalFormat;
/*************************************
Program Name: Grade
Name: Dennis Liang
Due Date: 3/31/11
Program Description: Write a program
which reads from a file a list of
students with their Grade. Also display
last name, first name, then grade.
************************************/
import java.util.*;
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;
class Grade {
public static void main(String [] args)throws IOException {
//declaring
String line = "";
StringTokenizer st;
String delim = " \t\n\r,-";
String token;
String firstname;
String lastname;
String grade;
String S69andbelow="Students with 69 or below\n";
String S70to79 ="Students with 70 to 79\n";
String S80to89= "Students with 80 to 89\n";
String S90to100= "Students with 90 to 100\n";
int gradeint;
double gradeavg = 0;
int count = 0;
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream finput = new FileInputStream(inputFile);
FileOutputStream foutput = new FileOutputStream(outputFile);
FileReader reader = new FileReader(inputFile);
BufferedReader in = new BufferedReader(reader);
Scanner std = new Scanner(new File("input.txt"));
Scanner scanner = new Scanner(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
Scanner scan = new Scanner(S69andbelow);
//reading linev
line = scanner.nextLine();
st = new StringTokenizer(line, delim);
//avoiding selected characters
try {
while(st.hasMoreTokens()) {
firstname = st.nextToken();
lastname = st.nextToken();
grade = st.nextToken();
//storing tokens into their properties
gradeint = Integer.parseInt(grade);
//converting token to int
gradeavg = gradeavg + gradeint;
//calculating avg
count++;
//recording number of entries
if (gradeint <=69) {
S69andbelow = S69andbelow + lastname + " "
+ firstname + " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 70 && gradeint <= 79) {
S70to79 = S70to79 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 80 && gradeint <=89) {
S80to89 = S80to89 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else {
S90to100 = S90to100 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
}//end while
System.out.println(S69andbelow + "\n" + S70to79 + "\n"
+ S80to89 + "\n" + S90to100);
//caterorizing the grades
gradeavg = gradeavg / count;
//calculating average
DecimalFormat df = new DecimalFormat("#0.00");
out.write("The average grade is: "
+ df.format(gradeavg));
System.out.println("The average grade is: "
+ df.format(gradeavg));
Writer output = null;
output = new BufferedWriter(new FileWriter(outputFile));
// scanner.nextLine(S69andbelow);
//output.write(S69andbelow + "\n" + S70to79 + "\n"
// + S80to89 + "\n" + S90to100);
// output.close();
}
catch( Exception e ) {
System.out.println(e.toString() );
}
// Close the stream
try {
if(std != null )
std.close( );
}
catch( Exception e ) {
System.out.println(e.toString());
}
}
}
my input file looks like this:
Bill Clinton 85 (enter)
Al Gore 100 (enter)
George Bush 95 (enter)
Hillery Clinton 83(enter)
John McCain 72(enter)
Danna Green 87(enter)
Steve Delaney 76(enter)
John Smith(enter)
Beth Bills 60(enter)
It would help to point things out just in case I don't follow you all the way through.
An easy way of finding a problem in this would be to comment out most of the code and find out each step at a time. So start with being able to read the file. Then print to the screen. Then print the organized data to the screen. Finally print the organized data to the file.
This should be a fairly simple