This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 4 years ago.
I would like it so that a user can tell my code that when a certain variable has a certain value it should do something. I have written a simple code sample of what I would like this to look like and I hope you can make sense of it. Is it in any way possible to make a String and let Java check wheter the variable that carries the same name is equal to the value of another variable.
int turn = 1;
String variable = "turn";
int compareToThisValue = 1;
if (variable.toVariable() == compareToThisValue) {
System.out.println("Yes it works thank you guys!");
{
I guess the following code can help. It uses java Reflection to get the job done. If you have some other requirements this can be tweaked to do so.
import java.lang.reflect.*;
class Test {
int turn = 1;
boolean checkValueVariable(String variableName, int value) throws Exception {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(variableName))
return field.getInt(this) == value;
}
return false;
}
public static void main(String... args) {
Test test = new Test();
String variableName = "turn";
int variableValue = 1;
try {
System.out.println(test.checkValueVariable(variableName, variableValue));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
This question already has answers here:
Compiler says "Variable might not have been initialized", although I have a flag variable to guarantee it [duplicate]
(7 answers)
Closed 4 years ago.
I'm learning Java and I have encountered a behaviour that I don't understand. All similar topics I have found here provided walkaround with initialization with default values (which I happily used) but no one has explained why the following approach generates errors.
To understand Java better, I have written the code below just to isolate the problematic part, so please focus on the error I'm asking about - I know this code does not make much sense.
public class Test {
public static void main(String[] args) {
int value;
ValueContainer valueContainer;
boolean isInputLegal = false;
while (!isInputLegal) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Set value ");
value = scanner.nextInt();
isInputLegal = true;
} catch (NumberFormatException | InputMismatchException e) {
scanner.nextLine();
isInputLegal = false;
}
if (isInputLegal) {
valueContainer = new ValueContainer(value);
}
}
valueContainer.printValue();
}
}
class ValueContainer {
int value;
public ValueContainer(int value) {
this.value = value;
}
public void printValue() {
System.out.println(value);
}
}
The error appears in line valueContainer = new ValueContainer(value); and in line valueContainer.printValue();
Things I have tried:
I thought maybe there is some kind of exception I am missing, so I replaced catch (NumberFormatException | InputMismatchException e) with catch (Exception e). Didn't help.
I thought maybe the compiler thinks the loop can go infinite and still not provide initialization, so I added a counter to the loop, which stops it after 1000 iterations and inserts some default values. Didn't help.
I understand that this error shows up usually when the programmer makes a mistake and leaves a path that leads to usage of initialized value, but I am 90% percent positive this is not the case here.
Try initialising your value, so instead of writing:int value; write: int value = 0,
also try and initialise your ValueContainer with the default constructor, and set it's value with a setter
public static void main(String[] args) {
int value = 0;
ValueContainer valueContainer = new ValueContainer();
boolean isInputLegal = false;
while (!isInputLegal) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Set value ");
value = scanner.nextInt();
isInputLegal = true;
} catch (NumberFormatException | InputMismatchException e) {
scanner.nextLine();
isInputLegal = false;
}
if (isInputLegal) {
valueContainer.setValue(value);
}
}
valueContainer.printValue();
}
This should work (with adding a setter method in your ValueContainer class)
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 6 years ago.
In java do we have any method to find that a particular string is part of string array.
I can do in a loop which I would like to avoid.
e.g.
String [] array = {"AA","BB","CC" };
string x = "BB"
I would like a
if (some condition to tell whether x is part of array) {
do something
} else {
do something else
}
Do something like:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
Example:
if(Arrays.asList(myArray).contains(x)){
// is present ... :)
}
since Java8 there is a way using streams to find that:
boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
// is present ... :)
}
You could also use the commons-lang library from Apache which provides the much appreciated method contains.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}
This code will work for you:
bool count = false;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(x))
{
count = true;
break;
}
}
if(count)
{
//do some other thing
}
else
{
//do some other thing
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I keep receiving this error but I cannot see any logical errors in my code.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
private double getValueOrDefault(String symbol, double defaultValue) {
double value = getValue(symbol);
if (value != -1)
return value;
else
return defaultValue;
}
public void createStocks() {
// try get stock realtime values
stocks.add(new TechStock("BB", 30.3));
stocks.add(new TechStock("GOOG", getValueOrDefault("GOOG", 5.8)));
stocks.add(new TechStock("AMZN", getValueOrDefault("AMZN", 6.3)));
stocks.add(new FinanceStock("GLNG", getValueOrDefault("GLNG", 121)));
}
public static double getValue(String symbol) {
// read data
try {
URL url = new URL(API_URL.replace("XXX", symbol));
Scanner s = new Scanner(url.openStream());
// find price
while (s.hasNextLine()) {
String line = s.nextLine();
if (line.startsWith("\"price\"")) {
// split shenanigans
String[] f = line.split("\"");
return Double.parseDouble(f[3]);
}
}
// if we reached here: the stock is invalid
return -1;
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}
public class StockFrame extends Frame
{
private int amount;
private Portfolio portfolio;
private ArrayList <StockMarket> stocks = new ArrayList<StockMarket>();
private TextArea stockDetails;
private TextField purchaseCode;
private boolean found = false;
private int locateStock() {
for(int i = 0; i<stocks.size(); i++) {
if(stocks.get(i).getCode().equals(purchaseCode.getText())) {
return i;
}
}
return -1;
}
private void a() {
int position = locateStock();
if(position != -1){
StockMarket bs = stocks.get(position);
.....
}
I tried changing I to 1 but I still receive the NullPointerException.
The error seems to be located at the int position = locateStock(); but I am unsure.
A NullPointerException occurs when you try to reference an object that hasn't been declared at that point in the execution of your program.
The fact that you still got the exception when you tried changing the initial value of i to 1 tells me that when you call locateStock(), your List of TechStocks hasn't been initialized with a new List<TechStock>() statement prior to calling locateStock(). Therefore, when you try to declare the for loop using stocks.size(), you get an exception, since stocks is null at that point.
However, it's difficult to say how to exactly fix your problem because you didn't really offer enough information in your snippet for anyone to know how that code fits in context with the rest of your program.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am a bit lost...I'm learning Java and have to program a small poll command line application.
We are supposed to program it in german first(to be consistent between us all), so I'll try to translate it, so it's easier to read for you.
My problem is, that it's throwing an exception (while compiling) as following:
Exception in thread "main" java.lang.NullPointerException
at communication.Poll.addQuestionItem(Poll.java:18)
at main.PollTool.main(PollTool.java:8)
am I initializing my array "questionItems" wrong? Aren't I supposed to do it like that? What's wrong here? Did I forget something? :(
main.PollTool:
package main;
import communication.Poll;
public class PollTool {
public static void main(String[] args) {
Poll poll = new Poll ("Best Smartphone:",3);
poll.addQuestionItem("iPhone"); //<--line 8
poll.addQuestionItem("Android");
poll.addQuestionItem("Windows Phone");
poll.askQuestions("This poll determines the polularity of different Smartphones.");
}
}
communication.Poll:
package communication;
import java.util.Scanner;
import calculations.QuestionItem;
public class Poll {
private String questionTitle;
private QuestionItem[] questionItems;
private int count;
private Scanner in = new Scanner(System.in);
public Poll(String s,int arraySize){
questionTitle = s;
questionItems = new QuestionItem[arraySize]; //<--problem here?
}
public void addQuestionItem(String s){
if(count<questionItems.length){
questionItems[count++].setItemText(s); // <--exception here
}
}
public void askQuestions(String topic){
System.out.println(topic);
System.out.println(questionTitle);
for(int i=0; i<questionItems.length; i++){
System.out.println("- - - "+ questionItems[i].getItemText() +" - - -");
System.out.print("Your numerical answer: ");
questionItems[i].vote(in.nextInt());
}
}
void evaluation(){
//not ready :)
}
}
calculation.QuestionItem:
package calculation;
public class QuestionItem {
int count;
int overall;
String text;
public void vote (int pointValue){
overall += pointValue;
count++;
}
public double getDurchschnitt(){
return (double) overall/count;
}
public void setItemText(String s){
text = s;
}
public String getItemText(){
return text;
}
}
When you initialize an array of objects like this:
questionItems = new QuestionItem[arraySize];
All of the values are null by default.
In addQuestionItem, you try to call a method on an object in the array. However, that object starts off null, so this line of code doesn't work:
questionItems[count++].setItemText(s);
What you have to do is initialize the object before setting the text:
questionItems[count] = new QuestionItem();
questionItems[count].setItemText(s);
count++;
Alternatively, you can do what Constant suggested, and initialize all the objects when you initialize the array.
By the looks of it, you're making the array but it doesn't contain the objects yet. You probably want this in the constructor instead.
questionItems = new QuestionItem[arraySize];
for(int i = 0; i < questionItems.length; i++) {
questionItems[i] = new QuestionItem();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm supposed to write exceptions to prevent invalid objects, such as Strings having no blanks or the double and int numbers being in a certain range. I am really confused on how to do this. Am I supposed to use an if/else statement? Or more try/catch statements?
EDIT: Each object needs to be validated. The strings cannot have blanks or contain only blanks, and the numbers cannot be less than zero. There are five other try/catch statements but I only included one. My question is what would I write so that the exception output is different for the different problems and is there a way to write it to avoid writing each exception for each separate try/catch? I looked at other posts about writing exceptions but I haven't learned what super is or does and cannot use it.
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public static void main(final String[] arg) throws Exception {
try {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
System.out.println(cd1.toString());
System.out.println("=========================");
} catch (final CDException cde) {
System.out.println(cde.getMessage());
System.out.println("=========================");
}
}
}
I would check the String, int,... with an if-statement and if something is incorrect throw an IllegalArgumentException.
First you have to write conditions (i.e. if statements) that check if the input is invalid. When you detect invalid input, you should throw an exception.
You can write custom exception like mentioned here.
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
You can give some logical name to your custom exception like IntegerNumberOutofRangeException.
And then you can use if else in your code and throw that custom exception for specific condition you have mentioned.
Code
int intNumber = 50;
if (intNumber > 60 && intNumber < 100) {
// Do your work
} else {
throw new CustomException("Integer number out of expected range of 60 to 100");
}
You should use IF to make validations.
A best practice is to not throw an exception from the constructor of a class.
Another best practice is to not make validations in the constructor of the class.
So a ruff improvement of your code would be (i didn't run it and there are still improvements to be made):
public class CD {
String artistname = "";
String albumname = "";
double cdprice = 0;
int amountinstock = 0;
public String ValidationMessage = "";
public CD(final String artistname, final String albumname, final double cdprice, final int amountinstock) {
this.artistname = artistname;
this.albumname = albumname;
this.cdprice = cdprice;
this.amountinstock = amountinstock;
}
public boolean ValidateCD()
{
this.ValidationMessage = "";
if (/*insert validation condition here*/)
{
this.ValidationMessage = "CD IS NOT VALID BECAUSE TITLE IS WRONG";
return false;
}
return true;
}
public static void main(final String[] arg) throws Exception {
final CD cd1 = new CD("Muse", "The Resistance", 11.99, 20);
final boolean isValid = cd1.ValidateCD();
if (!isValid) {
System.out.println(cd1.ValidationMessage);
}
}
}