This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Looking for some help here. I'm trying to make this method work. Whenever I run the method, it throws IllegalArgumentException even if I do type in A,B,C or D. I am using an inputReader class. Here is the code for my DriverExam class. Please let me know where I am going wrong. I'd like it so the only valid answers are a,b,c,or d. I have to use a while loop and everything I've tried won't help me match the driverAnswers.
public class DriverExam
{
// instance variables
public static final String[] ANSWERS = {"B","D","A","A","C","A","B","A","C","D","B","C","D","A","D","C","C","B","D","A"};
private String [] driverAnswers;
private InputReader inputReader;
public DriverExam(){
driverAnswers = new String[20];
inputReader = new InputReader();
}
public void promptStudentAnswers(){
int index = 0;
while(index < driverAnswers.length){
System.out.println("enter answer");
String driverAnswers = inputReader.readString();
if(driverAnswers != ANSWERS[index]){
throw new IllegalArgumentException(" answers can only be A,B,C or D");
} else{
index++;
}
}
}
}
First, you want to test if the answer is one of A, B, C or D (not that the answer matches something in the correct answers array). Also, your driverAnswers is masked because you created another local variable with that name. Basically, I think you wanted something like
public void promptStudentAnswers() {
int index = 0;
while (index < driverAnswers.length) {
System.out.println("enter answer");
String answer = inputReader.readString().trim().toUpperCase();
if (answer.length() == 1 && "ABCD".indexOf(answer) != -1) {
driverAnswers[index] = answer;
index++;
} else {
System.out.println("Answers can only be A,B,C or D");
}
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}
This question already has answers here:
Java, Simplified check if int array contains int
(15 answers)
Closed 6 years ago.
for example I want to do something like this:
package tst;
public class forInif {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
if (for(int i : a) {i == 5;}) {/**/}
}
}
I know normally I should make a boolean value of this situation by my own, but just in case, is there anyway to do something like that rather than make a boolean value somewhere else?
In Java 8+, you can use IntStream.anyMatch:
if (IntStream.of(a).anyMatch(i -> i == 5)) { ...
Not directly no: the condition check in a Java if needs to be a boolean type. But you could build a function:
public class forInif {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
if (foo(a)) {/**/}
}
}
where foo is a function returning a boolean that takes an int[] as a parameter.
There is no way to make a for loop return a boolean value. However, streams sound like a good way to do this in one or two lines:
int[] a = {1,2,3,4,5};
int fives = Arrays.stream(a).filter(e -> e == 5).count();
if (fives > 0) {
//replace this with whatever you want to do when a five is found
System.out.println("One or more fives exists in the array");
}
This question already has answers here:
Java exception handling
(8 answers)
Closed 7 years ago.
Well im really new to java and im really trying hard to understand what can be done in java and what can't. I'm making a console application based on the well known game Hangman. Basiclay what i'am trying to do is stop the user from typing 'e's more than twice, to do that i made 2 methods:
The first one adds 1 to the int variable mManyTimes whenever the user types e.
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
the second method is the one that sends an exception
to the user when the user types e more then twice.
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
Basicly i created two files, one that holds the code of the game(Which those two methods are in) and other one.
the file that holds the logic of the game is Game.java and here is the code that is inside it:
public class Game {
private String mAnswer;
private String mHits;
private String mMisses;
private int mManyTimes;
public char letter;
public Game(String answer) {
mAnswer = answer;
mHits = "";
mMisses = "";
}
public boolean applyGuess(char letter) {
//checks for char letter inside the mAnswer variable.
//If it is there the indexOf() method should return the index of the letter.
//If it is not there it will return -1.
//We are basicly saing if indexOf() method returns 0 or more then that then the isHit
//if it is not then the isHit boolean will return false.
boolean isHit = mAnswer.indexOf(letter) >= 0;
if (isHit) {
mHits = mHits + letter;
} else {
mMisses = mMisses + letter;
}
adder();
return isHit;
}
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
The other file that holds the main() method and prints the code to the console is Hangman.java:
public class Hangman {
public static void main(String[] args) {
// Enter amazing code here:
Game game = new Game("treehouse");
game.applyGuess('e');
game.applyGuess('e');
System.out.println(game.cheatStopper());
}
}
So here is the question that frustrated me and i never found and answer for:
How do i get my code to work and stop the user from typing more then two e.
Well well i know my code has many errors and bad structure but dont forget that im new to java, and thanks for advance :).
You need a catch block. Look up how to catch exceptions.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
{
int[] n = new int[4];
n[0]=1;
n[1]=3;
n[2]=4;
n[3]=5;
for(int i=0; i<4; i++)
{
System.out.print(n[i]+ " ");
}
menjava(n);
System.out.println();
for(int i =0;i<4;i++)
{
System.out.print(n[i]+ " ");
}
}
public static void menjava(int[] a)
{
a[0]=1*10;
a[1]=3*10;
a[2]=4*10;
a[3]=5*10;
}
}
http://imgur.com/0CNqY9A //the result in console
{
int n = 1;
System.out.println(n);
menjava(n);
System.out.println(n);
}
public static void menjava(int st)
{
st = 4;
}
}
http://imgur.com/dAqzuez //the result in console
So why did the Array get returned, but the integer stayed the same (whcih in my mind should). I can't find anything on why the array get's returned in an void function.
The reference to the array is not returned nor changed.
The array referenced has been changed.
int[] n = new int[4];
In this code n is a reference to an array and this reference is copied when you pass it to a method. This reference is not changed.
Your issue here is that Java is a pass by value language. This means in your situation you are providing your method menjava with what might as well be a temporary array that contains the same values as your original array n. So when this array is passed to menjava it does the calculations, but to this temporary array that your main method doesn't know about.
The easiest fix here is to have your menjava method return the array it worked on and set your array to that value in the calling function something like this:
public static int[] menjava(int[] a){
//changes to array a
return a;
}
and then in your calling function:
{
//your other code
n = menjava(n);
//the rest of your code
}
This question already has an answer here:
Missing return statement error in a method
(1 answer)
Closed 9 years ago.
trying to figure this out. I've created a method that checks if the user has entered an integer using a catch block.
The method obviously is asking for a return statement but no matter where I put it it does not work. Could anyone offer any advice?
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
inputDouble();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn == true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {System.out.println ("Integers only, try again" );
myKeyboard.next();
return num;
}
}
}
}
When carryOn == false then it will go to the bottom of your method and there's no return statement there. You need to have a return statement at the bottom.
Here's an explanation of the error: If a function says it returns something (an int in this case) that means that every path it can take must return an int. You're missing one of those paths which is a compile time error.