How to take multiple user inputs using if-else statements in java. - java

import java.util.Scanner;
public class Assignment6 {
public static void commandList()
{
System.out.println("Command Options------------");
System.out.println("a: Create a new table");
System.out.println("b: Change the row sizes");
System.out.println("c: Change the column sizes");
System.out.println("d: Change the data types");
System.out.println("e: Change the formats");
System.out.println("f: Display the table");
System.out.println("g: Display the log data");
System.out.println("?: Display this menu");
System.out.println("q: Quit the program");
System.out.println("---------------------------");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Command Options------------");
System.out.println("a: Create a new table");
System.out.println("b: Change the row sizes");
System.out.println("c: Change the column sizes");
System.out.println("d: Change the data types");
System.out.println("e: Change the formats");
System.out.println("f: Display the table");
System.out.println("g: Display the log data");
System.out.println("?: Display this menu");
System.out.println("q: Quit the program");
System.out.println("---------------------------");
String input = "";
System.out.println("Please input a command:");
input = in.nextLine();
do
{
if (input.equals("a"))
{
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable = in.nextInt();
}
else if (input.equals("b"))
{
System.out.println("Change the row sizes");
int newRow = in.nextInt();
}
else if (input.equals("c"))
{
System.out.println("c [Type an integer to update the table column]: ");
int newColumn = in.nextInt();
}
else if (input.equals("d"))
{
System.out.println("d [Type an integer to update the data type]: ");
int newDataType = in.nextInt();
}
else if (input.equals("e"))
{
System.out.println("e [Type and integer to update printf format]: ");
int newPrintf = in.nextInt();
}
else if (input.equals("f"))
{
System.out.println("f [Display the table]");
}
else if (input.equals("g"))
{
System.out.println("g [Display the log data]");
}
else if (input.equals("?"))
{
commandList();
}
else
{
System.out.println("Invalid ***Type ? to get commands***");
}
}
while (!input.equals("q"));
{
}
}
}
I created a menu and I am asking the user to input a letter and the program will show a command option they choose. Right now I have it so if the user inputs "a" then "Input three integers to initialize the table" will print. I need it to then print "Please input a command" next but it just keeps printing "Input three integer to itialize the table" I have been trying different methods for a while now and I have no idea what to do. Any help?

Look at the bottom of your do-while loop:
do
{
if (input.equals("a"))
{
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable = in.nextInt();
}
// … more if-else statements
} while (!input.equals("q"));
It keeps printing that statement because after the if-else statement finishes, the value of input still equals "a" since you haven't changed the value of input.
Perhaps you want the user to enter new input before the while loop checks again.
// … more if-else statements
input = in.nextLine(); // <-- add new user input
} while (!input.equals("q"));
And as Juned Ahsan has already said you need to add more code within that first if statement to print the other commands that you mentioned.

You need to loop to ask for three integers. Better use array to capture the values. Somethign like this:
if (input.equals("a"))
{
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable[] = new int[3];
for (int i = 0; i < 3 ; i++) {
System.out.println("Input " + (i+1) + "table value: ");
newTable[i] = in.nextInt();
}
}

Since depending on the command entered by the user, the number of inputs you accept from the user changes, try using loops inside the if or else conditions. A do while loop will just keep going the same number of times for any of the commands entered. Try something like this:
String input = "";
do {
System.out.println("Please input a command:");
input = in.nextLine();
if (input.equals('a')) {
System.out.println("a [Input three integers to ititialze a table:] ");
int newTable[] = new int[3];
for (int i = 0; i < 3 ; i++) {
System.out.println("Input " + (i+1) + "table value: ");
newTable[i] = in.nextInt();
}
}
else if(input.equals('b')) {
// Accept as many inputs you want for command 'b'
}
} while (!input.equals('q'))
The outer do while loop will ensure that you can accept as many commands from the user till the user enters 'q'.

Related

Loops in Java after user inputs values

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 **");

Check if array is already created in Java

class CreateArray{
Scanner input = new Scanner(System.in);
public void Create(){
System.out.print("How many numbers numbers do you want to enter? Minimum of 5 and a maximum of 20 only: ");
int num = input.nextInt();
if (num >=5 || num >20){
int array[] = new int[num];
System.out.println("Enter the numbers you want: ");
if(array.length != 0){
for(int i = 0 ; i<array.length; i++){
array[i] = input.nextInt();
}
}
System.out.print("Your array of numbers are: ");
for(int i = 0 ; i<array.length; i++){
System.out.print(array[i] + " ");
}
}
else{
System.out.print("Please input a the right numbers of array");
} }}
I would like to know how to identify if array is already created so that i can display an error message. I have two classes as you can see above theres the class CreateArray and here is the main class: I am new to java actually so forgive me. And also the logic is that when user create an array then they decide to continue and check again the code will output "you have already created an array" Thank you so much for answering.
public class Lab3
{public static void main(String[] args){
Scanner ans = new Scanner(System.in);
String choice;
String choices;
do{
System.out.println("[1] Create Array");
System.out.println("[2] Insert Element");
System.out.println("[3] Search");
System.out.println("[4] Display");
System.out.println("[5] Delete");
System.out.println("[0] Stop");
System.out.print("\nEnter Choice: ");
choice = ans.nextLine();
if(choice.equals("1")){
CreateArray myObj = new CreateArray();
myObj.Create();
}
else{
System.out.print("Array has been created please procedd to other options!");
}
System.out.println();
System.out.print("Do you want to continue? : ");
choices =ans.nextLine();
}
while(!choices.equals("-1") || !choices.equals("-1"));
}}
You can check if an array is already created by using a global array variable that you can check from your main class.
Add this line int array[]; to the CreateArray class as a global variable, and replace int array[] = new int[num]; with array = new int[num]; so that it referances to the global vairable.
Then from your main/Lab3 class you can simply use if (myObj.array == null) to check if the array has NOT been created, or use if (myObj.array != null) to check if the array HAS been created.
Note, you also need to place the following code outside of the do{} while () loop CreateArray myObj = new CreateArray(); otherwise it will create a new object every loop and you will not be able to keep the inputs.
The complete code might look like this (with a few other changes to make more sense):
class CreateArray {
Scanner input = new Scanner(System.in);
//place a global variable here
int array[];
public void Create() {
System.out.print("How many numbers numbers do you want to enter? Minimum of 5 and a maximum of 20 only: ");
int num = input.nextInt();
//Fix this line as shown by Scary Wombat in comments:
if (num <= 5 || num <= 20) {
//Initialize the array here (This will make it a non null value)
array = new int[num];
System.out.println("Enter the numbers you want: ");
if (array.length != 0) {
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
}
System.out.print("Your array of numbers are: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
} else {
System.out.print("Please input a the right numbers of array");
}
}
}
And the Lab3 class could look like this:
public class Lab3 {
public static void main(String[] args) {
Scanner ans = new Scanner(System.in);
String choice;
String choices;
//Place the CreateArray object here so that it can be re-used between selecting options, otherwise you will lose all progress
CreateArray myObj = new CreateArray();
do {
System.out.println("[1] Create Array");
System.out.println("[2] Insert Element");
System.out.println("[3] Search");
System.out.println("[4] Display");
System.out.println("[5] Delete");
System.out.println("[0] Stop");
System.out.print("\nEnter Choice: ");
choice = ans.nextLine();
//Only call this method if it has not been created yet
if (choice.equals("1") && myObj.array == null) {
myObj.Create();
}
//If another option is chosen but the array has not been created, then give an error message
else if (myObj.array == null) {
System.out.print("Array has not been created yet, please choose option 1.");
}
else if (choice.equals("1")) {
System.out.print("THe array has already been created, please choose another option.");
}
//Place all other value checkes after the above checks:
else if (choice.equals("2")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("3")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("4")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("5")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("0")) {
System.out.print("This opetion is not yet supported.");
break;
} else {
System.out.print("Invalid option.");
}
System.out.println();
System.out.print("Do you want to continue? : ");
//What does this do?
choices = ans.nextLine();
} while (!choices.equals("-1"));
}
}

How to avoid double printed statements with an if statement in a while loop

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();

How do I set the conditional statement in this program?

So this code asks for a name and a number 1-20, but if you put in a number over 20 or below 1 the program still runs and I know I need a conditional statement right around figuring out the amount for "ano" to stop and re-ask the statement and re-run the segment but I don't know how to implement it into the code.
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}
Replace your while loop with this:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}
Try to surround your ano = userno.nextInt() in a while loop. (i.e., while(ano < 1 || ano > 20)) and put a prompt inside that while loop. That way, it will keep reading a new number until it finally no longer fulfills the while loop and will break out.

input a number on scanner

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");
}
}

Categories

Resources