Java - Using a Method in a If Statement [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to write a simple bit of code to get a input via BufferedReader and then execute some code within another method.
import java.io.*;
public class main {
public main() {
}
public static String input() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String out;
try {
out = br.readLine();
return out;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void someCode() {
//some code
}
public static void main (String[] args) {
input();
if(input() == "Input") {
someCode();
}
}
}
Thanks :)

Store the function in a variable like this:
String x = input();
if("Input".equals(x)) {
//do something
}
Also notice how I used .equals not == as == compares adresses in memory not the value.

You're calling the method once, throwing the result away, and then calling it again; the second time is probably not going to give you the results you want. Save the input in a variable instead:
String input = input();
if(input.equals("Input")) {
...
}
(You're also erroneously using == instead of .equals; see the code above.)

Related

Get variable value of string in java [duplicate]

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();
}
}
}

Iterating through attributes of DIFFERENT types in a class and printing each [duplicate]

This question already has answers here:
Printing all variables value from a class
(9 answers)
Closed 6 years ago.
I have this simple class:
public class Events{
Boolean wentToGym;
String eventsToday;
public Events(Boolean wentToGym, String eventsToday){
this.wentToGym = wentToGym;
this.eventsToday = eventsToday;
}
Now for some reason I need to iterate through these fields and print them. As they are from different types, I thought I would use the Object declaration in the for-loop:
public static void main(String[] args){
Events events = new Events(true, "first trial");
for(Object e: events.getClass().getDeclaredFields){
System.out.println(e.toString);
}
}
Unfortunately not working because the object has no toString method. It gives me the same result you get when you try printing an array. And I dont know how to cast them inside the loop as they are declared as objects. Whats the best way to iterate through the attributes of a class and print them?
Edit: the question some guys rushed into referring to as duplicated is about attributes all of the same type (Strings), so there is no need for using an object nor the problem is the same. Its always a good idea to try helping by even reading the whole thing even if its harder than feeling important by simply flagging a question.
Is this what you're looking for?
import java.util.Arrays;
public class Events {
Boolean wentToGym;
String eventsToday;
public Events(Boolean wentToGym, String eventsToday) {
this.wentToGym = wentToGym;
this.eventsToday = eventsToday;
}
public static void main(String[] args) {
Events events = new Events(true, "first trial");
Arrays.stream(events.getClass().getDeclaredFields()).forEach(field -> {
try {
System.out.println(field.getName() + ": " + field.get(events));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
}
}
Output:
wentToGym: true
eventsToday: first trial

How to access input variable from another class? java

Trying to get the 1st class to recognize what the user inputs in the 2nd class. Any ideas as to what is going wrong here? The 2nd class works fine, but when i try to call 'input' from the main class, it says that 'input' cannot be resolved. Any suggestions and pointers much appreciated. Thanks for your time.
1st class:
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = input.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = input.readLine();
}
}
}
2nd class:
public class automata extends Filter {
public static String input;
public static boolean UserInput() {
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
input = user_input.next();
if (accepts(input) == true){
System.out.print("works");
return true;
} else {
System.out.println("Problem");
return false;
}
}
2nd class should look like:
public class Automata { // we use upper case for class names
public String input; // or better private and use a get-method
public Automata() {} // constructor
public boolean readUserInput() { // lower case here
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
String nextInput = user_input.next();
input += nextInput; // otherwise you overwrite your current input
/*if (accepts(input) == true){
System.out.print("works");
// return true;
} else {
System.out.println("Problem");
return false;
}*/
// It is a terrible idea to return every time a single word is read
// rather read the whole String and then check if it is accepted
if (accept(input)) // whole String is checked
return true;
return false;
}
// in case the input variable is private
public String getInput() {
return input;
}
}
And then you have to access the class in this way:
public class Filter {
public static void main(String[] args) throws IOException {
Automata automata = new Automata();
if (automata.readUserInput()) {
// BufferedReader in4 = new BufferedReader(new StringReader(automata.getInput())); or automata.input in case it is public
// I don't understand why you want to read the input here again step by step
// rather read the whole input here
String userInput = automata.getInput();
}
}
}
You are confused with two different things: Class and Object. The Object is an Instance of the Class. Without understanding this you cannot understand what is wrong here.
Calling, for example Automata automata = new Automata() creates new Object of the class Automata.
"Extends" never helps you to get to the variables. It may help you to extend the current class and to use the methods that have been implemented in parent class, but you can never get to the pointers on the address spaces of that parent class.
To access a variable of another object you should declare public getter method for that variable in that class.
I think you need to replace
String s = input.readLine();
by
String s = in4.readLine(); in Filter class.
as readLine() is a method of BufferedReader Class
Try to rename the name of BufferedReader in input like this:
BufferedReader input = new BufferedReader(new StringReader(automata.input));
I think you have a typo..
Change input in the 1st class to in4.
'input' variable is declared in the 2nd class and you are trying to access it in the 1st class which is really impossible.
In class Filter, You do not have any member named input, due to which compile time exception is coming at input.readLine();.
From the context of your program, it appears that in4 should be used instead of input.
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = in4.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = in4.readLine();
}
}
}

Reading keystrokes from a keyboard and using if statement in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am learning how to program in Java. I wrote the following code but, I can't get the if statements to work when the variable inputName is compared to a string and the statement is true. Does anyone have any tips on how to fix this?
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String x = ("Hello type in your first name.");
System.out.println(x);
Scanner keyboard = new Scanner(System.in);
String inputName = keyboard.next();
if (inputName == "erick") {
System.out.println("Hi");
}
String v = "victor";
if (inputName == v) {
System.out.println("Hi");
}
String c = "christy";
if (inputName == c) {
System.out.println("Hi");
}
keyboard.close();
}
}
don't use == instead use equals() for string comparison.
== will check whether 2 references are referring the same object, while equals() will check the value being referred to.

NullPointerException with own class [duplicate]

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();
}

Categories