I am new to Java and am having trouble with this particular for loop. Everytime I run the loop and enter a number that is not 1 or 2, the loop displays: "Please choose a correct option". What could be the cause of this?
public class Kbin {
public static void main (String args[]) throws java.io.IOException {
int option;
int i = 0;
System.out.println("What would you like help with?");
System.out.println("\t1. If statement");
System.out.println("\t2. Switch statement");
option = (char) System.in.read();
// loop:
for(i = 0; option != 1 & option != 2; i ++){
System.out.println("What would you like help with?");
System.out.println("\t1. If statement");
System.out.println("\t2. Switch statement");
option = (char) System.in.read();
switch(option){
case '1':
System.out.println("here is how you do an if statement");
i += 1;
break loop;
case '2':
System.out.println("Here is how you do a switch statement");
i += 1;
break loop;
default:
System.out.println("Please choose a correct option.");
continue;
}
}
}
}
Option variable is not getting the correct value that u expect it to hold.
As by seeing your code the user would enter either 1 or 2, then you are trying to convert it into char thats where the problem is. Try to take int as input
Scanner input = new Scanner(System.in);
option = input.nextInt();
Related
I'm currently a newbie to programming. We were tasked to evaluate if the rows and columns intended for the two matrices are acceptable to perform the addition operation. And if invalid, we would display an appropriate message and repeat the process by asking the user whether to repeat the process or not. If the answer is no, control should be back to the main menu. We weren't allowed to use methods at the moment so I'm quite problematic with this.
import java.util.Scanner;
public class matrixTransposition {
public static void main(String[] args) {
Scanner src = new Scanner(System.in);
int menu_choice;
char case_choice;
char case_choice2;
boolean menu_repeat = true;
boolean case_repeat = true;
boolean check = true;
boolean inCheck = true;
int rows_A, columns_A;
int rows_A2, columns_A2;
int rows_S, columns_S;
int rows_M, columns_M;
do{
//main menu selection here
System.out.print("\nEnter your choice: ");
menu_choice = src.next().charAt(0);
switch(menu_choice){
case '1':
do{
System.out.println("-------------------------------------------------");
System.out.println("\t\tMatrix Addition");
//First Matrix/Array
System.out.print("\nFirst Matrix: Please enter number of rows: "); //asks the user to enter number of rows
rows_A = src.nextInt();
System.out.print("\nFirst Matrix: Please enter number of columns: "); //asks the user to enter number of columns
columns_A = src.nextInt();
int [][] firstMatrix_A = new int [rows_A][columns_A];
int [][] secondMatrix_A = new int [rows_A][columns_A]; //declaring the arrays to be used
int [][] sumMatrix_A = new int [rows_A][columns_A];
//asks the user to enter values
System.out.println("\nPlease enter values for first matrix: ");
for(int i=0; i<rows_A; i++)
for(int j=0; j<columns_A; j++)
firstMatrix_A[i][j]=src.nextInt();
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//Second Matrix/Array
do{
System.out.println("------------------------------------");
System.out.print("Second Matrix: Please enter number of rows: "); // asks the user to enter rows
rows_A2 = src.nextInt();
System.out.print("\nSecond Matrix: Please enter number of columns: "); //asks the user to enter columns
columns_A2 = src.nextInt();
//validating if the 2nd matrix has the same length as the first matrix
if(rows_A2 != rows_A || columns_A2 != columns_A){
System.out.println("------------------------------------");
System.out.println("Error! Input is not the same length as the First Matrix!");
System.out.print("Do you want to input again? [Y][N]: ");
case_choice2 = src.next().charAt(0);
switch(case_choice2){
case 'Y':
check = true; //if the user entered Y, the user would be able
break; //re-enter rows and columns for the 2nd matrix
case 'N':
check = false; //if the user entered N, the user would be immediately brought
menu_repeat = true; //back to the main menu selection
break;
case 'y':
check = true; //if the user entered Y, the user would be able
break; //re-enter rows and columns for the 2nd matrix
case 'n':
menu_repeat = true; //if the user entered N, the user would be immediately brought
check = false; //back to the main menu selection
break;
default: //if the user did not enter Y or N, the user would be ask to
//enter again.
System.out.println("---------------------------------------------");
System.out.println("Invalid Input Please Try Again....");
while(case_repeat){
System.out.println("---------------------------------------------");
System.out.print("Try Again? [Y][N]: ");
case_choice2 = src.next().charAt(0);
switch(case_choice2){
case 'Y':
check = true; //if the user entered Y, the user would be able
case_repeat = false; //re-enter rows and columns for the 2nd matrix
break;
case 'N':
check = false; //if the user entered N, the user would be immediately brought
case_repeat = false; //back to the main menu selection
menu_repeat = true;
break;
case 'y':
check = true; //if the user entered y, the user would be able
case_repeat = false; //re-enter rows and columns for the 2nd matrix
break;
case 'n':
check = false; //if the user entered n, the user would be immediately brought
case_repeat = false; //back to the main menu selection
menu_repeat = true;
break;
default: //if the user did not enter Y or N, the user would be ask to
//enter again.
System.out.println("---------------------------------------------");
System.out.println("Invalid Input Please Try Again....");
case_repeat = true;
}
}
}
}
//else if all inputs are valid the program would proceed to the next step
else{
//asks the user to enter values
System.out.println("\nPlease enter values for second matrix: ");
for(int i=0; i<rows_A2; i++)
for(int j=0; j<columns_A2; j++)
secondMatrix_A[i][j]=src.nextInt();
check = false;
}
}while(check);
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
for(int i=0; i<rows_A; i++)
for(int j=0; j<columns_A; j++)
sumMatrix_A[i][j] = firstMatrix_A[i][j] + secondMatrix_A[i][j]; //adds the two matrices
System.out.println("------------------------------------"); //displays the first matrix
System.out.println("First Matrix");
for(int i=0; i<rows_A; i++){
for(int j=0; j<columns_A; j++){
System.out.print(firstMatrix_A[i][j] + " ");
}
System.out.println();
}
System.out.println("------------------------------------"); //displays the second matrix
System.out.println("Second Matrix");
for(int x=0; x<rows_A2; x++){
for(int y=0; y<columns_A2; y++){
System.out.print(secondMatrix_A[x][y] + " ");
}
System.out.println();
}
System.out.println("------------------------------------"); //displays the sum of the two matrices
System.out.println("Matrix Sum");
for(int i=0; i<rows_A; i++){
for(int j=0; j<columns_A; j++){
System.out.print(sumMatrix_A[i][j] + " ");
}
System.out.println();
}
System.out.print("Do you want to try again? [Y][N]: "); //asks the user to re-run the operation
case_choice = src.next().charAt(0);
}while(case_choice == 'Y' || case_choice == 'y'); //if yes the operation would re-run
if(case_choice == 'N' || case_choice == 'n'){ //if no, the user would be brought back to the
menu_repeat = true; //main menu selection
}
break;
}
}while(menu_repeat);
}
}
The problem is that when the user enters N, you are breaking out of the inner loop. What you want is to break out of the loop where you are displaying menu choices, i.e., the outer most loop.
Your code structure is as follows:
do{
//main menu selection here
switch (menu_choice) {
case '1':
do {
//First Matrix/Array
//Second Matrix/Array
do {
//compare matrix and prompt for input if rows and col dont match
case_choice2 = src.next().charAt(0);
switch (case_choice2) {
case 'N':
check = false;
menu_repeat = true;
break;
.
.
.
}
}
}
}
}
Your break statement breaks out of the inner loop. Whereas you want to break out to the outer most loop.
You should use labels for this purpose:
do{
//main menu selection here
//define label here
main_menu:
switch (menu_choice) {
.
.
.
switch (case_choice2) {
case 'N':
check = false;
menu_repeat = true;
//label used here
break main_menu;
.
.
.
This will break out to the loop of your choice. You can also use continue, if you want to pass the control back to the loop.
Please note: You might want to re consider the usage of the case_choice variable because it will no longer be always accessible outside the loop, as you are breaking out of it. The compiler will for sure give you an error for the same.
I am new to programming and got stuck on a task. It says that user should input their name and the size of it and then it would be printed in stars with that size, also it should use loops in this program not just sout stars.
I have no idea on how to approach this problem so I would really appreciate it if anyone could give me an idea :)
What I have tried so far is:
(update):
i was able to do my whole coding and reach the thing i want, but what i'am stuck in a point, where if user update the size which is n , how i can use it in my whole switch while printing where Pattern(A) prints star version of letter
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int option = 0;
while (option != 3) {
System.out.println("Hello, Welcome to Işık NameIt program. ");
System.out.println("----------------------------------------------------------------");
System.out.println("The following options are available for you:\n" +
"1) Display a name\n" +
"2) Change the size\n" +
"3) Exit Program");
System.out.print("Choose an option: ");
option = input.nextInt();
int n = 5;
switch (option) {
case 1:
System.out.print("What is your name?! ");
String name = input.next();
for(int i=0; i<=name.length()-1; i++) {
char letter = name.charAt(i);
switch (letter){
case 'a':
PatternA(n);
break;
case 'y':
PatternY(n);
break;
case 'h':
PatternH(n)
break;
case 'm':
PatternM(n)
break;
}
}
break;
case 2:
System.out.print("What is the new size? ");
int nupdate = input.nextInt();
}
}
}
public static void PatternA(int n) {
// Outer for loop for number of lines
for (int i = 0; i < n; i++) {
// Inner for loop for logic execution
for (int j = 0; j <= n / 2; j++) {
// prints two column lines
if ((j == 0 || j == n / 2) && i != 0 ||
// print first line of alphabet
i == 0 && j != 0 && j != n / 2 ||
// prints middle line
i == n / 2)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
System.out.println("-----------------------------------------------------------------------");
}
I'm not 100% clear on what you are expecting as your output, if you provided a sample of that it would be helpful. However, with the way you have your program implemented right now you will want to throw your switch statement inside of a while loop to continue executing the program until a 3 is input by the user.
while (option != 3)
{
switch (option)
{
// code
}
// code
option = input.nextInt();
}
Within that while block you can execute whatever statements you want when the user inputs their specified option. Depending on the requirements of the code you should also consider validating the user input. What happens if they don't put in a 1, 2, or 3?
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Hello, Welcome to Işık NameIt program. ");
System.out.println("----------------------------------------");
System.out.println("The following options are available for you:\n" +
"1) Display a name\n" +
"2) Change the size\n" +
"3) Exit Program");
System.out.print("Choose an option: ");
int option = input.nextInt();
int size = option.length;
while(option !=3){
switch (option){
case 1:
for(int index = 0; index <= size; index++) {
System.out.print("*");
}
System.out.println(" ");
case 2:
System.out.print("What is the new size? ");
size = input.nextInt();
input.nextLine();
case 3:
break;
}
}
}
Hello there fellow coders. Just a noob here that is currently stuck in a pickle.
I am coding a math training program, and am needing to loop back to my main menu.
There is an infinite loop i am having trouble getting out of. If the user keeps answering the correct answer, it just keeps on asking for another problem. Selecting yes will generate a new answer and will keep doing so (infinite). Selecting no will terminate the program.
How do i make is so if they select no, it takes the user back to the main menu?
Also, how to make it so if they select yes, the problem only loops a new equation at max 10 times before taking the user back to my main menu.
This is my Code:
import java.util.Scanner;
import java.util.Random;
public class MathPracticeProgram
{
public static void main(String[] args)
{
//Scenario: Make a practice program for Addition, Subtraction, Multiplication, and Division. Include exit option as well.
Random rand = new Random ();
Scanner scan = new Scanner (System.in);
int menu = (5);
int num1, num2, user_answer, total;
System.out.println("Math Practice Porgram");
System.out.println("Please Input Your Choice via the number\n");
System.out.println("1. Addition\n2. Subtraction\n 3. Multiplication\n 4. Division\n Exit Program by entering 0");
System.out.println("\nYour choice:");
menu = scan.nextInt();
System.out.println("\n");
//Menu Selection
if (menu <= 5 || menu > 0)
{
switch(menu)
{
//Exit
case 0:
{
System.out.println("Thank you for using my math practice program.");
}
break;
//Addition
case 1:
{
System.out.println("You have selected Addition");
String user_again;
do
{
num1 = rand.nextInt(99);
num2 = rand.nextInt(99);
int counter = 0;
do
{
System.out.println("New solution to solve: ");
System.out.println(num1 + " + " + num2 + " = ");
user_answer = scan.nextInt();
System.out.println("\n");
total = num1 + num2;
if(user_answer != total)
{
System.out.println("Incorrect...");
counter++;
}
}while (user_answer != total && counter < 3);
System.out.println("Correct! Do you want another problem? yes or no: ");
user_again = scan.next();
}while(user_again.equalsIgnoreCase("yes"));
System.out.println("\nChanging to Main Menu\n");
}
break;
//Subtraction
case 2:
{
}
break;
//Multiplication
case 3:
{
System.out.println("Multiplication");
}
break;
//Division
case 4:
{
System.out.println("Division");
}
break;
}
}
}
}
While writing code for my program I thought of testing the first part before moving on and writing the operations. Although I have the user input, but I want the options to be displayed after each operation (add, deltete..) is done untill the users presses exit. How do I modify my code to do it?
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n Exit");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int choice;
System.out.println("Enter your Choice : ");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Getting ready to Add a Record ");
//set();
break;
case 2:
System.out.println("Getting ready to Delete a Record ");
//delete();
break;
case 3:
System.out.println("Getting ready to Update a Record ");
//update();
break;
case 4:
System.out.println("Here is your record ");
//display();
break;
case 5:
System.out.println("Out we go.");
System.exit(0);
//exit();
break;
default:
System.out.println("Try again");
break;
}
} while ( choice > 5 || choice < 1 );
}
}
Simply change your while condition to:
} while ( choice > 0 && choice < 5 );
First make sure your scanner really has an int, use sc.hasNextInt() to validate the user entered a number. To end the do/while loop at "5.Exit", just have it like do{...}while(choice!=5). Code below is not tested.
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n 5.Exit");
System.out.println("Enter your Choice : ");
choice = -1;
Scanner sc = new Scanner(System.in);
// validate the next thing in your scanner is an int
// otherwise, sc.nextInt() might cause an exception
if (sc.hasNextInt()){
choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Getting ready to Add a Record ");
// ...
break;
case 2: System.out.println("Getting ready to Delete a Record ");
// ...
break;
case 3: System.out.println("Getting ready to Update a Record ");
// ...
break;
case 4: System.out.println("Here is your record ");
// ...
break;
case 5: System.out.println("Out we go.");
// skip System.exit(0), your main method ends
// automatically when you leave your do/while loop
break;
default: System.out.println("Try again");
break;
}
}
// if choice == 5 it ends, otherwise, starts over...
} while ( choice != 5 );
}
}
Although I have the user input, but I want the options to be displayed
after each operation (add, deltete..) is done untill the users presses
exit.
You can set int flag=0; and when user selects exit option set flag to 1 to tell loop to exit.As of now you are already breaking out for number > 5 or < 1 in default case so no need to put that condition in while.
int flag=0;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=1;//Set flag to 1 if user enters 5
break;
...
} while ( flag!=1 );//Exit the loop when flag==1
//Or directly while ( choice!=5 );
Serious EDIT
As Java Programmer I should probably suggest you to use boolean primitive type for flagging.
boolean flag=true;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=false;//Set flag to 1 if user enters 5
break;
...
} while (flag);//Exit the loop when flag==false
One More thing:
Surround code with try-catch to leave out invalid inputs and prompt again for input.
Most of the times it's not recommended to swallow the Exception.
do{
try{
....//Your Switch case
}catch(InputMismatchException e){}
} while (choice !=5);//But remove System.exti(0); from your switch statement
Simply make your while loop as:
} while ( choice!=0 );(The Wrong one)
Correction:
} while(choice!=0 && choice<=5)
I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.
Scanner s2 = new Scanner(System.in);
for(int i=0; i < this.num_choices; i++)
{
if(s2.hasNext())
{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
}
else
{
System.out.println("Lets end this");
}
}
`
I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to
choice2 = Integer.parseInt(read_choice2.next());
which is inside a while loop as well. Here is the code for that:
public class Main
{
public static void main(String args[]) throws IOException
{
Vector<Survey> mysurveys = new Vector<Survey>();
boolean carry_on = true;
int choice = 0;
Scanner read_choice = new Scanner(System.in);
System.out.println("Let's begin the Survey/Test application!");
while(carry_on)
{
System.out.println("What would you like to do?");
System.out.println("1. Create a new Survey");
System.out.println("2. Create a new Test");
System.out.println("3. Display a Survey");
System.out.println("4. Display a Test");
System.out.println("5. Save a Survey");
System.out.println("6. Save a Test");
System.out.println("7. Load a Survey");
System.out.println("8. Load a Test");
System.out.println("9. Quit");
System.out.println();
System.out.println("Please enter a number for the operation you want to perform: ");
choice = Integer.parseInt(read_choice.next());
/*try
{
choice = Integer.parseInt(buffer.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice.nextInt();
}*/
switch(choice)
{
case 1:
System.out.println("Please Enter a Name for your Survey");
String in = buffer.readLine();
Survey s1 = new Survey();
s1.CreateNew(in);
mysurveys.add(s1);
////
add_question(s1.type);
break;
case 2:
System.out.println("Please Enter a Name for your Test");
//String in = buffer.readLine();
Test t1 = new Test();
//t1.CreateNew(in);
mysurveys.add(t1);
break;
////
//add_question(t1.type);
case 3:
break;
// call Survey.display()
case 4:
break;
case 5:
Survey s = new Survey();
ReadWriteFiles x = new ReadWriteFiles();
x.SaveSurvey(s);
break;
case 6:
Test t = new Test();
//ReadWriteFiles x = new ReadWriteFiles();
//x.SaveSurvey(t);
break;
case 7:
carry_on = false;
break;
default:
System.out.println("Incorrect Input. Try Again");
System.out.println();
break;
}
}
read_choice.close();
}
public static void add_question(String type) throws IOException, NullPointerException
{
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));
while (carry_on2)
{
//
System.out.println("1. Add a new T/F Question");
System.out.println("2. Add a new Multiple Choice Question");
System.out.println("3. Add a new Short Answer Question");
System.out.println("4. Add a new Essay Question");
System.out.println("5. Add a new Ranking Question");
System.out.println("6. Add a new Matching Question");
System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
System.out.println("Please enter a number for the operation you want to perform: ");
choice2 = Integer.parseInt(read_choice2.next());
/*try
{
choice2 = Integer.parseInt(buffer2.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice2.nextInt();
}*/
switch(choice2)
{
case 1:
q = new TrueFalse();
break;
case 2:
q = new MultipleChoice();
break;
case 3:
q = new ShortAnswer();
break;
case 4:
q = new Essay();
break;
case 5:
q = new Ranking();
break;
case 6:
q = new Matching();
break;
case 7:
carry_on2 = false;
break;
default:
System.out.println("Incorrect Input.");
break;
}
q.createQuestion(type);
}
}
}
I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.
In general way, you should add if(read_choice.hasNext()) before invoking read_choice.next(); You have the exception java.util.NoSuchElementException because no elements found to be read. this is a good habit.
About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close() outside of loop.
Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().
read_choice.close();
Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;
You don't need to initialize the Scanner multiple times. Just create one instance and pass it around (keep using it).
Also,
for(int i=0; i < this.num_choices; i++)
{
//if(s2.hasNext())
//{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
you don't need that condition check. The next() will block until the input is entered.