This question already has answers here:
PrintWriter append method not appending
(5 answers)
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I need HELP. I tried to separate the valid serial keys from invalid ones. I got the output correctly. but then when i tried to write it in a file, ONLY the last line is being written.
the output is:
1A000000
1A000001
1A000002
1A000003
1A000004
1A000005
2B200012
3C343455
4D342423
5E324344
6F435435
7G245347
and I want to write this to a file. But ONLY 7G245347 is being written.
import java.util.*;`
import java.io.*;
public class ValidSerialKey {
public static void main(String[] args) throws IOException {
String keys = "";
File file = new File("serialkeys.txt");
try{
Scanner scan = new Scanner(file);
while (scan.hasNext()){
keys = scan.nextLine();
if ((keys.charAt(0) == '1' || keys.charAt(0) == '2' || keys.charAt(0) == '3' || keys.charAt(0) == '4' || keys.charAt(0) == '5' ||
keys.charAt(0) == '6' || keys.charAt(0) == '7' || keys.charAt(0) == '8' || keys.charAt(0) == '9' ) &&
(keys.charAt(1) == 'A' || keys.charAt(1) == 'B' || keys.charAt(1) == 'C' || keys.charAt(1) == 'D' || keys.charAt(1) == 'E' ||
keys.charAt(1) == 'F' || keys.charAt(1) == 'G' || keys.charAt(1) == 'H' || keys.charAt(1) == 'I' || keys.charAt(1) == 'J' ||
keys.charAt(1) == 'K' || keys.charAt(1) == 'L' || keys.charAt(1) == 'M' || keys.charAt(1) == 'N' || keys.charAt(1) == 'O' ||
keys.charAt(1) == 'P' || keys.charAt(1) == 'Q' || keys.charAt(1) == 'R' || keys.charAt(1) == 'S' || keys.charAt(1) == 'T' ||
keys.charAt(1) == 'U' || keys.charAt(1) == 'V' || keys.charAt(1) == 'W' || keys.charAt(1) == 'X' || keys.charAt(1) == 'Y' ||
keys.charAt(1) == 'Z' )){
System.out.println(keys);
File filein = new File("ValidKeys.txt");
try{
try
(PrintWriter pw = new PrintWriter(filein)){
pw.print(keys);
pw.close();
}
}catch (FileNotFoundException ex){
System.out.println(ex.getMessage());
}
}//end of if
}//end of while
scan.close();
}catch (FileNotFoundException exp){
System.out.println(exp.getMessage());
}
}
}
You want to keep the PrintWriter opened to write other things during the next iterations of the loop
So don't create a new one at each iteration.
As a side note, you don't need to close explicitly the PrintWriter instance when you use try with resources.
You should replace this logic :
loop
try
(PrintWriter pw = new PrintWriter(uniqueFile)){
pw.print(keys);
}//end of inner try
end loop
by a logic where you include the whole logic in the try with resources statement :
try(PrintWriter pw = new PrintWriter(uniqueFile)){
loop
pw.print(keys);
end loop
}
catch (IOException e){
... // exception handling
}
Related
This question already has answers here:
PrintWriter append method not appending
(5 answers)
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I need HELP. I tried to separate the valid serial keys from invalid ones. I got the output correctly. but then when i tried to write it in a file, ONLY the last line is being written.
the output is:
1A000000
1A000001
1A000002
1A000003
1A000004
1A000005
2B200012
3C343455
4D342423
5E324344
6F435435
7G245347
and I want to write this to a file. But ONLY 7G245347 is being written.
import java.util.*;`
import java.io.*;
public class ValidSerialKey {
public static void main(String[] args) throws IOException {
String keys = "";
File file = new File("serialkeys.txt");
try{
Scanner scan = new Scanner(file);
while (scan.hasNext()){
keys = scan.nextLine();
if ((keys.charAt(0) == '1' || keys.charAt(0) == '2' || keys.charAt(0) == '3' || keys.charAt(0) == '4' || keys.charAt(0) == '5' ||
keys.charAt(0) == '6' || keys.charAt(0) == '7' || keys.charAt(0) == '8' || keys.charAt(0) == '9' ) &&
(keys.charAt(1) == 'A' || keys.charAt(1) == 'B' || keys.charAt(1) == 'C' || keys.charAt(1) == 'D' || keys.charAt(1) == 'E' ||
keys.charAt(1) == 'F' || keys.charAt(1) == 'G' || keys.charAt(1) == 'H' || keys.charAt(1) == 'I' || keys.charAt(1) == 'J' ||
keys.charAt(1) == 'K' || keys.charAt(1) == 'L' || keys.charAt(1) == 'M' || keys.charAt(1) == 'N' || keys.charAt(1) == 'O' ||
keys.charAt(1) == 'P' || keys.charAt(1) == 'Q' || keys.charAt(1) == 'R' || keys.charAt(1) == 'S' || keys.charAt(1) == 'T' ||
keys.charAt(1) == 'U' || keys.charAt(1) == 'V' || keys.charAt(1) == 'W' || keys.charAt(1) == 'X' || keys.charAt(1) == 'Y' ||
keys.charAt(1) == 'Z' )){
System.out.println(keys);
File filein = new File("ValidKeys.txt");
try{
try
(PrintWriter pw = new PrintWriter(filein)){
pw.print(keys);
pw.close();
}
}catch (FileNotFoundException ex){
System.out.println(ex.getMessage());
}
}//end of if
}//end of while
scan.close();
}catch (FileNotFoundException exp){
System.out.println(exp.getMessage());
}
}
}
You want to keep the PrintWriter opened to write other things during the next iterations of the loop
So don't create a new one at each iteration.
As a side note, you don't need to close explicitly the PrintWriter instance when you use try with resources.
You should replace this logic :
loop
try
(PrintWriter pw = new PrintWriter(uniqueFile)){
pw.print(keys);
}//end of inner try
end loop
by a logic where you include the whole logic in the try with resources statement :
try(PrintWriter pw = new PrintWriter(uniqueFile)){
loop
pw.print(keys);
end loop
}
catch (IOException e){
... // exception handling
}
This is quite a beginner question but I'm wondering why my do...while loop is not closing.
The program is supposed to loop while the user input is not 'C', 'c', 'F', or 'f'.
It seems to close when just one boolean expression in the while section is valid but not if multiple are valid.
public class CelsToFaren
{
public static void main(String[] args)
{
// scanner setup
Scanner sc = new Scanner(System.in);
// Variable declarations
int celsius;
int answerC;
int farenheit;
int answerF;
char userLetter;
do
{
// initial menu options
System.out.println("Which temperature would you like to convert from? ");
System.out.println(" >(C)elsius ");
System.out.println(" >(F)arenheit ");
// user input of C, c, F, or f to select option
userLetter = sc.next().charAt(0);
// if user input C or c
if ((userLetter == 'C' || userLetter == 'c'))
{
System.out.print("Please enter the temperature: ");
celsius = sc.nextInt();
answerC = ((celsius*9/5)+32);
System.out.println("The answer is: " + answerC + " Farenheit ");
}
else
{
// if user input F or f
if ((userLetter == 'F' || userLetter == 'f'))
{
System.out.print("Please enter the temperature: ");
farenheit = sc.nextInt();
answerF = ((farenheit-32)*5/9);
System.out.println("The answer is: " + answerF + " Celsius ");
}
else
{
// if user input not F, f, C, or c
if ((userLetter != 'F' || userLetter != 'f' || userLetter != 'C' || userLetter != 'c'));
{
System.out.println("Please enter a valid option");
}
}
}
} while ((userLetter != 'c') || (userLetter != 'C') || (userLetter != 'f') || (userLetter != 'F'));
}
}
You need to change the exit logic.
In your case 1 | 0 | 0 = true so the loop continues.
You need to change it to:
while ((userLetter != 'c') && (userLetter != 'C') && (userLetter != 'f') && (userLetter != 'F'));
Your condition is wrong. Lets assume you want to break loop in if statement. It would look like
if(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F')
Now let's apply negation to get a condition under which you do not need to exit the loop
if(!(userLetter == 'c' || userLetter == 'C' || userLetter == 'f' || userLetter == 'F'))
this condition is simillar to
if(userLetter != 'c' && userLetter != 'C' && userLetter != 'f' && userLetter != 'F')
This question already has answers here:
Scanner NoSuchElementException when calling .next() method
(3 answers)
Closed 5 years ago.
if (charIte.next()=='{' || charIte.next()=='}'
|| charIte.next()=='[' || charIte.next()==']'
|| charIte.next()=='(' || charIte.next()==')'
|| charIte.next()=='*' || charIte.next()=='"'
|| charIte.next()=='/'){
}
The program returns:
Exception in thread "main" java.util.NoSuchElementException at line
|| charIte.next()=='(' || charIte.next()==')'
What is the problem?
Each invocation of next() consumes one token. Call it once, and save and then compare with the result. Like,
char ch = charIte.next();
if (ch == '{' || ch == '}' || ch == '[' || ch == ']' || ch == '('
|| ch == ')' || ch == '*' || ch == '"' || ch == '/') {
// ...
}
Each time you do charIte.next() you're asking to read the next token.
I think what you should do to ischar ite = charIte.next.chartAt(0) and then use ite in your if statement
if (ite next()=='{' || next()=='}'
|| ite.next()=='[' || ite.next()==']'
|| ite.next()=='(' || ite.next()==')'
|| ite.next()=='*' || ite.next()=='"'
|| ite.next()=='/'){
Info on Scanner
I'm writing a program converts letters in a phone number into their corresponding digits, and it's almost complete aside from some formatting:
import java.util.Scanner;
public class PhoneKeypad
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
String number;
int currentChar;
char character;
int finalNumber;
int getNumber;
int start;
String end;
currentChar = 0;
do
{
System.out.print ("\nEnter a phone number with letters: ");
number = scan.nextLine();
number = number.toUpperCase();
while (currentChar < number.length())
{
character = number.charAt(currentChar);
finalNumber = getNumber(character);
System.out.print (finalNumber);
currentChar++;
}
System.out.print ("\n\nContinue? <y/n> ");
end = scan.next();
System.out.flush();
scan.nextLine();
currentChar = 0;
} while (!end.equalsIgnoreCase("n"));
}
public static int getNumber (char uppercaseLetter)
{
int resultChar = 0;
if (Character.isLetter(uppercaseLetter))
{
if (uppercaseLetter == 'A' || uppercaseLetter == 'B' || uppercaseLetter == 'C')
resultChar = 2;
else if (uppercaseLetter == 'D' || uppercaseLetter == 'E' || uppercaseLetter == 'F')
resultChar = 3;
else if (uppercaseLetter == 'G' || uppercaseLetter == 'H' || uppercaseLetter == 'I')
resultChar = 4;
else if (uppercaseLetter == 'J' || uppercaseLetter == 'K' || uppercaseLetter == 'L')
resultChar = 5;
else if (uppercaseLetter == 'M' || uppercaseLetter == 'N' || uppercaseLetter == 'O')
resultChar = 6;
else if (uppercaseLetter == 'P' || uppercaseLetter == 'Q' || uppercaseLetter == 'R' || uppercaseLetter == 'S')
resultChar = 7;
else if (uppercaseLetter == 'T' || uppercaseLetter == 'U' || uppercaseLetter == 'V')
resultChar = 8;
else if (uppercaseLetter == 'W' || uppercaseLetter == 'X' || uppercaseLetter == 'Y' || uppercaseLetter == 'Z')
resultChar = 9;
}
else if (Character.isDigit(uppercaseLetter))
{
resultChar = Character.getNumericValue(uppercaseLetter);
}
return resultChar;
}
}
The issue I'm having is that I need to print the phone number back out exactly as the user entered it, aside the the letters. If the user enters 1-800-flowers, the program needs to print it back out as 1-800-3569377. It's the same for any special characters - hyphens, spaces, parenthesis, etc.
And the simpler the solution, the better, as I haven't yet gotten to arrays or anything more complicated than methods.
So I have a really annoying problem which I am hoping one of you could help solve for me. This is a really simple program that prints my COMP science username in asterisks. I have attached a choice for the user - to either print the username in asterisks or simply print the characters.
I have constructed a while loop that validates the data entered by the user is accurate. The conditions for this while loop are never met - so it always loops through it no matter what is entered. I'm sure this is a really simple problem, just haven't really used chars before so can't figure out what I am doing wrong.
//===================================================== START OF MAIN
public static void main (String [] args){
Scanner input = new Scanner(System.in); // Scanner for users input
char usersChoice = 0; // Variable for users input
System.out.println("\nWould you like to see the large letters or the small letters?\n (Enter L for large, S for small!!)\n");
usersChoice = input.next().charAt(0); // Users Input
System.out.println(usersChoice);
//================================================= WHILE LOOP TO CHECK AUTHENTICITY OF DATA
while (usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || usersChoice != 'S'){
System.out.println("\nWrong Input - Please try again!!!\n");
usersChoice = input.next().charAt(0);
System.out.println(usersChoice);
}//end of while
//================================================= IF (CHAR = L) PRINT BIG LETTERS
if (usersChoice == 'L' || usersChoice == 'l'){
printU();
print4();
printJ();
printA();
}//end of if
//================================================= ELSE PRINT LETTERS
else{
System.out.println("\nU");
System.out.println("4\n");
System.out.println("J\n");
System.out.println("A\n");
}//end of else
}//end of main
The while statement expression is always true since not all expressions can be true at once - you need the conditional && operator
while (usersChoice != 'l' && usersChoice != 'L' && usersChoice != 's' && usersChoice != 'S') {
Your logical or(s) should be logical and(s), this
while (usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' ||
usersChoice != 'S')
Should be
while (usersChoice != 'l' && usersChoice != 'L' && usersChoice != 's' &&
usersChoice != 'S')
The problem with your while loop is there is no character that could meet the conditions. Consider lower case l, when the usersChoice is l it's not L so it wouldn't finish.
while (!(usersChoice != 'l' || usersChoice != 'L' || usersChoice != 's' || usersChoice != 'S'))
Just add an exclamation mark before your while-loop.
Your while-loop always do not work because:
if userChoice is 'l', it is not 'L'/'s'/'S' (expression is true)
if userChoice is 'L', it is not 'l'/'s'/'S' (expression is true)
if userChoice is 's', it is not 'l'/'L'/'S' (expression is true)
if userChoice is 'S', it is not 'l'/'L'/'s' (expression is true)
Your while-loop always evaluates to true