Java do-while loop doesn't see closing statement [duplicate] - java

This question already has answers here:
Variables in a do while loop
(5 answers)
Closed 1 year ago.
I am putting all my code into a do-while statement so it keeps looping until the user enters 3 to quit. For some reason when I close the do statement it doesn't see the variable userInput. I've tried changing so many things around and none of it works. So the issue is at while (userInput !=3); it throws userInput cannot be resolved to a variable
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
do {
Scanner in = new Scanner (System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
int userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger <= secondInteger) {
System.out.print(firstInteger + " ");
firstInteger++;
}
}else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
}
} while (userInput != 3);
}
}

userInput must be declared outside the loop for the while condition to see it.
Try this:
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int userInput;
do {
Scanner in = new Scanner(System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger <= secondInteger) {
System.out.print(firstInteger + " ");
firstInteger++;
}
} else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
}
} while (userInput != 3);
}
}

userInput is defined inside the loop's block, so it's not accessible from outside it, including the loop's condition. One solution is to move the declaration out of it:
int userInput = -1;
do {
// code...
userInput = in.nextInt();
// more code...
} while (userInput != 3);

Related

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

Why does my scanner iterate twice once and then once all other times that I input something that is not an integer?

What I really want my program to do is iterate once every time, but when I run code, the first time I try to follow the constraints, it asks me to enter a number between 1 and 7 twice, and after I I go through one trial, the code flows as desired.
//import libraries
import java.util.Scanner;
public class Milestone1 {
public static void main(String[] args) {
//define variables
Scanner scnr = new Scanner(System.in);
int patternDes = 0;
boolean world[][] = new boolean[Config.WORLD_ROWS][Config.WORLD_COLUMNS];
//print statements
System.out.println("Welcome to Conway's Game Of Life");
System.out.println("--------------------------------");
System.out.println("1)Glider 2)Beacon 3)Beehive 4)R-pentomino");
System.out.println("5)Random 6)Custom or 7)Exit");
System.out.print("Choose a pattern:");
//Have the scanner choose a pattern
patternDes = scnr.nextInt();
//check constraints
while(!(patternDes <= 7 && patternDes >= 1))
{
System.out.println("Enter a number between 1 and 7: ");
if(!scnr.hasNextInt()){
scnr.nextLine();
continue;
}
else{
patternDes = scnr.nextInt();
if((patternDes <= 7 && patternDes >= 1)){
break;
}
else{
continue;
}
}
}
//write another while loop now
}
}
This has also happened in many other codes, and it takes me forever to fix the particular method.
Is this what you want ?
Scanner scnr = new Scanner(System.in);
int patternDes;
do {
System.out.println("Enter a number between 1 and 7: ");
patternDes = scnr.nextInt();
}while (patternDes <= 7 && patternDes >= 1);

How can I read any user input from the scanner library?

I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!

I'm almost finished, but how to loop the entire program?

My cash register program is nearly complete, it can process sales and returns and adds or subtracts this to the money in the register.
My only problem is that once I'm done adding values for example, the program closes and i cant figure out how to loop it back to the choice menu. I tried using a do loop and a do while loop but it yelled at me saying it had invalid input (probably because you have to press F to stop when you're checking out).
How can I loop this whole thing?
import java.util.Scanner;
import java.util.ArrayList;
public class Assignment3_000848913
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Integer> Prices = new ArrayList<Integer>();
ArrayList<Integer> ReturnPrices = new ArrayList<Integer>();
int totalRegisterMoney = 0;
int Choice = 0;
System.out.print("What would you like to do?");
System.out.println();
System.out.print("Press 1. Process a sale");
System.out.println();
System.out.print("Press 2. Process a return");
System.out.println();
System.out.print("Press 3. Display Money in register");
System.out.println();
System.out.print("Press 4. Exit");
System.out.println();
Choice = in.nextInt();
if(Choice == 1)
{
//THIS LOOP READS IN ALL THE PRICES//
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the integer price of the item: $");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
int totalPrice = processSale(Prices);
totalRegisterMoney = totalRegisterMoney + totalPrice;
System.out.print("Your total comes to $");
System.out.println(totalPrice);
}
if(Choice == 2)
{
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the price of the returned item: $");
int j = in.nextInt();
ReturnPrices.add(j);
System.out.println();
}
while(in.hasNextInt());
int returnTotal = processReturn(ReturnPrices);
if(returnTotal > totalRegisterMoney)
{
System.out.print("Sorry, there's not that much money in the register.");
System.out.println();
}
else
{
totalRegisterMoney = totalRegisterMoney - returnTotal;
}
System.out.print("You've completed the return.");
System.out.println();
}
if(Choice == 3)
{
viewBalance(totalRegisterMoney);
}
}
//END OF MAIN
If you were getting that error when you did the do..while, you were doing it OK.
The problem is that after writing the 'F' to exit option 1 , the loop returns and tries to convert that 'F' into
Choice = in.nextInt();
This causes an error bucause a 'F' is not a number.
You would need to put an
in.next();
after your
while(in.hasNextInt());
This also would happen on option 2 in your code

Java: How to use a sentinel value to quit a program when the user wants

The only thing i am missing is to use a sentinel value, like zero, to quit the loop when the user wants, even without enter any gussing.
import java.util.Scanner;
import java.util.Random;
public class RandomGuessing {
//-----------------------------------------------------------------------------------------------
//This application prompt to the user to guess a number. The user can still playing until
//guess the number or want to quit
//-----------------------------------------------------------------------------------------------
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random rand = new Random();
int randNum = rand.nextInt(100) + 1;
System.out.println(randNum);
System.out.println("\t\tHi-Lo Game with Numbers\t\t\n\t Guess a number between 1 and 100!!!\n");
String ans;
int attemptsCount = 0;
do {
System.out.print("Guess the number: ");
int input = scan.nextInt();
while(input != randNum){
attemptsCount++;
if(input < randNum){
System.out.println();
System.out.print("low guessing\nEnter new number: ");
input = scan.nextInt();
}
else{
System.out.println();
System.out.print("high guessing\nEnter new number: ");
input = scan.nextInt();
}
}
System.out.println();
System.out.println("Congrats!!! You guess right\nAttempts: "+attemptsCount);
System.out.println();
System.out.print("You want to play again (yes/no): ");
ans = scan.next();
randNum = rand.nextInt(100) + 1; //generate new random number between same above range,
//if the user wants to keep playing.
}while (ans.equalsIgnoreCase("yes"));
}
}
Here's a simple approach:
// inside do loop
System.out.print("Guess the number (-1 to quit): ");
int input = scan.nextInt();
if (input == -1) {
break;
}
Try using this code for exiting totaly:
System.exit(0);

Categories

Resources