Java phonebook with stored file - java

I wrote a program to ask user to input names, numbers, and any notes associated. I then am trying to allow the user to search any name and have that persons info displayed. I also want to be able to store and read a file from the phone book. I am having trouble with the store/read as well as recognizing a separate class that was created. I'm guessing I just have syntax errors because I am still new to programming. Thanks for any help!
public class Entry {
public String name, num, notes;
name = a;
num = b;
notes = c;
}
import java.util.*;
import java.io.IOException;
public class Phonebook {
static int amount;
static Scanner input = new Scanner(System.in);
static file f ("FileName");
public static Entry[] pb = new Entry[200];
public static void main(String[] args) {
String ask;
char letter;
amount = 0;
do{
System.out.println("Enter a command");
ask = input.nextLine();
letter = Character.toLowerCase(ask.charAt(0));
switch (letter) {
case 'e': System.out.println(add()); break;
case 'f': System.out.println(find()); break;
case 'l': System.out.println(list()); break;
case 'h': System.out.println(help()); break;
case 'q': System.out.println("Quit"); break;
default: System.out.println("Not a valid command"); break;
}
} while (letter != 'q');
}
public static void help() {
System.out.println("Use e for enter");
System.out.println("Use f for find");
System.out.println("Use l for list");
System.out.println("Use h to see this menu again");
}
public static void add() {
String a, b, c;
System.out.println("Enter a name: ");
a = input.nextLine();
System.out.println("Enter a number: ");
b = input.nextLine();
System.out.println("Enter any notes: ");
c = input.nextLine();
}
public static void list() {
for (int i = 0; i < amount; i++)
System.out.println(pb[i].name + pb[i].num + pb[i].notes);
}
public static void find () {
String f;
boolean found;
found = false;
System.out.println("Who?");
f = input.nextLine();
for (int i = 0; i < amount; i++); {
if (f.equals((pb[i].name))) {
System.out.println(pb[i].name + pb[i].num + pb[i].notes);
found = true;
} if (!found)
System.out.println("Not found");
}
}
public static void WritePhoneBook (String f) throws Exception {
PrintStream p = new PrintStream(f);
for (int i = 0; i < amount; i++) {
p.println(pb[i].name + pb[i].num + pb[i].notes);
p.close();
System.out.println("Phonebook stored.");
}
}
}
I'm not sure how to show the errors I received but they are:
file cannot be resolved to type
i cannot be resolved
PrintStream cannot be resolved,
Syntax error at FileName,
method println(boolean) in type PrintStream is not applicable.

Since the code does not even compile, let me look at the compilation errors only (and not the logic):
static file f ("FileName");
It is File (uppercase F). In java, by convention, all classes start with a uppercase letter.
the statement is not correctly constructed. It is supposed to be
static File f = "FileName";
or something like this. Note that you need to import java.io.File as well.
System.out.println(add());
...
the methods add, find... return void. Meaning, they return nothing. System.out.println() does not operate on nothing.
PrintStream p = new PrintStream(f);
you have not imported java.io.PrintStream.
i cannot be resolved to a variable
This is because of the ; at the end of the for.
for (int i = 0; i < amount; i++) { //note: no ; after the )
if (f.equals((pb[i].name))) {
In Entry.java
the class lacks a method. Assignments like name = a; are not valid outside a method, Also a, b and c are not defined.
It looks like you are very new to Java. You may want to use a IDE like eclipse so that you get a better picture of errors and recommended fixes and you can fix them faster. However, you will learn more and learn better if you use javac from the command line (which is what I think you are doing). Of course you need to do a lot of reading and learning.
PS: Such questions will most likely be downvoted to oblivion because it shows a lack of effort from the OP's part to find solutions. I happened to have a few minutes today, but no one has the time to look into this level of detail when there seems to be no effort from OP.
OP = Original Poster = the person that asked the question

Related

Incompatible operand types Scanner and String?

I keep getting the following errors:
Incompatible operand types Scanner
and String
Incompatible operand types int and
String
before I added the int op = Integer.valueOf(operator) line it kept giving me errors when I would name my cases. I'm still very new it's the second code I've written for my class so please keep the explanation simple if at all possible (there is also a calculator class not shown here if there's any confusion about that) :
//change the package name to calculatorClass///////////////
import java.util.Scanner;
public class assignmentB {
public static String String(int y,int x, String name, String str) throws Exception {
if (y < 1)
throw new Exception("Value must be larger than 0.");
if (x < 1)
throw new Exception("Value must be larger than 0");
return name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator c1 = new Calculator();
Scanner input = new Scanner(System.in);
c1.name = "The total is $";
try {
} catch (Exception e1){
System.out.println(e1);
}
{
int x, y, s, a, m;
String name1;
System.out.println("Red River College");
System.out.println("Custom Calculator");
System.out.println("Enter first value: ");
x = input.nextInt();
System.out.println("Enter second value: ");
y = input.nextInt();
System.out.println("Enter operation(a=Add, s=Subtract, m=multiply): ");
String operator = input.nextLine();
int op =Integer.valueOf(operator);
switch (op) {
case 1:
if (input == "s") {
System.out.println(c1.name + c1.subtract(x,y));
}
case 2:
if (input == "a") {
System.out.println(c1.name + c1.add(x,y));
}
case 3:
if (input == "m") {
System.out.println(c1.name + c1.multiply(x,y));
}
}
}
}
}
```
You have defined input to be a Scanner, with this line:
Scanner input = new Scanner(System.in);
You can then use input to do scanner things, as you're doing here:
x = input.nextInt();
So far so good.
But later in the code, you do this (and a few variations that are similar):
if (input == "s") {
...
}
This isn't valid. The Java compiler is telling you that it will not allow you to use == to compare a Scanner (that is, input) against a String (which in this example is "s"). The compiler is giving you an error to say: input == "s" isn't allowed.
It isn't clear what your intent is (that is, how you want the code to actually behave), but the issue is definitely with those three if statements. Each is attempting to compare a java.util.Scanner with a java.lang.String (one is "s", one is "a", the last is "m"). So you'll need to fix those to do whatever it is you're trying to do.
As a guess, maybe you want to read a new String input from the scanner, and then compare that to "s", etc.? If so, that could look something like below. Note that to compare strings you should use equals() (don't use == to compare strings, or any other objects).
String newString = input.next();
switch (op) {
case 1:
if (newString.equals("s")) {
System.out.println(c1.name + c1.subtract(x, y));
}
...
}

How can I get a multidimensional array to loop with string input?

Basically I'm making a program that reads from a multidimensional array to display it's corresponding information. What I want to do is make it so the while loop will continue to tell me I'm putting in the wrong class ID's until you put in a correct Class ID.
do
{
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for(int x = 0; x <= classes.length; ++x)
{
if(name.equals(classes[x][0]))
{
i = true;
System.out.println("Course info: " + classes [x][0]);
System.out.println(classes[x][1]);
System.out.println(classes[x][2]);
x = classes.length;
}
else{
System.out.println("Wrong course id");
i = false;
input.next();
}
}
}
while (!(i));
System.out.println("This is the end of the program!");
System.exit(0);
First of all, try to keep good naming conventions. i is bad name for a flag variable. Name it boolean found or something. It will not only help other people read and understand your code, but it will help you in order find the logic you have to use as well.
Now, since you have input.next(); in else part, i guess you want to ask again for user input, until a something is found. So, a name = input.nextLine(); is required again in order to take new input. But in your case the else part can be removed completely and let the do-while do the work.
An example:
public class Classes {
private static final String[][] CLASSES = { { "Maths", "info" }, { "History", "info" }, { "Biology", "info" } };
public static void main(String[] args) {
boolean found = false;
String name;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for (int i = 0; i < CLASSES.length; i++) {
if (name.equals(CLASSES[i][0])) {
found = true;
System.out.println("Course info: " + CLASSES[i][0]);
System.out.println(CLASSES[i][1]);
// System.out.println(CLASSES[i][2]); //My CLASSES array, does not have 3 columns
break;// exit for loop
}
}
if (!found)
System.out.println("Wrong course id");
} while (!found);
input.close();
System.out.println("This is the end of the program!");
}
}

java program won't output words

I'm trying to convert a text to nato alphabet but I can't figure out what is the problem. I tried to split the text into characters and then put it in arrays then in a for loop to test if the character is equal and write the correct word
Sample Text : hello
Result: hotel echo lima lima oscar
package text2nato;
import java.util.Scanner;
public class Text2nato {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to conver to nato :");
String text = scan.nextLine();
char[] carray = text.toCharArray();
for(int i=0;i<carray.length;i++){
if("a".equals(carray[i])){
System.out.print("alpha");
}if("b".equals(carray[i])){
System.out.print("brabo");
}if("c".equals(carray[i])){
System.out.print("charlie");
}
if("d".equals(carray[i])){
System.out.print("delta");
}if("e".equals(carray[i])){
System.out.print("echo");
} if("f".equals(carray[i])){
System.out.print("foxtrot");
}if("g".equals(carray[i])){
System.out.print("golf");
} if("h".equals(carray[i])){
System.out.print("hotel");
} if("i".equals(carray[i])){
System.out.print("india");
} if("j".equals(carray[i])){
System.out.print("juliet");
} if("k".equals(carray[i])){
System.out.print("kilo");
} if("l".equals(carray[i])){
System.out.print("lima");
} if("m".equals(carray[i])){
System.out.print("mike");
} if("n".equals(carray[i])){
System.out.print("november");
} if("o".equals(carray[i])){
System.out.print("oscar");
} if("p".equals(carray[i])){
System.out.print("papa");
} if("q".equals(carray[i])){
System.out.print("quebec");
} if("r".equals(carray[i])){
System.out.print("romeo");
} if("s".equals(carray[i])){
System.out.print("sierra");
} if("t".equals(carray[i])){
System.out.print("tango");
} if("u".equals(carray[i])){
System.out.print("uniform");
} if("v".equals(carray[i])){
System.out.print("victor");
} if("w".equals(carray[i])){
System.out.print("whiskey");
} if("x".equals(carray[i])){
System.out.print("x-ray");
} if("y".equals(carray[i])){
System.out.print("yankee");
} if("z".equals(carray[i])){
System.out.print("zulu");
}
}
}
}
Others have already pointed out in the comments that you're comparing a string to a char, which will never be equal. By way of illustration, try the following program:
public class Demo {
public static void main(String[] args) {
Boolean x = "b".equals('b');
System.out.println(x);
}
}
The result will be false. You could argue that this is a bit of a "gotcha" in Java, but that's a matter of opinion.
Also, if you have that many if statements in a row, it's a pretty good hint that something's probably gone wrong. At a minimum, a switch statement would be far easier to read:
package text2nato;
import java.util.Scanner;
public class Text2nato {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the text to convert to nato: ");
String text = scan.nextLine();
// You might want to consider converting the whole string to lowercase to make this case-insensitive
char[] carray = text.toCharArray();
for(int i=0; i < carray.length; i++){
if (i > 0)
{
// We need to prepend a space here
System.out.print(" ");
}
switch (carray[i])
{
case 'a': System.out.print("alpha"); break;
case 'b': System.out.print("bravo"); break;
// The rest of your cases go here
// Be sure to handle the case where the user enters something invalid
default: System.out.print(carray[i] + " is not a valid lowercase letter"); break;
}
}
}
}
As you can see, indenting the code properly, adding some extra whitespace, and using a switch statement makes this much easier to read.

Need advice on code java efficiency

I am new to java programming and I just created a calculator program and it seems to work fine but other programmers seem to use "parsing a lot" in their calculator programs. Just wanted to ask whether I'm taking a wrong approach and might run into problems in the future using this kind of logic.Thanks.
class Refresh {
private final String a;
private final String b;
private final String c;
private final String d;
private double x, y;
public Refresh() {
a = "Enter the first number: ";
b = "Enter the function; ";
c = "Enter the second number: ";
d = "The result is: ";
}
public void types() {
Scanner typ = new Scanner(System.in);
try {
System.out.println(a);
x = typ.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
System.exit(1);
}
System.out.println(b);
String func = typ.next();
try {
System.out.println(c);
y = typ.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
System.exit(1);
}
switch (func) {
case "+":
System.out.println(d + (x + y));
break;
case "-":
System.out.println(d + (x - y));
break;
case "/":
if (y == 0) {
System.out.println("Cannot divide by zero!");
} else {
System.out.println(d + (x / y));
}
break;
case "*":
System.out.println(d + (x * y));
break;
default:
System.out.println(func + " is not valid function");
}
}
public static void main(String[] args) {
Refresh fin = new Refresh();
fin.types();
}
}
Your program is fine as a demo or as a step in learning Java, but you probably would not use it as a production program. The reason is that your code assumes a command line interface (static void main(), Scanner, System.out.println()).
Users are used to graphical solutions nowadays. They expect the input and output to be given in a graphical front end and the calculations should be done in separate logic.
In this view, I would restructure your program in 3 parts:
A back end class which does the calculations (the Calculator class in the following sample code)
A front end class (called SimpleFrontEnd below) which builds on your code, but could later be replaced with e.g. a web interface
Data objects to communicate between back end and front end (the Calculation class below to send info from the front end to the back end)
Having these 3 parts, you can modify them independently of each other. You could decide that in the front end you only enter a single String, which is then parsed before being sent to the back end.
I would probably NOT use a single String in the front end that needs to be parsed, but a JSON object that maps directly to the Calculation class below, for the following reason: the front end can easily modify the operands and operator of the JSON object independently of each other, whereas modifying a string that has to be parsed is more complex.
Here is sample code that separates front end from back end:
public class Calculation {
private double leftOperand;
private String operator;
private double rightOperand;
public double getLeftOperand() {
return leftOperand;
}
public void setLeftOperand(double leftOperand) {
this.leftOperand = leftOperand;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public double getRightOperand() {
return rightOperand;
}
public void setRightOperand(double rightOperand) {
this.rightOperand = rightOperand;
}
}
public class Calculator {
public double calculate(Calculation calculation) {
switch (calculation.getOperator()) {
case "+":
return calculation.getLeftOperand() + calculation.getRightOperand();
case "-":
return calculation.getLeftOperand() - calculation.getRightOperand();
case "/":
if (calculation.getRightOperand() == 0) {
throw new IllegalArgumentException("Cannot divide by zero!");
}
return calculation.getLeftOperand() / calculation.getRightOperand();
case "*":
return calculation.getLeftOperand() * calculation.getRightOperand();
default:
throw new IllegalArgumentException(String.format("%s is not valid function", calculation.getOperator()));
}
}
}
public class SimpleFrontEnd {
public static void main(String[] args) {
try {
//1. input, could be later replaced with a front end
Scanner typ = new Scanner(System.in);
System.out.println("Enter the first number: ");
double x = typ.nextDouble();
System.out.println("Enter the function: ");
String func = typ.next();
System.out.println("Enter the second number: ");
double y = typ.nextDouble();
//2. store input in an data object that will be sent to the back end (later on, a web interface could send this as a JSON)
Calculation calculation = new Calculation();
calculation.setLeftOperand(x);
calculation.setOperator(func);
calculation.setRightOperand(y);
//3. retrieve the result from the back end
Calculator calculator = new Calculator();
try {
double result = calculator.calculate(calculation);
System.out.println(String.format("The result is: %f", result));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
} catch (InputMismatchException e) {
System.out.println("Please use only numbers!");
}
}
}
Parsing just means to scan a group of characters and then separate them into their own structures (tokenize them).
String aStr = "10";
The variable aStr would be of type String. You could then parse the string.
int aInt = Integer.parseInt(aStr);
Just for your information, Java has a built in calculator library.
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
String result = "100/10";
System.out.println(scriptEngine.eval(result));
Alright, this is actually very basic example. And honestly you did a great job. and even better at asking this question at this time. Usually people ignore efficiency during the learning process and get too late.
Why do they do parsing?
If you donot know about the below, then you should probably try reading more on it.
Scanner reads all the key inputs from users. Lets take example
Enter a number> 12
Scanner will hold 12\n
Now you see that? scanner is holding on to just number it is actually hold on to a string. which contains 12 and \n
When you ask scanner nextDouble it will just give you 12.
But then it is still holding on to that \n so the next string input, the string \n will be assigned.
By parsing, you will ignore this issue. And you will have better control over user input.

Rerun Main method from Main Method

Basically the last thing I need to do for this Math Quiz I have to program, I have to ask the user if they would like to answer more problems, if yes, rerun everything in the Main Method. If no, print goodbye. The no is easy, but I'm unsure how to tell it to rerun the main method if they say yes. Here is the code in my main method.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int digit = 0;
String result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
int numberOfProblems = amountOfProblems();
for (int i = 0; i < numberOfProblems; i++) {
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println("Enter your answer to the following problem: \n" +
number1 + result1 + number2);
int correctAnswer = getCorrectAnswer(number1, result1, number2);
int userAnswer = getUserAnswer();
CheckandDisplayResult(correctAnswer, userAnswer);
}
System.out.println("Would you like to solve more probelms(Y/N)? ");
String moreProblems = in.next();
if ("Y".equals(moreProblems)){
digit = 0;
result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
numberOfProblems = amountOfProblems();
for (int i = 0; i < numberOfProblems; i++) {
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println("Enter your answer to the following problem: \n" +
number1 + result1 + number2);
int correctAnswer = getCorrectAnswer(number1, result1, number2);
int userAnswer = getUserAnswer();
CheckandDisplayResult(correctAnswer, userAnswer);
}
System.out.println("Would you like to solve more probelms(Y/N)? ");
moreProblems = in.next();
if ("Y".equals(moreProblems)){
}
System.out.println("Thank you for taking this quiz, Goodbye!");
}
Now I have tried something like,
if "Y".equals(moreProblems)){
copy and past the main method
}
But that has the error of requiring an infinite loops as you'd have to have the more problems statement in every if of yes, meaning it would never end coding wise, you would keep copying and pasting forever.
You could enclose all the code you want to "re-run" in a while loop:
boolean run = true;
while (run) {
// Here your code
// Here input if user want to re-run
if (getUserChoice("").equals("NO"))
run = false;
}
Alternative to what others have suggested, this is the method I prefer:
while(true) {
//do all your stuff
if(/*some exit condition*/) { break; }
}
What you can do is move everything in main() into another static method, call it interact(). Then in main(), just have logic which calls interact() as long as the user wants to interact with your program. In other words, put the math quiz into one method, and the business of presenting the quiz into main(). Your program will be easier to read and easier to modify further, if needed.
Put all of it in a big do-while loop:
boolean more = false;
do {
// all your code
more = "Y".equals(moreProblems);
} while (more);
Or provided your Scanner is declared outside the loop you can just:
do {
// all your code
} while ("Y".equals(in.next()));
I guess this prototype might help you
import java.util.Scanner;
public class MathsClass {
public static void main(String[] args){
MathsClass object = new MathsClass();
while(object.response())
object.mathsQuiz();
}
public void mathsQuiz(){
//your quiz functionalities
System.out.println("Add two nos");
}
public boolean response(){
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean response = scanner.nextBoolean();
return response;
}
}

Categories