Guys I really need some help here :(
I need to create a contact list in which I need to be able to create, edit, delete, show and search contacts.
But after I enter number 1 (to include a new number) and type the name and number, it goes to an infinite loop and I was wondering if you guys could help me figure out why it's happening and how to fix it.
I'm pretty sure it has something to do with this block at the end of the code:
while (op!=6)
System.out.println();
But when I remove it, the loop just doesn't happen. Instead of an infinite loop it just doesn't loop at all. I've been trying for literally hours now and I can't seem to figure it out at all.
(also I'm not allowed to use array list here)
Sorry for my english and thank you already!
import java.util.Scanner;
public class Vetor45 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] name = new String[1000];
String nname, auxname;
int[] tel = new int[1000];
int ntel, op, cont, i, k, auxtel;
cont = 0;
k = 0;
for (i = 0; i < 1000; i++) {
name[i] = "Empty";
tel[i] = 0;
}
{
System.out.println("contact list:");
System.out.println("1. include a new number");
System.out.println("2. edit a number");
System.out.println("3. delete a number");
System.out.println("4. print all numbers");
System.out.println("5. search by name");
System.out.println("6. exit");
System.out.println("Option:");
op = scanner.nextInt();
System.out.println("");
if (op == 1) {
if (k <= 999) {
while (name[k] != "Empty") {
k++;
}
System.out.println("Enter a name:");
name[k] = scanner.next();
System.out.println("Enter a number:");
tel[k] = scanner.nextInt();
k++;
}
else {
System.out.println("complete");
}
}
else {
if (op == 2) {
i = 0;
System.out.println("enter a name:");
nname = scanner.next();
while (nname != name[i] && i < k - 1) {
i++;
}
if (nname == name[i]) {
System.out.println("enter the new number:");
ntel = scanner.nextInt();
tel[i] = ntel;
}
else {
System.out.println("name not registred");
}
}
else {
if (op == 3) {
k--;
i = 0;
System.out.println("enter a name:");
nname = scanner.next();
while (nname != name[i] && i < k) {
i++;
}
if (nname == name[i]) {
name[i] = "Empty";
tel[i] = 0;
} else {
System.out.println("name not registred");
}
}
else {
if (op == 4) {
for (i = 0; i <= k - 2; i++) {
for (cont = i + 1; cont <= k - 1; cont++) {
if (name[i] == name[cont]) {
auxname = name[i];
name[i] = name[cont];
name[cont] = auxname;
auxtel = tel[i];
tel[i] = tel[cont];
tel[cont] = auxtel;
}
}
}
System.out.println("phone list:");
for (i = 0; i < 1000; i++) {
if (name[i] != "Empty") {
System.out.println("name: " + name[i]);
System.out.println("tel: " + tel[i]);
}
}
}
else {
if (op == 5) {
i = 0;
System.out.println("enter a name:");
nname = scanner.next();
while (nname != name[i] && i < k) {
i++;
}
if (nname == name[i]) {
System.out.println("name: " + nname);
System.out.println("Tel: " + tel);
} else {
System.out.println("name not registred");
}
} else {
if (op == 6) {
System.out.println("exiting");
} else {
System.out.println("option not available");
}
}
}
}
}
}
System.out.println();
}
while (op != 6)
System.out.println();
}
}
You don't even have a do/while loop in this code, here is what a do/while loop loops like:
do{
//loop
}while(op != 6); //don't forget semi colon
You need to develop some standard for braces, and such. As it is right now, it's really hards to read this code.
Yes, as surmised by both you and #Amadan, the while (op != 6) is the problem. In general, when you're looping, something in the loop has to modify something in the condition you're looping on or something in the loop has to modify the normal control flow (so a return, break, etc.), so when you see while (op != 6), you should think "op is the only variable in the condition, so something inside the loop has to modify op or there has to be some other way to get out of the loop."
I think what you want to do is put a do before the big block before the while and then have the while at the end of the block, so you're doing this:
do
{
...
op = scanner.nextInt();
...
} while (op != 6);
That will read an int into op, do some stuff with it, and then bail out if the user entered 6.
The loop while (op!=6) is being run without any changes to op being allowed inside it.
//Rest of the code
System.out.println();
}
while (op!=6)
System.out.println();
}
}
The loop should be evealuated at the beginning of what you need to execute and have everything you want to do in the loop (including changing op) inside it:
for (i=0; i<1000; i++)
{name[i]="Empty"; tel[i]=0;}
while (op!=6)
{
System.out.println("contact list:");
//Rest of the code
You will probably have to move some braces round when you do this also. But I'm not going to go through the whole thing/ that's outside the scope of the question.
Related
I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}
I am a beginner programming, I want to ask multiple questions using arrays and tell the user whether he got each question right or wrong, which I managed to get it running, but now how do I implement the code so that the user will only have up to 3 attempts to get a question right.
for(int n = 0; n <QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
So if I correctly understand your goal, you've a list of questions, and whilst they have made fewer than three failed attempts at them, you would like for the users to get to try and answer them?
Using your existing style, you could do something like
for(int n = 0; n < QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Depending how the data is displayed and transferred and concerns regarding security etc, it would make for easier to manage code to have a QuestionAnswer object that contains the question and the answer, as well as a method for what constitutes a valid answer (e.g. case insensitive, or maybe you want to accept multiple words etc, whatever works for your case), so you could end up with code that looks like the below.
for(int i = 0; i < questionAnswerArray.length; i++)
{
QuestionAnswer qa = questionAnswerArray[i];
System.out.println("Question " + (i+1));
System.out.println(qa.getQuestion());
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (qa.isValidAnswer(ans))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Try to use while with the number of attempt you need:
for (int n = 0; n < QArray.length; n++) {
System.out.println("Question" + (n + 1));
System.out.println(QArray[n]);
int attempt = 3;
while (attempt > 0) {
System.out.print("Please enter the answer: ");
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
break;
} else {
System.out.println("That is incorrect!");
}
attempt--;
}
}
Put a second loop inside the first.
for(int n = 0; n < QArray.length; n++) {
boolean correct = false;
for(int m = 0; m < 3; m ++) {
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
correct = true;
break;
} else {
System.out.println("That is incorrect!");
}
}
if(!correct) {
//something
} else {
//something else
}
}
Note the break;. That command will exit the inner for-loop (which contains the scanner input) when a correct answer is submitted. If the user doesn't get the right answer in 3 tries, the for-loop will end by reaching the end of its counter.
My code is currently unable to start at the beginning of the program which is 'Please type in...'. I want the code to be able to return to the beginning statement everytime choice 1 or 2 is executed. The while statement does not satisfy this as I cant use the while statement before 'choice' is declared. I understand that I'm suppose to be using a do while loop but everytime I try to implement it - it gives me an error with braces.
The following is a snippet of my code:
System.out.println("Please type in 1 for a customer to view their portfolio, 2 to trade stocks or 3 to exit the application");
int choice = Integer.parseInt(input.nextLine());
{
while (!"3".equals(choice));
{
if (choice == 1) {
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice == 2) {
String StockSelect = "Please select a stock";
for (int i = 0; i < mystocks.length; i++) {
// [i] is the element we are accessing
StockSelect += " " + i + " " + (mystocks[i].getSymbol());
}
System.out.println(StockSelect);
int stockchoice = Integer.parseInt(input.nextLine());
System.out.println("Select 1 to buy or 2 to sell?");
int choice2 = Integer.parseInt(input.nextLine());
if (choice2 == 1) {
System.out.println("How many stocks would you like to buy ");
int volumebought = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() - (volumebought * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
if (choice2 == 2) {
System.out.println("How much stocks would you like to sell ");
int volumesold = Integer.parseInt(input.nextLine());
for (int i = 0; i < numofstocks; i++) {
mycustomers[menuchoice].setBalance(
mycustomers[menuchoice].getBalance() + (volumesold * mystocks[i].getprice()));
mycustomers[menuchoice].setPortfolio();
}
System.out.println(mycustomers[menuchoice].toString());
return;
}
}
if (choice == 3) // how to exit application
{
System.out.println("Thank you for using the application");
System.out.println("The current state of all customers are:");
for (int i = 0; i < mycustomers.length; i++) {
System.out.println(mycustomers[i].toString());
}
System.out.println("The current state of all stocks are:");
for (int i = 0; i < mystocks.length; i++) {
System.out.println(mystocks[i].toString());
}
System.exit(0);
}
}
}}}
How would I implement the do-while loop so that it goes back to the initial statement every time after executing the code - if only if the input is not 3?
Ask for input inside the while loop, like this:
choice = Integer.parseInt(input.nextLine());
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.
First off I'm sorry for the title I couldn't think of a better way to word it. The actual error is in option 3(whenever I try to add together all the sales in option 1). When I try to use salesList.length to track the size of the array I get cannot find symbol- variable length I'm very new to using array lists and that method worked for me in an earlier array but that array wasn't dynamic. Is there a specific way to track the length of a dynamic array list?
import java.util.*;
public class CustomerTest
{
public static void main(String[] args)
{
double totalSales = 0;
ArrayList<String> nameList;
nameList = new ArrayList<String>();
ArrayList<Double> salesList;
salesList = new ArrayList<Double>();
Scanner myScanner = new Scanner(System.in);
boolean done = true;
do
{
System.out.println("1) Add a new customer \n 2) Print all customers \n 3) Compute and print the total sales \n 4) Quit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Add a new customer ");
String answer = myScanner.nextLine();
nameList.add(answer);
System.out.print("Enter their sales ");
String answer2 = myScanner.nextLine();
double answer3 = Double.parseDouble(answer2);
salesList.add(answer3);
}
else if(choice == 2)
{
System.out.println("Customers: " + nameList);
System.out.println("Sales: " + salesList);
}
else if(choice == 3)
{
for(int i = 0; i < salesList.length; i++)
{
totalSales = totalSales + salesList[i];
}
System.out.println(totalSales);
}
else if(choice == 4)
{
System.out.println("Goodbye *Bows gracefully*");
done = false;
}
else
System.out.println("Invalid Choice");
}
while (done);
System.exit(0);
}
}
Change it to salesList.size();. Unlike arrays, the length of an ArrayList is not a directly accessible field.
Array have the length field
ArrayList doesnot have the length field type Use size()
use salesList.size(). unlike arrays you cannot use salesList.lenght
else if (choice == 3) {
for (int i = 0; i < salesList.size(); i++) {
totalSales += salesList.get(i);
}
System.out.println(totalSales);
}
Replace choice 3 with this and it should work.
your code is having bugs: Change the else if(choice==3) {} conditional part to following. you cannot use salesList.length, it can be done using salesList.size() and pleas change salesList[i] to salesList.get(i).
else if(choice == 3)
{
for(int i = 0; i < salesList.size(); i++)
{
totalSales += salesList.get(i);
}
System.out.println(totalSales);
}