while loop with if statement not working [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 5 years ago.
By way of an example I have a txt file that contains a list of dogs, one on each line of the file and then "**" on the last line. I then have the following code to load this into an ArrayList to use in a JComboBox.
This way I can simply add another line in the text box to add another dog.
My example code is as follows
public class test{
static String temp;
public static void main(String[] args) {
List<String> picklistDogs = new ArrayList<String>();
File picklistFile = new File (filePath);
try {
BufferedReader loadPickList = new BufferedReader (new FileReader(picklistFile));
while(true) {
temp = loadPickList.readLine();
if (temp != "**") {
picklistDogs.add(temp);
} else {
break;
}
}
loadPickList.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
}
catch(IOException e){
System.out.println("file io error");
}
} // END of main
} // END of class test
My problem seams to be that the if statement never triggers the break to exit the while loop.
Any solutions would be appreciated.

Use !temp.equals("**") .Try below code
if (!temp.equals("**")) {
picklistDogs.add(temp);
} else {
break;
}

In order to compare strings better to use java.lang.String#equals

Related

Printing ArrayList to an output file [duplicate]

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 2 years ago.
I am trying to print the content of a PriorityQueue to an output file by converting it to an ArrayList.
(NOTE: I'm not printing to the console!)
Besides I declared a toString method, I am still getting the outputs like this: I#7c3df479
Converting the queue to ArrayList:
private PriorityQueue<GameState> unexpanded = new PriorityQueue<>(Comparator.comparing(GameState::getF_n));
...
public ArrayList<GameState> getUnexpanded()
{
ArrayList<GameState> unExpanded = new ArrayList<>(unexpanded);
return unExpanded;
}
Getting the ArrayList and trying it to print:
private void printSolution() throws IOException
{
FileWriter outFile = new FileWriter("output.txt");
PrintWriter output = new PrintWriter(outFile);
ArrayList<GameState> unexpanded = game.getUnexpanded();
for (int i = 0; i < unexpanded.size(); i++)
{
output.printf(unexpanded.get(i).toString() + "\n");
}
output.close();
}
toString method:
public class GameState
{
private int[][] grid;
...
#Override
public String toString()
{
return "{" + grid + "}";
}
}
Everything is working fine but the program print the contents like: I#7c3df479
Can anybody please help me with this?
Many thanks for the answers and comments in advance.
'grid' is declared as a 2D array which isn't a primitive in java. As such, when you try to print it, it still prints out the memory address / reference.
Try replacing it with Arrays.deepToString(grid) instead.

Driver Exam multiple choice Array while loop prompt student Answers method [duplicate]

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

How do I call a list from other classes? [closed]

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 7 years ago.
Improve this question
Okay so I am building a program that will sort grades and records of students. It is a command-line program and when run it will start by asking for user input. there are several commands such as exit(exits program), load [file name](loads a file name), student [student name] (loads student records), etc. the others are not important. Well basically what I am wondering and what I am stuck on is all those functions will be in separate classes and will be called when the user inputs a specific command, but if I put the "load" command in its own class, then how do I get it to share its information with the other classes? I know I have to use BufferReader to read in the files, but how would I go implementing my load class, or if there is a better way feel free to say so. here is my code so far. there isn't much on my other classes because I feel like I need to figure out how to read in and share the file with the other classes first.
import java.util.*;
import java.io.*;
public class program7
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Grade Stats by ");
System.out.print(">");
while(scan.hasNextLine())
{
String input = scan.nextLine();
if(input.equals("exit"))
{
System.exit(0);
}
else if(input.equals("help"))
{
System.out.println("exit - program closes.");
System.out.println("load [filename] - loads a class database specified in [filename].");
System.out.println("students - prints out a list of students from the class, along ");
System.out.println(" with total points, and final grades for each student.");
System.out.println("assignments - prints out a list of assignments from the file, along with points possible");
System.out.println("student [student name] - Prints report for the student");
System.out.print(">");
}
else if(input.contains("load"))
{
String[] split = input.split(" ");
LoadStudents loadStudents = new LoadStudents(split[1]);
loadStudents.getFromFile();
System.out.print(">");
}
else if(input.equals("students"))
{
Students students = new Students();
students.printer();
System.out.print(">");
}
else if(input.equals("assignments"))
{
System.out.print(">");
}
else if(input.contains("student"))
{
String[] split = input.split(" ");
Student student = new Student(split[1]);
System.out.print(">");
}
else if(input.contains("assignment"))
{
}
else if(input.equals("grades"))
{
}
else
{
System.out.println("exit - program closes.");
System.out.println("load [filename] - loads a class database specified in [filename].");
System.out.println("students - prints out a list of students from the class, along ");
System.out.println(" with total points, and final grades for each student.");
System.out.println("assignments - prints out a list of assignments from the file, along with points possible");
System.out.println("student [student name] - Prints report for the student");
System.out.print(">");
}
}
}
}
That is my main class, but here is my Load and Students class.
import java.util.*;
import java.io.*;
public class LoadStudents
{
public String inputFile;
public List<Object> info = new ArrayList<Object>();
public LoadStudents(String inputFile)
{
this.inputFile = inputFile;
}
public List<Object> getFromFile()
{
try
{
BufferedReader in = new BufferedReader(new FileReader(inputFile));
try
{
String line = "";
while(in.readLine() != null)
{
line = in.readLine();
info.add(line);
}
}
catch(IOException e)
{
System.err.println("Exception, man");
}
finally
{
in.close();
}
}
catch(FileNotFoundException e)
{
System.err.println("File wasnt found ");
}
catch(IOException e)
{
System.err.println("Exception, man");
}
return info;
}
}
import java.util.*;
public class Students
{
public Students()
{
}
public void printer()
{
List<Object> info = (new LoadStudents()).getFromFile();
for (int x = 0; x<info.size(); x++)
{
System.out.println(info.get(x));
}
}
}
the Students class isnt finished but I am trying to figure out how to read the list from other classes. I have done research and have seen 3 similar problems, but they there is still something I'm missing because I keep getting the error
.\Students.java:11: error: constructor Load in class Load cannot be applied to g
iven types;
List<Object> info = (new LoadStudents()).getFromFile();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand it wants input, but I want it to use the previous input the user gives it when he inputs the command "input [whateverfile]".
Can anyone tell me how I can call that list my Load class produces to any other class?
There are many ways to do this. My suggestion is that your Load class should be a factory that actually creates a list of Student from the file, and not a list of strings.
Here are more suggestions:
Load class could have all methods statics and it could be non-instantiable. The fields you have in this class are useless after the file is read, you can just pass them to the static method as parameters.
Load is not a nice name for that class. LoadStudents is more meaningful, or even better StudentFactory.
Load and Student probably don't need to be public, package-private are be enough. Same for all the methods in these classes. Always use the lowest visibility possible.
data() is not a nice name for that method either. Something like getStudents(), or if you follow above advice, getFromFile(), is more meaningful.
Always print/log the stacktrace of the exceptions, otherwise you won't even know what/where it happened.
Instead of making the user type the whole commands, put a number on each option and let user select by number, that's faster to type and you avoid typo errors as well.
Only import the classes you're actually working with and not the whole package, that will make the compilation faster (unless you're importing a lot of classes from that package, which is not the case here).
EDIT: since you still don't understand what I mean, here's an example:
class StudentFactory {
private static List<Student> listCache = new ArrayList<>();
static List<Student> getStudents(final String filePath) {
if (listCache.isEmpty() {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filePath));
String line;
while((line = in.readLine()) != null) {
// Parse the line and create a Student instance from it, then add it to the list
listCache.add(student);
}
} catch(IOException e) {
System.err.println("Exception, man");
e.printStackTrace();
} catch(FileNotFoundException e) {
System.err.println("File wasnt found ");
e.printStackTrace();
} finally {
if (in != null) in.close();
}
}
return listCache;
}
private StudentFactory() {
// Avoid instantiation
}
}
Then you can just do
final List<Student> listOfStudents = StudentFactory.getStudents(filePath);
from anywhere in your code to get a list of students. filePath can be null if you already passed it previously.

Error with a Scanner variable in while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm new in Java and I find it very complicated because of the errors that I come across with. So I have a problem with this piece of code:
Main Class:
public class Main {
public static void main(String[] args){
Answer a = new Answer();
String ans = null;
while(ans != "A"){
ans = a.create();
System.out.print(ans + "\n");
}
}
}
Answer class:
import java.util.Scanner;
public class Answer {
public String create(){
Scanner s = new Scanner(System.in);
return s.next();
}
}
I want the program to allow me to write something. Then, if what I've written hasn't been the letter A, the program must allow me to write something else, otherwise has to stop. But, even though I write "A", the program is still keeping on, allowing me to write something else. What's wrong with the code?
String can't be compared properly using the != operator. Instead you should use while(!ans.equals("A")). Secondly, try not to recreate the Scanner object in the create method. This is a resource waste.

Loop isn't breaking when a specific string is inputted [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
When the user inputs pBreak, it should break the while loop. However, this isn't working and I'm confused on why. Could somebody please help me?
package main;
import java.io.*;
import java.util.*;
public class TextFiles {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
Scanner input = new Scanner(System.in);
while (true) {
String line = input.next();
if (line == "pBreak") {
break;
}
out.write(line);
out.newLine();
}
out.close();
} catch (IOException e) {
System.out.println("Error!");
}
}
}
Use equals instead of ==. Consider, null-safe equals
if ("pBreak".equals(line)) {
Change:
if (line == "pBreak") {
to
if (line.equals("pBreak")) {
== compares object references, .equals(String) compares String values.
This code will also work:
if (line.equals("pBreak")) {
break;
}
== operator will compare the references of the two operands.
As line variable is a different string object's reference ,it will not match to string literal constant reference pBreak while comparing.
if (line .equals("pBreak")) {
break;
}
So equals() method has to be used to compare the String.enter code here

Categories

Resources