Hello everyone i'm doing my homework and i want to understand, how to fulfill properly third section in code - 3.View operation history. (List of all operations performed by user, use array for storing this information in format: “[operation index]. [operation name] - [user input]”. Also i have an issue -
Application should work and accept user input until he wants to exit from program.
Scanner in = new Scanner(System.in);
System.out.println("Please select operation");
System.out.println("1.Encode");
System.out.println("2.Decode");
System.out.println("3.View operation history");
System.out.println("4.Exit program");
Integer userInput = Integer.valueOf(in.nextLine());
if (userInput.equals(1)) {
System.out.println("You chosen encoding operation");
System.out.println("Please choose codec name - caesar or morse");
String userInputEncode = in.nextLine().toLowerCase();
if (userInputEncode.equals("caesar")) {
System.out.println("Enter text to encode");
String userInputEncode2 = in.nextLine().toLowerCase();
System.out.println("Encoded text: " + caesarEncoder.encode(userInputEncode2));
} else if (userInputEncode.equals("morse")) {
System.out.println("Enter text to encode");
String userInputEncode3 = in.nextLine().toLowerCase();
System.out.println("Encoded text: " + morseEncoder.encode(userInputEncode3));
} else
System.out.println("You entered wrong codec name, try one more time");
} else if (userInput.equals(2)) {
System.out.println("You chosen decoding operation");
System.out.println("Please choose codec name - caesar or morse");
String userInputDecode = in.nextLine().toLowerCase();
if (userInputDecode.equals("caesar")) {
System.out.println("Enter text to decode");
String userInputDecode2 = in.nextLine().toLowerCase();
System.out.println("Decoded text: " + caesarDecoder.decode(userInputDecode2));
} else if (userInputDecode.equals("morse")) {
System.out.println("Enter text to Decode");
String userInputDecode3 = in.nextLine().toLowerCase();
System.out.println("Decoded text: " + morseDecoder.decode(userInputDecode3));
}
else
System.out.println("You entered wrong codec name, try one more time");
}
else if (userInput.equals(3)) {
}
else if (userInput.equals(4)) {
in.close();
System.out.println("Program was closed by user");
You probably need a loop that checks if the user has typed the number 4.
Then you can create a List before the loop where you will store all the history of what the user has typed during the execution of the program.
And then in the case of the number 3 is selected, you can use that list to take the historical data and then print all the data that you need
Below a simple and fast example (not the best way):
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
Scanner in = new Scanner(System.in);
List<String> operationHistory=new ArrayList<String>();
Integer userInput = null;
do{
System.out.println("Please select operation");
System.out.println("1. aaa");
System.out.println("2. bbb");
System.out.println("3. print selection history");
System.out.println("4. exit");
userInput = Integer.valueOf(in.nextLine());
if (userInput.equals(1)) {
System.out.println("Please type something");
String userInputEncode = in.nextLine().toLowerCase();
operationHistory.add("1. aaa - " + userInputEncode);
}else if (userInput.equals(2)) {.
System.out.println("Please type something");
String userInputEncode = in.nextLine().toLowerCase();
operationHistory.add("2. bbb - " + userInputEncode);
}else if (userInput.equals(3)) {
System.out.println("Operation History:");
for(String operationitem:operationHistory){
System.out.println(operationitem);
}
System.out.println("-------------");
}
}while(!userInput.equals(4));
in.close();
System.out.println("Program was closed by user");
This is just an example similar to your code, you can use it to understand how your problem can be solved and how the loops and the lists works
You then probably want to manage some unexpected input
Related
public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");
I'm new to stackoverflow and wanted to know why my statement keeps on being repeated twice when i introduce an if statement in my while loop # "if done, type "back"". Secondly, can someone tell me why the ArrayList keeps an empty String at index 0 when i only add one item to the ArrayList? Thanks!
Here is the code:
package com.codewithrichard;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList <String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
System.out.println("1) add item to list");
System.out.println("2) display list and amount of items in it");
System.out.println("3) quit!");
while (appIsStillOn) {
System.out.println("Option (1-4): ");
int option1 = input.nextInt();
if (option1 == 1) {
while (true) {
System.out.println("item (if done, type \"back\"): ");
String itemAdded = input.nextLine().toLowerCase();
if (!itemAdded.equals("back")) {
shoppingList.add(itemAdded);
} else {
break;
}
}
}
else if (option1 ==2){
System.out.println(shoppingList);
System.out.println("size of shopping list: " + shoppingList.size());
}
else {
System.out.println("Can't wait for you to come back!");
appIsStillOn = false;
}
}
}
}
The Scanner#nextInt() method (and many other next...() methods) does not consume the newLine character from the Scanner buffer which is produced when the ENTER key is hit. The Scanner#nextLine() method will consume it if encountered after a Scanner#nextInt() method therefore giving the impression that the prompt for input was skipped over.
Also Consider this...
What is to happen if the User accidentally types in an alpha character instead of a menu choice digit? That's right, your application will crash due to a InputMismatchException.
You should always carry out some form of validation for User input and if that validation fails, allow the User to make a proper entry. This obviously promotes a more trouble free environment when using your application. Using your current model, here is an example of this:
java.util.Scanner input = new java.util.Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList<String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list.");
while (appIsStillOn) {
int option1 = 0;
while (option1 < 1 || option1 > 3) {
System.out.println();
System.out.println("Your Shopping List options are:");
System.out.println(" 1) Add item to list.");
System.out.println(" 2) Display list and amount of items in it.");
System.out.println(" 3) Quit!");
System.out.print("Choice (1-3): --> ");
try{
option1 = input.nextInt();
if (option1 < 1 || option1 > 3) {
throw new java.util.InputMismatchException();
}
/* Consume the enter key hit (newline char) in case
a Scanner#nextLine() prompt is next so that it
doesn't get consumed by that method. */
input.nextLine();
}
catch (java.util.InputMismatchException ex) {
System.err.println("Invalid menu choice supplied! Try again...");
/* Consume the enter key hit (newline char) in case
a Scanner#nextLine() prompt is next so that it
doesn't get consumed by that method. It is also
required here in case an exception has bypassed
the above 'input.nextLine()' call.*/
input.nextLine(); // Consume the enter key hit (newline char)
}
}
if (option1 == 1) {
while (true) {
System.out.println();
System.out.println("Enter the item to add (when done, enter \"back\"): ");
System.out.print("Item: --> ");
String itemToAdd = input.nextLine();
if (itemToAdd.trim().equals("")) {
System.err.println("Invalid Item String! You must supply something!");
continue;
}
else if (itemToAdd.equalsIgnoreCase("back")) {
break;
}
shoppingList.add(itemToAdd);
}
}
else if (option1 == 2) {
System.out.println();
System.out.println(shoppingList);
System.out.println("Number of Items in shopping list: " + shoppingList.size());
}
else {
System.out.println();
System.out.println("Bye-Bye - Can't wait for you to come back!");
appIsStillOn = false;
}
}
After take input input.nextInt(), when you press enter input.nextLine().toLowerCase() takes the data of that line since input.nextInt() doesn't take \n(newline).
Read the newline to skip it after input.nextInt()
int option1 = input.nextInt();
input.nextLine();
Firstly I'm a new person here. I need to ask one question.
Scanner klavye = new Scanner(System.in);
System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo = klavye.nextLine();
if(hesapNo.length() != 11) {
System.out.println("You need to enter number with 11 digit");
}
else {
if(hesapNo.charAt(3) == '-' && hesapNo.charAt(6) == '-') {
System.out.println(hesapNo + " is valid");
}
else {
System.out.println(hesapNo + " is not valid");
}
}
I want to take only digit number but If I write below like this:
ABC-DC-SMND
"The count is valid"
how can I solve this problem?
Thanks for all of your interest.
You can do it with regular expressions and a loop to prompt the user until a valid input.
Scanner klavye = new Scanner(System.in);
System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo;
final String regexPattern = "\\d{3}-\\d{2}-\\d{4}";
do {
hesapNo = klavye.nextLine();
System.out.println("You need to enter a number with 11 digit with pattern: DDD-DD-DDDD");
}
while(!hesapNo.matches(regexPattern));
System.out.println(hesapNo + " is valid");
That can be done with a simple regex using String.matches:
Scanner klavye = new Scanner(System.in);
System.out.println("DDD-DD-DDDD enter bank number digit: ");
String hesapNo = klavye.nextLine();
if(hesapNo.matches("\\d{3}-\\d{2}-\\d{4}")){ // <-- this regex matches your pattern DDD-DD-DDDD
System.out.println(hesapNo + " is valid");
}else{
System.out.println("You need to enter number with 11 digit");
}
EDIT
If you want to keep asking for input until a valid one is entered then you can do this:
Scanner klavye = new Scanner(System.in);
String hesapNo;
boolean validInput;
System.out.println("DDD-DD-DDDD enter bank number digit: ");
do {
hesapNo = klavye.nextLine();
validInput = hesapNo.matches("\\d{3}-\\d{2}-\\d{4}");
if (!validInput) { // if invalid input then warn the user
System.out.println("Your bank number must be in DDD-DD-DDDD format");
}
} while (!validInput); // loop until a valid input is provided
System.out.println(hesapNo + " is valid");
I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?
System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);
if (b.hasNextDouble()) {
double lage = b.nextDouble();
setAge(lage);
addEmployeeMenu();
} else {
System.out.println("You should type only numbers!");
}
You can use a while loop like this
Scanner b = new Scanner(System.in);
double lage;
while (true) {
System.out.println("2 - Set The Age");
if(b.hasNextDouble()){
lage = b.nextDouble();
break;
}else b.nextLine();
}
The point is, get your number and check it inside a while loop, repeat as long as the input is not correct
You can also use NumberFormatException:
while (true) {
System.out.println("Set the age: ");
String input = sc.next();
try {
int x = Integer.parseInt(input);
System.out.println("Your input '" + x + "' is a integer");
break;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
}
}
I keep getting "java.lang.IllegalStateException" after using Scanner()
this is what I have
public void insertBook(){ //this method allows the user to insert a new book in the database
Boolean select = false;
Scanner input = new Scanner(System.in);
File textFile = new File("src/newbooks.txt");
FileWriter fw = null; //FileWriter and BufferedWriter have to be initialized and used inside a try catch
//to be used outside, initialize the objects as null
BufferedWriter bw = null;
try{
fw = new FileWriter(textFile);//check if it can read the textfile
bw = new BufferedWriter(fw);//FileWriter has to be wrapped in BufferedWriter
}catch(IOException e){
System.out.println("the file could not be found");
}//end catch
System.out.println(" select is " +select);//if(text == "n")
System.out.println("enter the book information below");
System.out.println("if the informatin is not available, enter\"information not available\"");
System.out.print("do you wnat to enter a book? ");
String text = input.next();
if(text.equals("n"))
select = true;
do{
String book = new String();
if(select == true)
break;
if(text.equals("n")){
System.out.print("inside if no\n");
select = true;
//break;//break here so
}
else if (text.equals("y")){
System.out.println("inside if y");
try{
Scanner input2 = new Scanner(System.in);
System.out.print("enter the title of the book: ");
book = input2.next();
bw.write(book + ", ");
System.out.println("after first write");
System.out.print("enter the author: ");
book = input2.next();
bw.write(book + ", ");
System.out.println();
System.out.print("enter the year of the book: ");
book = input2.next();
bw.write(book + ", ");
System.out.println();
System.out.print("enter the gender: ");
book = input2.next();
bw.write(book + ", ");
//System.out.println();
System.out.print("enter a description: ");
book = input2.next();
bw.write(book + ", ");
System.out.println();
bw.write("\n");
input2.close();
select = false;
}
catch(IOException e){
System.out.println("the text could not be read");
}
input.close();
}
else{
System.out.println("you didn't enter a valid selection");
}
System.out.print("do you want to enter another booK? Enter y for yes and n for no");
text = input.nextLine(); //error here
if(text.equals("n"))
select = true;
}while(select == false);//end while select
//input.close();
}//end of insert method
whenever I try to use the Scanner outside the if statements, it gives met the same error. it works if I enter a wrong choice or "n", but if I choose "y" and enter the data the Scanner fails after it gets to the last line for the input inside the do-while loop.
...
bw.write("\n");
input2.close();
select = false;
}
catch(IOException e){
System.out.println("the text could not be read");
}
You close the scanner here:
input.close(); // <- remove this line
}
else{
System.out.println("you didn't enter a valid selection");
}
...
And here it is already closed.
...
text = input.nextLine();
if(text.equals("n"))
select = true;
...
Close your scanner after you last need it.
This is because you cannot request a new line from a closed scanner.
Read more about it in the API Documentation about scanner:
public void close()
Closes this scanner. If this scanner has not yet
been closed then if its underlying readable also implements the
Closeable interface then the readable's close method will be invoked.
If this scanner is already closed then invoking this method will have
no effect.
Attempting to perform search operations after a scanner has been
closed will result in an IllegalStateException.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()