I've been working in these codes and I had a problem in the part when the user will input a value he/she want to check if it's in the array or not.
How to check an object in an array in Java?
public static void main (String args [])
{
String sInput1,sInput2,sLetters,s;
int iInput1,i1,i2;
boolean b1 = true;
sInput1 = JOptionPane.showInputDialog("Enter the number of values in the array:");
iInput1 = Integer.parseInt (sInput1);
String Arr1[] = new String [iInput1];
for (i1=0;i1<iInput1;i1++)
{
Arr1[i1] = JOptionPane.showInputDialog("Enter the values:");
System.out.println("You entered " + Arr1[i1] + ".");
}
sInput2 = JOptionPane.showInputDialog("Enter the value you want to check in the array:");
for (i1=0;i1<iInput1;i1++)
{
if (Arr1[i1].equals(sInput2))
{
b1=true;
}
else
{
b1=false;
}
if (b1 == true)
{
JOptionPane.showMessageDialog(null,"The value you want to check is in the array.","RESULT!",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null,"The value you want to check is not in the array.","RESULT!",JOptionPane.INFORMATION_MESSAGE);
}
}
Use:
b1 = Arrays.asList(Arr1).contains(sInput2);
Firstly you must initialise b1 as false:
boolean b1 = false;
Then your can do the check:
for (i1 = 0; i1 < iInput1 && !b1; i1++)
if (Arr1[i1].equals(sInput2))
b1 = true;
And, in the end, print out the result:
if (b1)
JOptionPane.showMessageDialog(null, "The value you want to check is in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null, "The value you want to check is not in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);
Or, shortly:
JOptionPane.showMessageDialog(null, "The value you want to check is" + (b1 ? " " : " not ") + "in the array.", "RESULT!", JOptionPane.INFORMATION_MESSAGE);
Related
In my code I have a while loop with 3 IF tests nested in between that have flags triggered by ELSE:
[test1] checks whether the input value has a length of exactly 1 [Prevents users from inputting nothing]
[test2] checks whether the input value at index 0 is a digit [I need a number as an input, but I'm using JSWING]
[test3] checks whether the input value length is greater than 1 [2 Digits (10,11,12,...)
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
while(exit == false || test1 == false || test2 == false || test3 == false) {
if(num1.length() < 1) {
JOptionPane.showMessageDialog(null,"Input required");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test1 = true;
}
if(Character.isDigit(num1.charAt(0)) == false) {
JOptionPane.showMessageDialog(null,"Input has to be a number between 0 - 9.");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test2 = true;
}
if(num1.length() > 1) {
JOptionPane.showMessageDialog(null,"Input has to be a number between 0 - 9.");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test3 = true;
}
if(test1 == true && test2 == true && test3 == true) {
exit = true;
}
The problem I'm having is somewhere between the first and second test. When I try inputting nothing as a value ["" / or just having an empty box and pressing enter], it detects the error of having nothing and displays "Input required" once, but once it loops, it outputs a StringIndexOutOfBoundsException for the second trial
It works in every other case I've tried (no input -> correct, no-input -> incorrect...) Only sequential no-input cases crash the program.
The error is said to be in this line, but I don't understand where, or how.
if(Character.isDigit(num1.charAt(0)) == false)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at oof.Lottery_Swing_FIX.main(Lottery_Swing_FIX.java:56)
Fixed Logic
JOptionPane.showMessageDialog(null,"Enter 3 one-digit positive numbers for your 3 guesses");
for(int counter = 0; counter < LIMIT; counter++) {
test = false;
while(exit == false || test == false) {
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "");
if(num1.length() < 1 || Character.isDigit(num1.charAt(0)) == false || num1.length() > 1) {
JOptionPane.showMessageDialog(null,"Integer between 1-9 required");
}
else {
test = true;
}
if(test == true) {
numberInput = Integer.parseInt(num1);
exit = true;
}
else {
continue;
}
}
Your 'fix' doesn't handle null which will be returned by the JOptionPane.showInputDialog() if the dialog is closed (x) or the cancel Cancel button is selected. You can't play null against the String#length() method as you can with a Null String ("") so, you need to check for this in your code otherwise you can end up with a NullPointerException. You can do this in your very first if statement as a conditional component:
if (num1 == null) {
// The CANCEL or dialog close button was selected.
}
You really don't need those boolean flags in your code. Things are going to happen or they simply will not. You don't really need flags to remind you so close to home (so to speak). If you have the conditions established properly within the if statements and utilize else if then they're not required. With that being said, you don't need these boolean flags within the condition for the while loop either.
The while loop needs to be concerned about one thing...that the prompt is provided valid data. If it isn't then the variable (num1) which holds the prompt data is converted to a null string (""). So in reality:
String num1 = "";
while (num1.equals("")) { .... }
So, for as long as num1 contains a null string ("") we just keep looping thus re-prompting for proper input.
In your code, you want to provide the User with specific details as to why their input failed. There are several ways to do this however whichever way you choose to do it, make sure it doesn't generate any exceptions (errors) that can ultimately halt your application or change its accurate performance. There is nothing wrong with using if and else if statements to carry out this particular task in its current use-case. Following your particular theme:
int LIMIT = 3, numberInput;
int[] guesses = new int[LIMIT];
String errMsg;
String num1;
JOptionPane.showMessageDialog(null, "<html>You will be prompted three times "
+ "to supply<br>a positive <font color=red><b>single digit</b></font> "
+ "number.</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
for (int counter = 0; counter < LIMIT; counter++) {
num1 = "";
while (num1.equals("")) {
errMsg = "";
num1 = JOptionPane.showInputDialog(null, "Please input Guess #" + (counter + 1),
"Guess #" + (counter + 1),JOptionPane.QUESTION_MESSAGE);
// Does num1 contain null?
if (num1 == null) {
if (JOptionPane.showConfirmDialog(null,
"<html>You <font color=blue>canceled</font> your input!<br>"
+ "Do you want to quit?</html>", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
System.exit(0);
}
num1 = ""; // Set for re-prompt.
continue;
}
// Is nothing supplied?
else if (num1.length() < 1) {
errMsg = "<html><font size=5 color=red><center>Nothing Supplied!"
+ "</center></font><br>You must provide a single Integer "
+ "value between<br>0 and 9 (inclusive).</html>";
}
// Is too much supplied?
else if (num1.length() > 1) {
errMsg = "<html><center><font size=5 color=red>To Much Supplied!</font><br>" +
"<font size=5 color=blue>\"" + num1 + "\"</font></center><br>" +
"You must provide a single Integer value between<br>0 and 9 "
+ "(inclusive).</html>";
}
// Is the supplied character a number?
else if (!Character.isDigit(num1.charAt(0))) {
errMsg = "<html><center><font size=5 color=red>Invalid Digit Supplied!"
+ "</font><br><font size=5 color=blue>\"" + num1 + "\"</font>"
+ "</center><br>You must provide a single Integer value "
+ "between<br>0 and 9 (inclusive).</html>";
}
// Does errMsg actually contain a message? If so display it.
if (!errMsg.equals("")) {
JOptionPane.showMessageDialog(null, errMsg, "Invalid Input!",
JOptionPane.WARNING_MESSAGE);
num1 = ""; // Set for re-prompt.
}
else {
numberInput = Integer.parseInt(num1);
// ... do whatever you want to do with numberInput, for example ....
guesses[counter] = numberInput;
}
}
}
// Display User's LIMITED guesses:
StringBuilder sb = new StringBuilder();
sb.append("<html>The <font color=red><b>").append(LIMIT).
append("</b></font> Guesses supplied by User are:<br><br>");
for (int i = 0; i < guesses.length; i++) {
sb.append("Guess #").append((i + 1)).append(": <font color=blue>").append(guesses[i]).append("</font><br>");
}
sb.append("</html>");
JOptionPane.showMessageDialog(null, sb.toString(), "Guesses Provided",
JOptionPane.INFORMATION_MESSAGE);
As you can see, providing details to a User about input failures requires a lot more code. All this code can be removed if you decide you want just a simple "Invalid Input!" message. This in essence forces the User to read the supplied prompts with more intensity, for example:
int LIMIT = 3;
int numberInput;
int[] guesses = new int[LIMIT];
String num1;
JOptionPane.showMessageDialog(null, "<html>You will be prompted three times "
+ "to supply<br>a positive <font color=red><b>single digit</b></font> "
+ "number.</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
for (int counter = 0; counter < LIMIT; counter++) {
num1 = "";
while (num1.equals("")) {
num1 = JOptionPane.showInputDialog(null, "Please input Guess #" + (counter + 1),
"Guess #" + (counter + 1),JOptionPane.QUESTION_MESSAGE);
// Does num1 contain null?
if (num1 == null){
if (JOptionPane.showConfirmDialog(null,
"<html>You <font color=blue>canceled</font> your input!<br>"
+ "Do you want to quit?</html>", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
System.exit(0);
}
num1 = ""; // Set for re-prompt.
}
else if (!num1.matches("\\d")) {
JOptionPane.showMessageDialog(null, "<html><center><font size=5 color=red>Invalid Input Supplied!</font><br>" +
"<font size=5 color=blue>\"" + num1 + "\"</font></center><br>" +
"You must provide a single Integer value between<br>0 and 9 "
+ "(inclusive).</html>", "Invalid Input!", JOptionPane.WARNING_MESSAGE);
num1 = "";
}
else {
numberInput = Integer.parseInt(num1);
// ... do whatever you want to do with numberInput, for example ....
guesses[counter] = numberInput;
}
}
}
// Display User's LIMITED guesses:
StringBuilder sb = new StringBuilder();
sb.append("<html>The <font color=red><b>").append(LIMIT).
append("</b></font> Guesses supplied by User are:<br><br>");
for (int i = 0; i < guesses.length; i++) {
sb.append("Guess #").append((i + 1)).append(": <font color=blue>").append(guesses[i]).append("</font><br>");
}
sb.append("</html>");
JOptionPane.showMessageDialog(null, sb.toString(), "Guesses Provided",
JOptionPane.INFORMATION_MESSAGE);
Pay special note to the condition for the else if statement (!num1.matches("\\d)) in the above code. Here the use of the String#matches() method is used with a small Regular Expression, the "\\d" expression. This expression tells the matches() method to see if the string we're matching (in num1) is a single digit string numerical value (like: "5" for example). So, what the else if statement is asking:
else if the string contained in num1 is NOT (!) a single digit string numerical value then run the code in my curly braces ({...}). This basically covers all input failures except null (because we're handling that as a quit option) and the String#matches() method will not accept null.
If you don't want a quit option then then you would only need a single if statement in your code:
if (num1 == null || !num1.matches("\\d")) { ... }
I need help in designing a for loop that returns the name if found and if it is not found it returns the requested name as not found. I need to do this without repeating the not found loop multiple times.
I have tried various if, else if, and else statements. I have also tried a do while loop inside of the for loop and also tried to do the not found statement outside of the loop
String[] values = new String[12];
int name = 1;
// Initialize Scanner
java.util.Scanner input = new java.util.Scanner(System.in);
// Create loop for name input
for (int i = 0; i < values.length; i++)
{
System.out.print("Enter in " + " the name of friend " + name++ + ": ");
values[i] = new String(input.next());
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
}
// Create loop for name output
System.out.println("\n" + "The names of your friends are: ");
for (int i = 0; i < values.length; i++)
{
if (values[i].equalsIgnoreCase("zzzz"))
{
break;
}
else
{
System.out.println(values[i]);
}
}
// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.equalsIgnoreCase(values[i]))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
else if (find != values[i] && (found = false))
{
System.out.println("\n" + "Your friend " + find + " was not found" );
break;
}
}
}
}
I expect the not found statement to not be reiterated multiple times through the loop until the actual name is found. If the name does not exist in the array, it should search through the whole array and return that it was not found.
See my attempt. I have cast all elements to lower case whilst we iterate through the array to ensure we don't miss a match. For example if we searched for
"tom" and in the array we had "Tom" the match would be missed.
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
boolean foundFlag = false;
String[] values = new String[12];
//Populate array
for(int i = 0, x = 1; i < values.length; i ++, x ++)
{
System.out.print("Enter name of friend " + x + ": " );
String name = input.next();
values[i] = name;
}
//Output all elements of the array
System.out.println("\n" + "The names of your friends are: ");
for(String x : values)
{
System.out.println(x);
}
//Find a friend
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
//Iterate through array and check if Friend inside.
for(int i = 0; i < values.length; i ++)
{
if(values[i].toLowerCase().equals(find.toLowerCase()))
{
foundFlag = true;
break;
}
}
//If friend in the array flag will be True, else flag will remain false.
if (foundFlag)
{
System.out.println("Friend " + find + " found");
}
else
{
System.out.println("Friend " + find + " not found");
}
}
}
just create a function to do your searching:
public boolean findName(String[] items, String name) {
if (items == null || items.length == 0 || name == null || name.trim().isEmpty()) return false;
for(int i = 0; i < items.length; i++) {
if (items[i].equalsIgnoreCase(name.trim())) {
return true;
}
}
return false;
}
Then where ever you need to find a friend:
boolean exists = findName(values, "Foo Bar");
if (exists) {
System.out.println("Friend exists");
} else {
System.out.println("Friend does not exists");
}
You can use also java 8 streams :
boolean found = Stream.of(values)
.anyMatch(value -> value.equalsIgnoreCase(name));
try to use this code :
// Search for the name
boolean found = false;
System.out.print("\n" + "Enter in the name of the friend you would like to find: ");
String find = input.next();
for(int i = 0;i < values.length && !found;++i)
{
if (find.toLowerCase().equals(values[i].toLowerCase()))
{
System.out.println("\n" + "Your friend " + find + " was found");
found = true;
break;
}
}
if(!found){
System.out.println("\n" + "Your friend " + find + " was not found" );
}
}
I'm a novice coder and we are given a task in college to only use Arrays
(I asked the teacher and said no array lists or whatsoever, wants to do it the rough way)
its about making an array that you are able to insert, search, or delete a value in it. I figured out the most of it by searching and applying out solutions.
But they wanted an output so that if I delete THEN I search that value, it would display that the value is gone, but the problem is since that value is deleted Java places a null in there, so when the for loop cycles through all of the nulls it creates the dreaded NullPointerException error. I'm currently searching right now for solutions with these limitations but to no avail, plus my Java vocabulary and terminology is admittedly short at the moment :P
import static java.lang.System.out;
import java.util.Scanner;
public class JavaApplication
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
//initialize String array x20
String[] regName = new String[20];
int regCount = 0;
int func = 0;
while (func == 0) //Main Menu Looper
{
out.println("Select function by entering its number.");
out.println("[1] Insert");
out.println("[2] Search");
out.println("[3] Delete");
out.println("[4] Exit");
out.print("Choose Operation: ");
func = kb.nextInt(); //Choose Option
out.print("======================================");
out.print("\n");
switch (func)
{
case 1: //Insertion
//set Array index start
char yesNo;
do
{
//Inserting into arrays loop
out.print("Insert student last name: ");
regName[regCount] = kb.next();
regCount++;
out.print("\n");
//Viewing loop
out.println("Student List: ");
for (int ctrl = 0; ctrl < regCount; ctrl++)
{
out.println(regName[ctrl]);
}
out.print("\n");
//Question loop
out.print("You want to insert again(Y/N):");
yesNo = kb.findWithinHorizon(".", 0).charAt(0);
if (yesNo == 'y' || yesNo == 'Y')
{
yesNo = 'y';
}
} while (yesNo == 'y');
func = 0;
break;
case 2: //Searching
out.print("Enter keyword: ");
String search = kb.next();
boolean found = false;
int searchCount = 0;
for (int ctrl = 0; ctrl < regCount; ctrl++)
{
if (regName[ctrl].equalsIgnoreCase(search)) {
found = true;
out.println(search + " has " + " a match.");
}
else
{
out.println(search + " has " + " not found.");
}
}
out.print("\n");
func = 0;
break;
case 3: //Deleting
out.print("type surname you want to delete: ");
String toDelete = kb.next();
for (int ctrl = 0; ctrl < regCount; ctrl++)
{
if (regName[ctrl].equalsIgnoreCase(toDelete)) {
regName[ctrl] = null;
out.println("Record deleted.");
}
}
out.print("\n");
func = 0;
break;
} //switch
} //while
} //main
} //class
Other answers propose checking for null. But this won't fix your problem. As the rest of your code expects no gaps in your list of students.
Try shifting the names after you delete some of them:
case 3: //Deleting
out.print("type surname you want to delete: ");
String toDelete = kb.next();
int deleted = 0;
for (int ctrl = 0; ctrl < regCount; ctrl++) {
if (regName[ctrl].equalsIgnoreCase(toDelete)) {
out.println("Record deleted.");
deleted++;
}
if(deleted > 0) {
int newCtrl = ctrl + deleted;
regName[ctrl] = (newCtrl < regCount) ? regName[newCtrl] : null;
}
}
regCount -= deleted;
out.print("\n");
func = 0;
break;
This solution assumes that your application allows duplicated entries.
Also I've found that your search operation prints <Name> has not found multiple times even if there is a match. Try changing it like this:
case 2: //Searching
out.print("Enter keyword: ");
String search = kb.next();
boolean found = false;
int searchCount = 0;
for (int ctrl = 0; ctrl < regCount; ctrl++) {
if (regName[ctrl].equalsIgnoreCase(search)) {
found = true;
out.println(search + " has a match : #" + ctrl);
break;
}
}
if(!found) {
out.println(search + " has not found.");
}
out.print("\n");
func = 0;
break;
UPDATE: deleting only first occurrence
case 3: //Deleting
out.print("type surname you want to delete: ");
String toDelete = kb.next();
int deletedIndex = -1;
for (int ctrl = 0; ctrl < regCount; ctrl++) {
if(deletedIndex >= 0) {
int newCtrl = ctrl + 1;
regName[ctrl] = (newCtrl < regCount) ? regName[newCtrl] : null;
} else if (regName[ctrl].equalsIgnoreCase(toDelete)) {
deletedIndex = ctrl;
out.println("Record deleted : #" + deletedIndex);
regCount--;
}
}
out.print("\n");
func = 0;
break;
When searching, check for null before calling equalsIgnoreCase on it.
if (regName[ctrl]!=null && regName[ctrl].equalsIgnoreCase(search)) {
found = true;
out.println(search + " has " + " a match.");
}
else
{
out.println(search + " has " + " not found.");
}
Consider Null checks whenever you code using any data structure for avoiding un-checked exceptions. So you can add the check first which executes first and if true then only proceeds further.
if (regname[ctrl] != null && regName[ctrl].equalsIgnoreCase(search)) {
Hope this helps you solve your problem!
Just do null checks: if (regName[ctrl].equalsIgnoreCase(search)) { can become if (regname[ctrl] != null && regName[ctrl].equalsIgnoreCase(search)) { and so on.
This is equivalent to:
if (regname[ctrl] != null)
{
if (regName[ctrl].equalsIgnoreCase(search))
{
...
Because of the way Java evaluates expressions the second part will only be done if the first is ok - in your case only try to use the array if the value at that index is not null)
If you want to impress your teacher break the insert search and delete into different methods.
I've created two arrays with ArrayList (java), aList1 and aList2. Both will have a mix of doubles and strings. How do I directly compare the individual contents of aList1 to their corresponding individual contents in aList2 For example, if the first value or string in aList1 doesn't match the first value or string in aList2, there should be a message saying that the two don't match. This should go on for every element of each ArrayList.
Thanks!
EDITED:
Here was my initial attempt:
if (!aList1.get(0).equals(aList2.get(0))) {
JOptionPane.showMessageDialog(null, "#1 is incorrect.");
}
if (!aList1.get(1).equals(aList2.get(1))) {
JOptionPane.showMessageDialog(null, "#2 is incorrect.");
}
And so on, by comparing each element from aList1 to aList2, and seeing if they are not equal (whether they be doubles or strings). The corresponding elements and the sizes of the arrays will always be the same. So for example, if aList1 = {0,1,2,3,4,dog}, aList2 could contain {10,2,5,2,cat}.
EDIT: The whole code.
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
public class KevinMath2 {
static File filename = new File("homework.txt");
static ArrayList <Object> aList = new ArrayList <Object> ();
static String homework = " ";
static File filename2 = new File("homework2.txt");
static ArrayList <Object> aList2 = new ArrayList <Object> ();
static String homework2 = " ";
public static void main(String[] args) {
// TODO Auto-generated method stub
String initialInput = JOptionPane.showInputDialog(null, "Would you like to add answers or check answers?");
String again;
char repeat;
do {
switch (initialInput) {
case "Add answers":
char answerfinal1;
String answerPass = JOptionPane.showInputDialog(null, "Please enter the password");
while (!answerPass.equals("Victor")) {
JOptionPane.showMessageDialog(null, "Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
}
do {
do {
String options = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
" answers to add (M/D/Y)");
switch (options) {
case "05/29/15":
while (!homework.isEmpty()) {
homework = JOptionPane.showInputDialog("Please enter the answers, in order. After "
+ "the last answer, leave the next answer"
+ " blank, and click OK.");
if (!homework.isEmpty()) aList.add(homework);
}
try {
FileWriter fw = new FileWriter (filename);
Writer output = new BufferedWriter (fw);
int sz = aList.size();
for (int i=0; i < sz; i++) {
output.write(aList.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
break;
}
} while (!homework.isEmpty());
String final1 = JOptionPane.showInputDialog(null, "Is this correct: " + aList.get(0) + " "
+ aList.get(1) + " " + aList.get(2) + " " +
aList.get(3) + " " + aList.get(4) + "? (Yes or No)");
answerfinal1 = final1.charAt(0);
} while (answerfinal1 == 'n' || answerfinal1 == 'N');
break;
//Need to store the array permanently
case "Check answers": //Need to make it so it stores array of Kevin's answers permanently
char answerfinal2;
String checkPass = JOptionPane.showInputDialog(null, "Please enter the password");
while (!checkPass.equals("Kevin")) {
JOptionPane.showMessageDialog(null, "Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
}
do {
do {
String options2 = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
" answers to check (M/D/Y)");
switch (options2) {
case "05/29/15":
while (!homework2.isEmpty()) {
homework2 = JOptionPane.showInputDialog("Please enter the answers, in order. After "
+ "the last answer, leave the next answer" +
" blank, and click OK.");
if (!homework2.isEmpty()) aList2.add(homework2);
}
try {
FileWriter fw = new FileWriter (filename2);
Writer output = new BufferedWriter (fw);
int sz = aList2.size();
for (int i=0; i < sz; i++) {
output.write(aList2.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
}
} while (!homework2.isEmpty());
String final2 = JOptionPane.showInputDialog(null, "Is this correct: " + aList2.get(0) + " "
+ aList2.get(1) + " " + aList2.get(2) + " " +
aList2.get(3) + " " + aList2.get(4) + "? (Yes or No)");
answerfinal2 = final2.charAt(0);
} while (answerfinal2 == 'n' || answerfinal2 == 'N');
int i = 0; // counter variable
if (aList.size() == aList2.size()) { // Check if both lists are equal
for (Object obj : aList) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a string
if (!aList.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (!aList.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
}
}
i++;
}
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
break;
}
again = JOptionPane.showInputDialog(null, "Would you like to check another answer, or "+
"add another answer? (Yes or No)");
repeat = again.charAt(0);
} while (repeat == 'y' || repeat == 'Y');
JOptionPane.showMessageDialog(null, "Thanks for using this program");
}
}
Try using a for loop to iterate through the first ArrayList and use the counter ('i' in the example below) from that for loop to compare each of the indices that you loop through using the get method provided by ArrayList.
for (int i = 0; i < aList1.size(); i++) {
if (!aList1.get(i).equals(aList2.get(i)))
//output whatever you want it to say
}
Edit: changed to .equals instead of == as suggestion. Good catch.
Compare their datatypes of both the elements of your list if they match then try to compare their contents
For comparing the datatype follow the below mentioned code
int a = 10;
Object o = a;
System.out.println(o.getClass().getSimpleName());
If the datatype matches then try to compare their contents
I agree with coal175s answer but since you say you are mixing types in your arrayLists, you should your the .equals() method to compare them.
if !(aList1.get(i).equals(aList2.get(i))) {
Two things to consider:
Do both ArrayList have the same size
When you're checking elements, must they be the same data type, or can we cast everything to a String and then compare. I will assume they must be the same data type.
Having said that:
public static void main(String[] args) throws Exception {
List<Object> list1 = new ArrayList<>(Arrays.asList(1234, 123.45, "999", 444.444, 999.999));
List<Object> list2 = new ArrayList<>(Arrays.asList("1234", 123.45, "9991", 444.444));
for (int i = 0; i < list1.size(); i++) {
// Only check against parallel list if the index is in the bounds
if (i < list2.size()) {
// Check if the data types match
if (!list1.get(i).getClass().getName().equals(list2.get(i).getClass().getName())) {
System.out.println(String.format("%s: %s != %s: %s",
list1.get(i).getClass().getName(), list1.get(i),
list2.get(i).getClass().getName(), list2.get(i)));
}
// Check if the values match if the datatypes match
else if (!list1.get(i).equals(list2.get(i))) {
System.out.println(String.format("%s != %s", list1.get(i), list2.get(i)));
}
}
}
}
Results (999.999 from list1 does not get checked):
java.lang.Integer: 1234 != java.lang.String: 1234
999 != 9991
You should initialise your List object with Object generics i.e. List<Object> list = new ArrayList<>(); so you can add both String and Double in your list.
Here is an ideal solution to compare two arrays.
List<Object> aList1 = new ArrayList<Object>();
List<Object> aList2 = new ArrayList<Object>();
aList1.add("abc");
aList1.add(25);
aList2.add("abc");
aList2.add(25);
int i = 0; // counter variable
if (aList1.size() == aList2.size()) { // Check if both lists are equal
for (Object obj : aList1) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a string
if (aList1.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
} else {
JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (aList1.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
} else {
JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
}
}
if (obj.getClass() == Integer.class) {
JOptionPane.showMessageDialog(null, "Integer is found");
}
i++;
}
}
Your code is very hard to follow, when you write a program please try to follow Java conventions.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class KevinMath2 {
static File filename = new File("homework.txt");
static ArrayList<Object> aList = new ArrayList<Object>();
static String homework = "";
static File filename2 = new File("homework2.txt");
static ArrayList<Object> aList2 = new ArrayList<Object>();
static String homework2 = "";
static String answerPass = "";
static final int TOTAL_QUESTIONS = 5;
public static void main(String[] args) {
String initialInput = JOptionPane.showInputDialog(null,
"Enter Add answers / Check answers to continue");
switch (initialInput) {
case "Add answers":
answers("Victor", aList, filename);
int choice = JOptionPane.showConfirmDialog(null,
"Would you like to compare your answers?", "Yes/No", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
answers("Kevin", aList2, filename2);
checkAnswers(aList, aList2);
}
break;
// Need to store the array permanently
case "Check answers": // Need to make it so it stores array of
// Kevin's answers permanently
answers("Kevin", aList2, filename2);
if (aList.size() == 0) {
JOptionPane.showMessageDialog(null,
"Please add answers to compare.");
answers("Victor", aList, filename);
}
checkAnswers(aList, aList2);
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
break;
}
// exit the program
JOptionPane.showMessageDialog(null, "Thanks for using this program");
}
public static void answers(String pass, ArrayList<Object> list, File f) {
answerPass = JOptionPane.showInputDialog(null,
"Please enter the password");
// validate user
while (!answerPass.equals(pass)) {
JOptionPane.showMessageDialog(null,
"Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null,
"Please enter the password.");
}
// add answers
String final1 = "";
do {
clearFile(f);
list.clear();
// validate the date of the answers
String options = JOptionPane.showInputDialog(null,
"Enter the date of the desired" + " answers (MM/DD/YY)");
// add your answers
enterAnswers(options, list, f);
// verify the answers
final1 = JOptionPane.showInputDialog(null, "Is this correct: "
+ list.get(0) + " " + list.get(1) + " " + list.get(2) + " "
+ list.get(3) + " " + list.get(4) + "? (Y/N)");
} while (final1.charAt(0) == 'n' || final1.charAt(0) == 'N');
}
public static void enterAnswers(String options, ArrayList<Object> list,
File f) {
switch (options) {
case "05/29/15":
boolean valid = false;
for (int i = 0; i < 5; i++) {
while (!valid) {
homework = JOptionPane
.showInputDialog("Please enter your answer for question "
+ (i + 1));
if (!homework.isEmpty())
valid = true;
}
list.add(homework);
valid = false;
}
writeFile(f, list); // write the answers to a file
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
}
}
public static void writeFile(File filename, ArrayList<Object> list) {
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
for (int j = 0; j < list.size(); j++) {
output.write(list.get(j) + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Oops! I cannot create that file.");
}
}
public static void clearFile(File filename) {
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
output.write("");
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Oops! I cannot create that file.");
}
}
public static void checkAnswers(ArrayList<Object> a, ArrayList<Object> b) {
int i = 0; // counter variable
if (a.size() == b.size()) { // Check if both lists are
// equal
for (Object obj : a) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a
// string
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
if (obj.getClass() == Integer.class) { // or an integer
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
i++;
}
}
}
}
Answer is based on the assumption
Add answers to an ArrayList.
Compare your answers from another ArrayList.
You aren't comparing your answers from the written files.
You are writing your 'Added answers' to a file, but you aren't reading that file back again to compare against your 'Check answers'. To do that, write another method to read in the homework.txt file, store each line to your aList, then compare against aList2.
My task is to enter names into an array. If the name has already been entered, the program must alert about that and offer to reenter the player under the same number.
This is my code:
public void enterNames() {
for (int i=0; i<nameOfPlayers.length; i++)
{
do
{
// isDuplicate is a Boolean initialized to false
System.out.println("CHECK": + isDuplicate);
System.out.println("Enter player " + (i+1) + ":");
nameOfPlayers[i] = in.next();
for (int k=0; k<nameOfPlayers.length; k++)
{
if (k!=i && nameOfPlayers[i].equals(nameOfPlayers[k]))
{
isDuplicate = true;
break;
}
}
} while (isDuplicate = false);
}
}
Interesting, even when I enter a duplicate value, it is caught and assigns true to isDuplicate, but when it returns to the beginning of the while loop, the value is false again ("CHECK: false").
Looks like an easy task, but I am caught...
Also, I did not want to use HashSet and wanted to use only Array.
Thanks a lot!
EDIT:
Thanks to others, I rewrote the code to the following:
public void enterNames() {
List<String> nameOfPlayersList = new ArrayList<String>();
int i = 0;
for (i=0; i<numberOfPlayers;)
{
while(true)
{
System.out.println("Enter player " + (i+1) + ":");
String input = in.next();
if(!nameOfPlayersList.contains(input))
{
nameOfPlayersList.add(input);
i++;
break;
}
System.out.println("Player " + input + " already exists, please retry");
}
}
}
Answer reformed, used List to add more and more elements without pre defined size.
changed while (isDuplicate == false); to while (!isDuplicate);
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> nameOfPlayers = new ArrayList<String>();
boolean isDuplicate = false;
int i = 0;
do {
System.out.println("Enter player " + (i + 1) + ": or Q for Quit");
String input = scanner.next();
if (!input.equalsIgnoreCase("Q")) {
if (nameOfPlayers.contains(input)) {
isDuplicate = true;
} else {
nameOfPlayers.add(input);
isDuplicate = false;
}
System.out.println("CHECK : " + isDuplicate);
} else {
break;
}
i++;
} while (!isDuplicate);
}
Enter player 1: or Q for Quit
ankur
CHECK : false
Enter player 2: or Q for Quit
singhal
CHECK : false
Enter player 3: or Q for Quit
ankur
CHECK : true
The problem you are having is because of the
} while (isDuplicate = false);
it should be (mind the double ==)
} while (isDuplicate == false);
Apart from that your code is quite inefficient. You would probably do much better with two Arrays if that is really what you want, otherwise a linked list would be best.
Your while is incorrect, this
while (isDuplicate = false);
assigns false to isDuplicate which has a side-effect of also evaluating to false. You watned something like
while (isDuplicate == false);
or the shorter
while (!isDuplicate);