null pointer exception prob in my coding - java

I am always getting nullPointerException on line validateCarPlate(nStr) in the main method and on line if(y.matches(rex)). How should i edit to remove the nullPointerException?
import javax.swing.*;
import java.lang.Exception;
public class Q2{
public static void main(String[]args){
boolean loop = true;
while(loop){
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
try{
validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y.matches(rex)){
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];
for(int i=0; i<x.length();i++){
arr[i] = x.charAt(i);
}

Looks like
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
this returns null
change the code like this
public static void main(String[]args){
boolean loop = true;
while(loop){
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
if(nStr != null)
{
try{
validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
}
Since, javadocs for JOptionPane#showInputDialog() says Shows a question-message dialog requesting input from the user I think you forgot to give a input.

change you method like that
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y == null){
// put some message to handle that exception such as
// JOptionPane.showMessageDialog(null,"Some Message");
}else if(y.matches(rex))
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
Also put the code of computeCheckDigit(y); method.

If you click the Cancel button, JOptionPane.showInputDialog will return a null. You can check the return value before passing nStr to validateCarPlate. If a null returned, just drop this nStr and continue the loop (or break it according to your requirement).

Related

Set a value to an object array

public class Jeux {
public static void main(String [] args) {
int nPlayer= 0;
String name;
boolean ok = false;
Player[] groupe = null;
do {
try {
System.out.print("How many player: ");
nPlayer= Clavier.lireInt();
ok = true;
} catch(NumberFormatException e) {
System.out.println("ERROR, enter a number");
}
} while(!ok);
groupe = new Player[nPlayer];
System.out.println(groupe.length);
for(int i=0; i<groupe.length; i++){
try{
System.out.print("Enter the name of the player " + (i + 1));
name = Clavier.lireString();
groupe[i].setNom(name);
} catch(NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
}
why can't I set the name for groupe[i] --> groupe[i].setNom(nom);. I get an exception.
I try to create multiple object without knowing the length of the array.
Maybe there's other possibility with array list and other method but im in school and we didn't see other method for the moment.
You need to instantiate each Player object in addition to instantiating the array which holds them:
name = Clavier.lireString();
groupe[i] = new Player(); // replace this with actual constructor
groupe[i].setNom(name);
Your code is catching a NullPointerException which is precisely what I would expect from your current code.

Validate if input is not numeric (number)

I am just a beginner. Am trying to validate if an input is numeric and not a string. I can't seem to get the correct result. It's always false.
import javax.swing.JOptionPane;
public class CheckDigit
{
public static void main(String[] args)
{
String containsOnlyNumbers;
containsOnlyNumbers = JOptionPane.showInputDialog("Please enter some numbers: ");
// System.out.println(containsOnlyNumbers("12345"));
// System.out.println(containsOnlyNumbers("12abc345"));
if (false)
{
JOptionPane.showMessageDialog(null, "False!");
}
else
{
JOptionPane.showMessageDialog(null, "True!");
}
}
public static boolean containsOnlyNumbers(String str)
{
for (int i = 0; i < str.length(); i++)
{
if (!Character.isDigit(str.charAt(i)))
return false;
}
return true;
}
}
Please advise. TIA.
If your want to use your solution you have to replace
if (false)
with
if (!containsOnlyNumbers(containsOnlyNumbers))
because you are not calling your method (same name for method and String).
You can also try like this,
public static boolean numericCheck(String str)
{
try{
double d=Double.parseDouble(str);
}catch(NumberFormatException e)
{
return false;
}
return true;
}
if method return true then input is a number, if return false input is not numeric

Java Scanner issues, Notecard class

I am trying to make a program that is basically virtual notecards. Each notecard has a string for a question and an answer as well as a count for now many times it has been asked. I am using a scanner in many instances and I think i am using it incorrectly, and am not quite sure why. The program will let me answer the first 2 questions, tell me they are incorrect no matter what, and skip letting me answer the last one. Here is the notecard class:
public class Notecard {
public String ans;
public String q;
public int count;
public Notecard(String q, String ans) {
this.q = q;
this.ans = ans;
this.count = 0;
}
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
System.out.println("Correct!");
return true;
} else {
System.out.println("Incorrect! Correct answer:" + this.ans);
count++;
return false;
}
}
public void clearCount() {
this.count = 0;
}
public String getQ() {
return this.q;
}
}
and here is my other file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class CreateNotecard {
int trys;
public static void main(String[] args) {
System.out.println("Get ready to be quizzed \n\n");
ArrayList<Notecard> notecards = makeCards();
quiz(notecards);
}
static ArrayList<Notecard> makeCards() {
ArrayList<Notecard> notecards = new ArrayList<Notecard>();
try {
BufferedReader in = new BufferedReader(new FileReader(
"notecards.txt"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] argg = str.split(",");
notecards.add(new Notecard(argg[0], argg[1]));
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
return notecards;
}
static void quiz(ArrayList<Notecard> notecards) {
ArrayList<Notecard> backupList = notecards;
Scanner sc = new Scanner(System.in);
long seed = System.nanoTime();
Collections.shuffle(notecards, new Random(seed));
int total = notecards.size();
int correct = 0;
for (Notecard x : notecards) {
System.out.println(x.getQ());
String effort = sc.next();
Boolean nailedIt = x.answer(effort);
if (nailedIt) {
correct++;
}
}
System.out.println("Total Notecards: " + total + "\nTotal Correct: "
+ correct);
System.out.println("Accuracy: " + (correct / total));
System.out.println("Do you want to repeat? Put \"y\" or \"n\"");
String choice1 = sc.nextLine();
if (choice1.toUpperCase().equals("Y")) {
System.out.println("Use only cards missed or all? Type \"missed\" or \"all\"");
String choice2 = sc.nextLine();
if (choice2.toUpperCase().equals("MISSED")) {
quiz(notecards);
} else {
quiz(backupList);
}
} else {
return;
}
}
}
I have a text file which I am using for this program, it contains
19-9,10
square root of 4,2
capitol of Missouri,Jefferson City
Blastoise's 1st evolution,squirtle
and my output is
Get ready to be quizzed
square root of 4
2
Incorrect! Correct answer:2
capitol of Missouri
Jefferson City
Incorrect! Correct answer:Jefferson City
Blastoise's 1st evolution
Incorrect! Correct answer:squirtle
Total Notecards: 3
Total Correct: 0
Accuracy: 0
Do you want to repeat? Put "y" or "n"
You are comparing the wrong things:
public Boolean answer(String effort) {
if (this.q.toUpperCase().equals(effort.toUpperCase())) {
Should be
if (this.ans.toUpperCase().equals(effort.toUpperCase())) {
The problem is that the Scanner class is looking for a delimiter to create tokens with, which is by default whitespace. Since you enter "2", the Scanner.next() finds no delimiters, so no token.
For example, if you enter "Jefferson City", the Scanner found one delimiter, so two tokens. sc.next in that case would be "Jefferson" only (no "City", that's the next token).
Solution? Read the line from stdin and using sc.nextLine()

Java programming - cannot reveive input from getInput in word filtering code

I've been coding a while for an assignment but can't figure out how
to receive a string input from the user to have the sentences filtered by unicode.
When I try to run the code, the input prompt won't happen. What am I doing wrong?
Any advice is appreciated.
package deel1;
import java.util.*;
public class Deel1 {
public static void main(String[] args) {
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zin = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zin = scan.nextLine().trim();
}
if (zin.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zin;
}
static String filterZin(String zin) {
for (int groteLetters = 65; groteLetters <= 90; groteLetters++) {
groteLetters = groteLetters + 32;
char kleineLetterAlfabet = (char) groteLetters;
}
int specialeTekens1 = 33;
int specialeTekens2 = 58;
int specialeTekens3 = 91;
if (specialeTekens1 <= 47 && specialeTekens2 <= 64 && specialeTekens3 <= 96) {
System.out.println("");
}
System.out.println("Gefilterd: " + zin);
}
}
Nah, come on, nobody posted an answer?
As Rohit pointed out, you never invoked the function!
//this method is the entry point
public static void main(String[] args) {
// invoke getting input, store it in local variable
String input = getInput();
//invoke filtering method, store result in lcal variable
String output = filterZin(input);
}
The filterZin method doesn't really do anything...
Bigger problem, that it is not even valid! The filterZin method is specified to have a String return type - and nothing gets returned. Add a return statement to the end, to get at least a syntactically correct method...
You wrote a method getXYZ() which returns a String when called.
This is your method definition:
static String getInput() {
//your code
return someString;
}
This says, when you'll call this method at any point in the program, this method will return a String object.
Inside your main method:
String returnString = getInput();
This is called method calling or invocation. You will not receive something until you call for it.
Now, about your program asking for input from user.
Here's a simple code for that:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//This will create a chain for input from console
System.out.println("Enter a line:");
String userInput;
try{
userInput = br.readline();
}catch(IOException e){
e.printStackTrace();
}

Allowing a maximum number of times for system to accept incorrect PIN

I made a java login screen for a console application, but I need it to allow the user to input ther wrong PIN only 3 times. After the user has entered the PIN more than 3 times, the system should exit.
However, the loop which I used for the else part of the if condition does not seem to be making any changes to the program. (program wont execute the else part even once). Does anybody know what I am doing wrong?
if (userPIN.equals(a[0]))
{
System.out.println("You have login!");
valid=true;
String b=a[2];
Login.c=Double.parseDouble(b);
System.out.println(c);
obj.balance = Login.c;
obj.MainMenu();
System.exit(0);
}
else if(userPIN != a[0])
{
int count=0;
for(int i=0;i<count;i++)
{
System.out.println("Invalid PIN!");
check();
}
}
int count=0;
for(int i=0;i<count;i++)
The for loop's condition is initially false, hence it will never execute its body.
You have many problems in your code :
in the first if your using :
userPIN.equals(a[0])
but in the else you're using :
userPIN != a[0]
Your for loop cannot run correctly :
int count=0;
for(int i=0;i<count;i++)
Here is the correct implementation using Object-Orientation :
import java.util.Scanner;
public class PinChecker {
// Immutable Class
private static final class Pin {
private String _pin;
Pin(String pin) {
this._pin = pin;
}
public String toString() {
return _pin;
}
public boolean equals(Pin pin) {
if(pin.toString().equals(_pin)) {
return(true);
} else {
return(false);
}
}
}
public static final int NB_OF_TRIES = 3;
public static void main(String[] args) {
System.out.println("Enter your PIN :");
Pin userPin = new Pin("FOO");
Scanner console = new Scanner(System.in);
boolean pinMatch = false;
int i = 0;
while(!pinMatch && i < NB_OF_TRIES) {
Pin keyedPin = new Pin(console.nextLine());
i++;
if(userPin.equals(keyedPin)) {
pinMatch = true;
} else {
System.out.println("Invalid PIN!");
}
}
if(pinMatch) {
System.out.println("OK, nb of tries :" + i);
} else {
System.out.println("KO, nb of tries :" + i);
}
}
}
You can store the keyedPin object if you need to.
in the else part try !(userPIN.equals(a[0]))
Your else part is not checking the contents.

Categories

Resources