Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was curious if anyone could help me understand what I'm doing wrong. I'm just learning how to use OutputStreams and BufferedWriters in Java and I'm not sure I'm doing it right. I know how to use one OutputStream and BufferedWriter but my problem is trying to use two of them in one class.
Right now the main errors I'm getting lies in my LowerAndUpper class and is between my try/catch statements and in my if/else statements and I'm not sure what I'm doing wrong. So I'd appreciate any help you guys could give on the matter and in helping me understand how to use two of these items at once.
These are the errors I'm getting and since I'm still a beginner with Java in general I don't exactly understand what's going on here:
line 40 error: ')' expected
if (creditsEarned>60 writerUpper.write){
line 40 error: not a statement
if (creditsEarned>60 writerUpper.write){
line 40 error: ';' expected
if (creditsEarned>60 writerUpper.write){
line 43 error: 'else' without 'if'
else (writerLower.write){
line 43 error: not a statement
else (writerLower.write){
line 43 error: ';' expected
else (writerLower.write){
Here is my code:
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LowerAndUpper {
public static void main(String[] args) {
Path file1 =
Paths.get("C:/temp/lowerclassman.txt");
Path file2 =
Paths.get("C:/temp/upperclassman.txt");
String s = "";
String delimiter = ",";
int id;
String name;
double creditsEarned;
final int QUIT = 999;
try {
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file1));
BufferedWriter writerUpper = new BufferedWriter(new OutputStreamWriter(output));
OutputStream output2 = new BufferedOutputStream(Files.newOutputStream(file2));
BufferedWriter writerLower = new BufferedWriter(new OutputStreamWriter(output2));
while (true) {
id = Validate.collectInt("Enter student ID number or " + QUIT
+ " to quit >> ");
if (id == QUIT) {
break;
}
name = Validate.collectString(2, "Enter student name "
+ id + " >> ");
creditsEarned = Validate.collectWage("Enter credit hours >> ");
s = id + delimiter + name + delimiter + creditsEarned;
if (creditsEarned>60 writerUpper.write){
System.out.println("Student is a Lowerclassman");
else (writerLower.write){
System.out.println("Student is an Upperclassman");
}
}
writerUpper.write(s, 0, s.length());
r.newLine();
} //end while
writer.close();
writer2.close();
} catch (Exception e) {
System.out.println("Message: " + e);
}
}
}
// **************************************************************************
class Validate {
public static int collectInt(String messageIn) {
Scanner input = new Scanner(System.in);
int intOut = 0;
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
intOut = input.nextInt();
valid = false;
} catch (InputMismatchException ie) {
input.nextLine();
System.out.println("You must enter a whole number");
} //end catch
} //end while
return intOut;
}//end collectInt method
//*************************************************************************
public static String collectString(int strLen, String messageIn) {
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
if (strOut.length() < strLen) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("You must be at least %s characters\n",
strLen);
} //end catch
} //end while
return strOut;
} //end collectString method
//*************************************************************************
public static String collectZipcode(String messageIn) {
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
Integer.parseInt(strOut);
if (strOut.length() != 5) {
throw new Exception();
}
valid = false;
} catch (NumberFormatException ne) {
System.out.println("Please enter a valid zip code");
} catch (Exception e) {
System.out.printf("A zip code should be 5 numbers long");
} //end catch
} //end while
return strOut;
}//end collectZipcode method
//*************************************************************************
public static String collectEmail(String messageIn) {
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence emailChk = strOut;
Matcher matcher = pattern.matcher(emailChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid email "
+ "address\n");
} //end catch
} //end while
return strOut;
}//end collectEmail method
//*************************************************************************
public static Double collectWage(String messageIn) {
Scanner input = new Scanner(System.in);
double dblOut = 0;
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
dblOut = input.nextDouble();
valid = false;
} catch (InputMismatchException ie) {
input.nextLine();
System.out.println("You must enter a whole number ");
} //end catch
} //end while
return dblOut;
}//end collectInt method
//*************************************************************************
public static String collectPhone(String messageIn) {
String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence phoneChk = strOut;
Matcher matcher = pattern.matcher(phoneChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid phone "
+ "number\n");
} //end catch
} //end while
return strOut;
}//end collectPhone method
//*************************************************************************
public static String collectSsn(String messageIn) {
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence ssnChk = strOut;
Matcher matcher = pattern.matcher(ssnChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid social security "
+ "number\n");
} //end catch
} //end while
return strOut;
}//end collectSsn
} //end Validate Class
Thanks in advance for all your help.
Firstly, you have initialised:
BufferedWriter writerUpper = new BufferedWriter(new OutputStreamWriter(output));
But then used two other varible names:
writer.close();
And:
r.newLine();
Correct usage of BufferedWriter can be found in this documentation:http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
As for the if and else statements, make sure you format your code correctly. General usage of an if statement is to have a condition:
if(condition)
{
//do something
}
else
{
//do something else
}
Ie for your circumstance:
if (creditsEarned>60 writerUpper.write){
System.out.println("Student is a Lowerclassman");
else (writerLower.write){
System.out.println("Student is an Upperclassman");
}
}
Should be:
if (creditsEarned> 60){
writerUpper.write(s, 0, s.length());
writerUpper.newLine();
}
else
{
writerLower.write(s, 0, s.length());
writerLower.newLine();
}
And then make sure you use the same variable names as you initialised:
writerLower.close();
writerUppder.close();
Related
Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.
So I've recently learned exception handling for Java and I'm still trying to get used to it and all but I feel like I'm missing something. I was doing an assignment for my class and the compiler doesn't like my code.
I'm supposed to be making a Calculator that takes in an operator and then a number, and if the operator (+, -, *, /) given is not one of the aforementioned four, then an exception is thrown.
I used try-catch but for some reason the try and catch aren't recognizing each other unless I place them next to each other which isn't really what I want.
My question is really: Is there a way for my try and catch to recognize each other without being right next to each other, so I can run code in-between them? Or is that impossible and I'm doing it all wrong?
Here's my code so far:
import java.util.*;
public class Calculator
{
public static void main(String[] args)
{
String operatorInput;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}
numberInput = input.nextDouble();
if(operatorInput.compareTo("+")==0)
{
result += numberInput;
} else if(operatorInput.compareTo("-")==0)
{
result -= numberInput;
} else if(operatorInput.compareTo("*")==0)
{
result = result * numberInput;
} else
{
result = result / numberInput;
}
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
}
}
}
And here's the exception class I made:
public class UnknownOperatorException extends Exception
{
public UnknownOperatorException()
{
super("Please select an actual operator and try again: ");
}
public UnknownOperatorException(String message)
{
super(message);
}
}
They have to be next to each other. There's a few things you could do:
Move the } at the commented line down a ways, like this
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}//this one here
Take that and move it to here
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
}// put it here
Then take these two lines
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
And move them below the catch:
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
}
}
That will let your while loop still sort of function and make your try/catch work. You might need to tweak things a bit to make them work right though
In order for try/catch to work, as Ghost says in a comment, you will need to put them next to each other.
And the code above has some problems...
maybe this works.
public static void main(String[] args) {
String operatorInput=null;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while ((userRedo.toUpperCase()).compareTo("Y") == 0) {
try {
operatorInput = input.nextLine().trim();
if (operatorInput.compareTo("+") != 0
&& operatorInput.compareTo("-") != 0
&& operatorInput.compareTo("*") != 0
&& operatorInput.compareTo("/") != 0) {
throw new UnknownOperatorException("Unknown operator!");
}
} catch (UnknownOperatorException e) {
System.out.println(e.getMessage());
continue;
}
numberInput = Double.parseDouble(input.nextLine());
if (operatorInput.compareTo("+") == 0) {
result += numberInput;
} else if (operatorInput.compareTo("-") == 0) {
result -= numberInput;
} else if (operatorInput.compareTo("*") == 0) {
result = result * numberInput;
} else {
result = result / numberInput;
}
System.out.println("\nresult " + operatorInput + " " + numberInput + "= ");
System.out.println("Updated result: " + result);
System.out.print("Again? (y/n) : ");
userRedo = input.nextLine();
}
input.close();
}
public class Building implements CarbonFootprint {
//implement 4a
void getCarbonFootprint(){
System.out.println("Kim Byers, CSIS 505, Exception Handling, Assignment1");
//Building display
double Bill;
}
//class variables
double monthlyElectricBill;
double monthlyGasBill;
//constructor
public void Building(double monthlyElectricBill, double monthlyGasBill) {
monthlyElectricBill = ([monthyly Electric Billmonth;
monthlyGasBill = monthlyGasBill;
//Constructor
//set method statements
}
So, I was looking for an efficient way, using Java's standard packages, to read an input integer... For example, I came across the class "Scanner", but I found two main difficulties:
if I don't insert an int, I'm not actually able to solve the exception;
this class works with tokens, but my aim is to load the string in its full length.
This is an example of execution I would like to realize:
Integer: eight
Input error - Invalid value for an int.
Reinsert: 8 secondtoken
Input error - Invalid value for an int.
Reinsert: 8
8 + 7 = 15
And this is the (incorrect) code I tried to implement:
import java.util.Scanner;
import java.util.InputMismatchException;
class ReadInt{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = in.nextInt();
} catch (InputMismatchException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
Use a BufferedReader. Check NumberFormatException. Otherwise very similar to what you have. Like so ...
import java.io.*;
public class ReadInt{
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = Integer.parseInt(in.readLine());
} catch (NumberFormatException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
To use with tokens:
int i = Integer.parseInt(in.next());
Then you could do:
int i;
while (true) {
System.out.print("Enter a number: ");
try {
i = Integer.parseInt(in.next());
break;
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
}
//do stuff with i
That above code works with tokens.
I need help figuring out how to loop my IOException (in where I ask for a filename until a valid one is entered). I need a loop that somehow recognizes that an invalid file was entered and am unsure how to do this.
import java.util.*;
import java.io.*;
public class JavaGradedLab {
public static void main(String[] args) throws IOException {
Scanner inScan, fScan = null;
int [] A = new int[5];
inScan = new Scanner(System.in);
System.out.println("Please enter the file to read from: ");
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
String nextItem;
int nextInt = 0;
int i = 0;
while (fScan.hasNextLine())
{
nextItem = fScan.nextLine();
nextInt = Integer.parseInt(nextItem);
A[i] = nextInt;
i++;
}
System.out.println("Here are your " + i + " items:");
for (int j = 0; j < i; j++)
{
System.out.println(A[j] + " ");
}
}
}
Well, there's sure to be someone explaining how to make your code better via best practices etc., but as a very basic answer which in itself can probably be improved (assuming that your code works when the input is valid):
while(true) {
try{
String fName = inScan.nextLine();
fScan = new Scanner(new File(fName));
break;
}
catch (FileNotFoundException ex)
{
System.out.println("Your file is invalid -- please re-enter");
}
}
I'm trying to use args[0] as an input file, but when I run the program, I keep getting an IndexOutOfBoundsException, although I'm quite sure that args[0] is the correct argument. I ran into this problem with my last program as well, but I can't figure out what I'm doing wrong.
Code:
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class SortTest {
public static void main(String args[]) throws FileNotFoundException {
try {
Scanner read = new Scanner(new File(args[0]));
while (read.hasNextLine()) {
String name = read.nextLine();
read.nextLine();
String line1 = read.nextLine();
int sh = Integer.parseInt(line1.substring(0,2));
int sm = Integer.parseInt(line1.substring(3));
read.nextLine();
String line2 = read.nextLine();
int fh = Integer.parseInt(line2.substring(0,2));
int fm = Integer.parseInt(line2.substring(3));
if (fh<sh) {
System.out.println("Times not in correct order.");
return;
} else if (fh==sh) {
if (fm<sm) {
System.out.println("Times not in correct order.");
return;
}
} else {
System.out.println(name + "\n" + sh + ":" + sm + "\n" + fh + ":" + fm);
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println("Invalid file path.");
}
catch (NoSuchElementException n) {
System.out.println("No readable text in file.");
}
catch (IndexOutOfBoundsException x) {
System.out.println("Proper format is java LectureSortTest <input>");
}
catch (NumberFormatException num) {
System.out.println("File contents not formatted correctly");
}
}
}