Exception in thread "main" java.util.NoSuchElementException in if statem [duplicate] - java

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

Related

How to write data to a file and see the data in the file [duplicate]

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
}

Check if an character is an operator [duplicate]

This question already has answers here:
If statement, compare one variable to multiple [duplicate]
(6 answers)
Is there a simpler way to check multiple values against one value in an if-statement? [duplicate]
(12 answers)
Comparing chars in Java
(13 answers)
is it possible to check if a char matches a list of possibilities?
(4 answers)
How can I compare char characters?
(1 answer)
Closed 4 years ago.
I want to check if a character is an operator like : %,/,*,+,-
This is the code to get input from the user in the main function:
Scanner input = new Scanner(System.in);
System.out.println("Operator (S is stoppen)");
String operator = input.nextLine();
char o = operator.charAt(0);
So the input is stored in the variabele 'o'
So now I tried to make a new function to check if the character is one of these functions: %,/,*,+,-
this is the function I tried to make:
static boolean isGeldigeOperator(char o) {
if (o == '%' || '/' || '*' || '+' || '-'){
return true;
} else{
return false;
}
So if o == one of the operators return true and if not return false.
Now the error that I'm getting is about this line:
if (o == '%' || '/' || '*' || '+' || '-'){
Its this error: Operator || cannot be applied to 'boolean', 'char'
Does anyone know what I'm doing wrong?
This line:
if (o == '%' || '/' || '*' || '+' || '-'){
should be:
if (o == '%' || o == '/' || o == '*' || o == '+' || o == '-'){

Checking a string for invalid characters

I am trying to write a program that takes a string as input.
This string must be an equation with only brackets, operations or digit.
The code I posted below is what I came up with, but when I run it, anything I enter is apparently an invalid string. Can someone please tell what I did wrong?
System.out.println("Enter a string");
String str = s.nextLine(); //s is a Scanner object
int n = str.length();
for(int i = 0; i < n; i++) {
if( !Character.isDigit(str.charAt(i)) || str.charAt(i) != '+'
|| str.charAt(i) != '-' || str.charAt(i) != '*'
|| str.charAt(i) != '/' || str.charAt(i) != '('
|| str.charAt(i) != ')' || str.charAt(i) != '['
|| str.charAt(i) != ']' || str.charAt(i) != '{'
|| str.charAt(i) != '}') {
System.out.println("invalid string, try again: ");
str = s.nextLine();
}
...}
As suggested in the comments, switch || for &&:
if( !Character.isDigit(str.charAt(i)) && str.charAt(i) != '+'
&& str.charAt(i) != '-' && str.charAt(i) != '*'
&& str.charAt(i) != '/' && str.charAt(i) != '('
&& str.charAt(i) != ')' && str.charAt(i) != '['
&& str.charAt(i) != ']' && str.charAt(i) != '{'
&& str.charAt(i) != '}') {
System.out.println("invalid string, try again: ");
str = s.nextLine();
}
Or, to make your code easier to understand:
final String validChars = "0123456789+-*/()[]{}";
for(int i = 0; i < n; i++) {
if(!validChars.contains(str.charAt(i))) {
System.out.println("invalid string, try again: ");
str = s.nextLine();
// potential bug here - i and n are not being reset
}
}
Note: You have a bug where you don't reset the i index or the n length when reading a new line from the scanner in the case where your previous line contained an invalid character (see comment in code above).
if you dont want change all of your code you can that :
System.out.println("Enter a string");
String str = s.nextLine(); // s is a Scanner object
int n = str.length();
if (n > 0) {
for (int i = 0; i < n; i++) {
if (!(Character.isDigit(str.charAt(i)) || str.charAt(i) == '+' || str.charAt(i) == '-'
|| str.charAt(i) == '*' || str.charAt(i) == '/' || str.charAt(i) == '(' || str.charAt(i) == ')'
|| str.charAt(i) == '[' || str.charAt(i) == ']' || str.charAt(i) == '{'
|| str.charAt(i) == '}')) {
System.out.println("invalid string, try again: ");
str = s.nextLine();
n = str.length();
i = -1;//reset i for the new line ( set at -1 for the next i++ of the next loop )
}
}
} else {
System.out.println("empty string ");
}
package hello;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class Characts {
#Test
public void testSwitch () {
assertTrue(isValid("123+321*"));
assertFalse(isValid("A123+321*"));
assertTrue(isValid("123+321*\n")); // don't forget returns and line feeds
}
private boolean isValid(String str) {
for (int i = 0 ; i < str.length(); i++) {
char s = str.charAt(i);
if (Character.isDigit(s)) {
continue;
} else {
switch (s) {
case '+' :
case '-' :
case '*' :
case '/' :
case '(' :
case ')' :
case '[' :
case ']' :
case '{' :
case '}' :
continue;
}
return false;
}
}
return true;
}
}

Only last line is being written into a file [duplicate]

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
}

Multiple || statements in one if statement

I'm trying to have my program check the name that the player enters to see if it uses any invalid characters. It seems to make sense in my mind how to make it work, but it seems not to work in the actual environment. When I run it, and I use invalid characters then it will just go on to the next part of the program. Any Ideas on how to fix it?
Here is my relevant code block:
if (!(nameInput.getText().equals(""))) {
boolean allow = true;
String check = nameInput.getText();
for (int i = 0;i>check.length();i++) {
if (check.charAt(i) == '`' || check.charAt(i) == '~' ||
check.charAt(i) == '!' || check.charAt(i) == '#' ||
check.charAt(i) == '#' || check.charAt(i) == '$' ||
check.charAt(i) == '%' || check.charAt(i) == '^' ||
check.charAt(i) == '&' || check.charAt(i) == '*' ||
check.charAt(i) == '(' || check.charAt(i) == ')' ||
check.charAt(i) == '_' || check.charAt(i) == '+' ||
check.charAt(i) == '=' || check.charAt(i) == '[' ||
check.charAt(i) == ']' || check.charAt(i) == '{' ||
check.charAt(i) == '}' || check.charAt(i) == ';' ||
check.charAt(i) == '\''|| check.charAt(i) == ':' ||
check.charAt(i) == '"' || check.charAt(i) == '<' ||
check.charAt(i) == '>' || check.charAt(i) == '?' ||
check.charAt(i) == ',' || check.charAt(i) == '.' ||
check.charAt(i) == '/' || check.charAt(i) == '\\'||
check.charAt(i) == '|' || check.charAt(i) == '1' ||
check.charAt(i) == '2' || check.charAt(i) == '3' ||
check.charAt(i) == '4' || check.charAt(i) == '5' ||
check.charAt(i) == '6' || check.charAt(i) == '7' ||
check.charAt(i) == '8' || check.charAt(i) == '9' ||
check.charAt(i) == '0') {
allow = false;
}
}
if (allow == true) {
player = new Player(check);
window.refresh();
mainMenu();
} else {
JOptionPane.showMessageDialog(window, "Invalid Name(Uses invalid Characters","Invalid!", JOptionPane.OK_OPTION);
}
} else {
JOptionPane.showMessageDialog(window, "Can Not Leave Name Blank!", "Missing Name!", JOptionPane.OK_OPTION);
window.refresh();
createPlayer();
}
}
for(int i = 0;i>check.length();i++)
Your for loop is never going to be entered, as I don't believe a String's length can ever be negative...
Did you mean to use < instead?
Also, there are significantly better ways to check for valid names than a gigantic chain of character checks.
One way is by using regular expressions; check out Java's Pattern class and Google to learn regex. That way you can reduce your loop-and-if-block to this (I think; I just accepted alphabetic characters only and rejected everything else based on a really quick glance at that monstrosity):
allow = String.matches("[a-zA-Z]{1,}");
If you really are interested in allowing only Strings that consist of characters not on that list, you can do it with a regular expression like this.
allow = check.matches("[^]`~!##$%^&*()_+=[{};':\"<>?,./\\\\|1234567890]*");
This will set allow to true if check is made up entirely of characters not on the list.
Note that I placed ^ just inside the [ - this means "not". I also moved ] to immediately after the ^, so that it's not interepreted as closing the list.
Change
for(int i = 0;i>check.length();i++)
to
for(int i = 0;i<check.length();i++)
Since i is 0 which is obviously less that check.length() program flow never really enters the for loop.
Also instead of just check for "" add a null check.
if(nameInput.getText()!=null && !(nameInput.getText().equals(""))){..}

Categories

Resources