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.
Related
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 have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.
My code compiles and I have two text files that need to be read from the program but when I run the program I get the following error: the menuItems.txt contains:
Churro
Ice Cream
Hamburger
Cheese burger
Turkey Leg
Corn Dog
Pizza
Funnel Cake
Soda
The priceItems contains:
5
4
9
10
13
7
9
6
5
All Files are located on my desktop
Error: Could not find or load main class Disneyland
package com.Kassie$;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class Disneyland {
//Initialize the items 1D array
public static String[] getItems() {
try {
//Read from file
String[] aItems = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuItems.txt")))
.split("\n");
return aItems;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Initialize the items 1D array
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Find the character's location
public static String findLocation(String[][] storedValue, String name) {
for(int i = 0; i < storedValue.length; i++) {
if(storedValue[i][0].equals(name)) {
return (storedValue[i][1]);
}
}
return null;
}
public static void main(String[] args) {
char choice = ' ';
int totPrice = 0;
Scanner s = new Scanner(System.in);
String[][] characterLocation = {{"Mickey Mouse","Main Street USA"},
{"Minnie Mouse", "Toon Town"},
{"Goofy","Frontier Land"},
{"Pluto","Tomorrowland"},
{"Belle","Fantasyland"},
{"Jasmine", "Adventureland"}};
System.out.println("Do you like to know the "
+ "Disney Character's location(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Enter the name of the character");
String aName = s.next();
String location = findLocation(characterLocation,aName);
if( location != null) {
System.out.println("The character is located in " + location);
}
else {
System.out.println("Sorry! The character you are looking for "
+ "is not in park today");
}
}
String[] items = getItems();
String[] prices = getPrices();
choice = ' ';
System.out.println("Would you like to view the menu?(Y/N)");
choice = s.next().charAt(0);
if(choice == 'N' || choice == 'n') {
System.exit(0);
}
while(choice == 'Y' || choice == 'y') {
for(int i = 0; i < items.length; i++) {
System.out.println("Enter " + (i+1) + " for " + items[i]);
}
int option = s.nextInt();
System.out.println("Item : " + items[option-1]);
System.out.println("Price : " + prices[option-1]);
totPrice = totPrice + Integer.parseInt(prices[option-1]);
System.out.println("Do you want to order more(Y/N)?");
choice = s.next().charAt(0);
}
System.out.println("Are you an Annual Pass Holder?(Y/N)?");
choice = s.next().charAt(0);
if(choice == 'Y' || choice == 'y') {
System.out.println("Your bill amount due : $" + ((double)totPrice -
((double)(totPrice*15))/100));
System.exit(1);
}
System.out.println("Your bill amount due : $" + totPrice);
}
}
You need to escape the dollar sign in your path.
To match a dollar sign, use "\$"
public static String[] getPrices() {
try {
//Read from file
String[] aPrices = new String(Files.readAllBytes
(Paths.get("src/com/Kassie\\$/desktop/menuPrices.txt")))
.split("\n");
return aPrices;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I have written a RPN Calculator in Java, but I am struggling to get my code to exit when the user enters a blank line instead of an equation. The program needs to loop until this blank line is entered.
Below is my source code.
$`import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
import java.io.FileNotFoundException;
public class Calculator {
private static Scanner input;
public static int invalidlines = 0;
public static int validlines = 0;
public static ArrayList<String> validList = new ArrayList<String>();
public void FileNotFoundException(){
System.out.println("Please enter a valid expression!");
}
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
}
catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
}
else
{
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
}
else
{
return false;
}
}
}
public static void main(String[] args) throws IOException {
input = new Scanner(System.in);
String keyboardInput = new String();
String currentLine = new String();
Scanner kbScan = new Scanner(System.in);
System.out.println("Please press the letter F for file input or K for keyboard input");
String inputString = new String(input.nextLine());
int answer = 0;
while (true){
if (inputString.equals("K") || inputString.equals("k")) {
System.out.println("Please enter an equation");
keyboardInput = kbScan.nextLine();
}
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
if (inputString.equals("") || inputString.equals(""));
{
System.exit(0);
}
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch(equation[2]) { // This case switch checks the third position of the string to decide which operator is being used. It then works out the answer and breaks to the next instruction
case("+"):
answer = num1 + num2;
break;
case("-"):
answer = num1 - num2;
break;
case("/"):
answer = num1 / num2;
break;
case("*"):
answer = num1 * num2;
break;
}
System.out.println("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
System.out.println("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
}
else{
System.out.println("The equation you entered is invalid");
}
if (inputString.equals("f") || inputString.equals("F")) {
try{
//Open the file
System.out.println("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
System.out.println("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
break;
case("-"):
answer = val1 - val2;
break;
case("/"):
answer = val1 / val2;
break;
case("*"):
answer = val1 * val2;
break;
}
System.out.println("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Please Enter a valid file name");
}
}
}
}
}
Just use following code to check the variable in which you are taking the user input,whether it's empty or not?
I am assuming you are taking in a variable called inputString,then the code should be-
if(inputString.isEmpty())
{
System.exit(0);
}
maybe you should use break instead of System.exit(0).
Also, I would check for empty input as soon as I read the input.
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);