Stop duplicate input (scanner & arrays) - java

I'm fairly new at programming. Currently im working on a uni project to create a basic text game using java. The problem im having is trying to figure out how to implement a business rule that does not allow a user to enter the same name. I have it set up so the scanner reads into the array. I'm using Java and this is my first time using the forum so i greatly appreciate any help given and thank all of you in advance!:)
And apologies for the poor formatting i dont know how to post properly yet.
try {
// Takes in the number of players
int noOfPlayers;
Scanner s = new Scanner(System.in);
System.out.println("Enter number of players between 2 and 4");
noOfPlayers = s.nextInt();
s.nextLine();
if (noOfPlayers < 2 || noOfPlayers >= 5) { // limits number of players enter no less than 2 and no greater than 4
System.out.println("Nope wrong number");
enterInfo();
s.close();
return;
} else {
// array for storing player names
String[] names = new String[noOfPlayers];
// iterates through the array depending how many players are selected
// and takes in String input
for (int counter = 0; counter < noOfPlayers; counter++) {
System.out.println("Enter name of player : " + (counter + 1));
names[counter] = s.nextLine();
// fix this to stop same name sbeing entered
//if(names.equals(names)) {
// System.out.println("Enter a different name");
// counter--;
// }
}
}
s.close();
} catch (Exception e) {
System.out.println("Problem");
}
}

How about use Set? Set has to have all different things.
Like in Array [kim,lee,kim,park] but in Set [kim,lee,park]
input kim => Array [kim] set[kim] lenth 1 == size 1
input lee => Array [kim,lee] set[kim,lee] lenth 2 == size 2
input kim => Array [kim,lee,kim] set[kim,lee] lenth 3 != size 2
then all you have to do is tell them "make another name plz"
String name = s.nextLine();
names[counter] = name;
Set<String> set = new HashSet<String>();
set.add(name)
if(names.length != set.size())
{
System.out.println("Enter a different name");
counter--;
}
I hope you understand my poor explanation.

Related

Replacing Position in Array Amongst Other Methods

Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.
I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method

How to find an element in an array [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 2 years ago.
I currently have a programming assignment. In the assignment, I have to have two array that I need to store the data of a store's stock with. I use the first array for the Manager to access. I use the second array for the Cashier to access.
The manager may add the code, name, price, and quantity of up to 15 items.
The cashier may add the code and quantity of any item. If the code of the does not exist in the manager's array, the program will automatically exit.
The elements of the arrays are not in the same order for both array lists. So how do I make sure that the item code that the cashier has entered, actually exists in the Manager's array?
This is how I have declared the arrays:
String[] stockItemCode = new String[15];
String[] stockItemName = new String[stockItemCode.length];
int[] stockItemQuantity = new int[stockItemCode.length];
double[] stockItemPrice = new double[stockItemCode.length];
String[] saleItemCode = new String[stockItemCode.length];
String[] saleItemName = new String[stockItemCode.length];
int[] saleItemQuantity = new int[stockItemCode.length];
double[] saleItemPrice = new double[stockItemCode.length];
This is how the manager enters items:
// 3- The manager:
// 3.1- The manager has to login to add the items to the inventory list. The username and password are "Manager" and "Man_2020" respectively.
if (username.equals(managerUsername) && password.equals(managerPassword))
{
// 3.2- Once the manager is logged in, he will enter the item's code, name, quantity, and price.
do
{
System.out.println("Please enter item code: ");
stockItemCode[stockItemLimit] = sc.next();
System.out.println("Please enter item name: ");
stockItemName[stockItemLimit] = sc.next();
System.out.println("Please enter item quantity (numbers only): ");
stockItemQuantity[stockItemLimit] = sc.nextInt();
System.out.println("Please enter item price (numbers only): ");
stockItemPrice[stockItemLimit] = sc.nextDouble();
stockItemLimit++;
// 3.3- After entering the above information for each item, the program prompts the manager to continue or logout of his account. He has to use 'L' or 'S' to sign-out.
System.out.println("Would you like to stop the program? Entering S or L will stop the program");
logoutPrompt = sc.next().charAt(0);
}
while(!(logoutPrompt == 'L' || logoutPrompt == 'S'));
}
This is how I have tried to compare the elements of the arrays (I know it's wrong, but I don't know why. I'm very new to programming).
// 4- The sales employee:
// 4.1- The sales employee logs in to scan the sold items and print the receipt. The username and password are "Sales" and "Sale_2020" respectively.
else if (username.equals(salesUsername) && password.equals(salesPassword))
{
i = 0;
// 4.2- The sales employee, enters the *code* and the *quantity* of the sold item.
do
{
System.out.println("Please enter item code: ");
saleItemCode[i] = sc.next();
System.out.println("Please enter item quantity (numbers only): ");
saleItemQuantity[i] = sc.nextInt();
saleItemName[i] = stockItemName[i]; //This is the problem
saleItemPrice[i] = stockItemPrice[i]; //This is the problem
// 4.3- The program calculates the total price of the transaction, by using the quantity and the price of the sold items.
if(saleItemCode[i] == stockItemCode[i])
{
saleItemPrice[i] = stockItemPrice[i] * saleItemQuantity[i];
// 4.4- The program has to deduct the sold quantity of the items from the stock list.
stockItemQuantity[i] = stockItemQuantity[i] - saleItemQuantity[i];
// 4.5- After entering each item, the employee is prompted to continue adding the item to the receipt, or print it (by using 'P').
System.out.println("Would you like to print the receipt by entering P? Enter anything else to continue adding items.");
logoutPrompt = sc.next().charAt(0);
}
else
{
// If the code is entered incorrectly, the program skips to 4.5.
System.out.println("Would you like to print the receipt by entering P? Enter anything else to continue adding items.");
logoutPrompt = sc.next().charAt(0);
}
i++;
}
while(logoutPrompt != 'P');
Also, whenever I try to print the information of the stock's items while in the Cashier's loop, the arrayElements return as null as if they do not exist even though they clearly do.
for(i = 0; i <= stockItemLimit; i++) //COME HERE
{
int indexNumb = i+1;
System.out.println(indexNumb + "\t" + saleItemCode[i] + "\t" + saleItemName[i] + "\t" + "$" + saleItemPrice[i] + "\t" + saleItemQuantity[i]);
}
All help would be appreciated.
You find an element in an unsorted array by looping over all elements and comparing each.
int stockitemindex = -1;
for(int searchindex = 0; searchindex <= stockItemLimit; searchindex++) {
if (stockItemCode[searchindex].equals(saleItemCode[i])) {
stockitemindex = searchindex;
break;
}
}
It's not clear from your description why the arrays of stockitem and saleitem have the same size. It's not even clear if you need an array for saleitem. Just a String code and int quantity would seem enough.
Also in your loop at the end of your question, you access saleitem array, not stockitem array, that's why you get null contents.

Allow user to input unique values

I'm trying to get input from the user to select players from an ArrayList. All the players in the ArrayList have a unique ID the user selects 5 - 8 players to start the program but I do not want to allow the user to input the same ID again as it will have a duplicate.
Heres what I m trying to do
I still am not getting this I tried this
public void SelectAthlete(){
Data ath = new Data();
ath.athleteData();
boolean choice = true;
int p=0;
String id;
int value =0;
Scanner input = new Scanner(System.in);
System.out.println();
do{
System.out.println();
System.out.print("\tEnter the number of Participants you want to Compete: ");
p=input.nextInt();
System.out.println("\tYou have Decided to compete with" +" " + p + " " +"Athletes");
if(p>=5 && p<=8){
System.out.println("\tEnter the Athlete ID : ");
for (int i=0;i<p;i++){
value=0;
id = input.next();
if(id.substring(0,1).equals("R") || id.substring(0,1).equals("P")){
for(int k=0;i<Data.AthleteData.size();k++)
{
if(Data.AthleteData.get(k).getID().contains(id))
{
value++;
choice = Data.Inputlist.add(id);
}
else if (!choice)
{
value--;
System.out.println("Please Enter Unique Value");
input.nextLine();
}
for(int j = 0; j<Data.AthleteData.size();j++)
{
if(id.equals(Data.AthleteData.get(j).getID()))
{
value++;
}
}
}
}
if(value!=0)
{
Data.Inputlist.add(id);
}
else
{
System.out.println("Enter a valid ID (in UPPER Case)");
input.nextLine();
i--;
}
}
choice = false;
}
else{
System.out.println("\n\tHowever You need to have
atleast 5 Athletes or atmost 8 Athletes to Start a game.");
input.nextLine();
}
for (int m=0;m<Data.AthleteData.size();m++){
if (Data.Inputlist.contains(Data.AthleteData.get(m).getID()))
{
System.out.println(Data.AthleteData.get(m));
}
}
}while(choice);
You could use a HashSet and see the response of the add method as follows:
Set<String> someSet = new HashSet<String>();
boolean isUnique = someSet.add("abc");
System.out.println(isUnique); // this will output true as abc does not already exist in the set and add operation was successful
isUnique = someSet.add("abc");
System.out.println(isUnique); //this will output false as abc already exists in the set and hence cannot be added again
But since you are using a Custom Object and not a String, you will need to declare the set as follows:
Set<YourClass> someSet = new HashSet<YourClass>();
In addition to that you will need to make sure that the equals method in YourObject class is implemented correctly too.
You can refer to these links for more information about equals: http://www.geeksforgeeks.org/overriding-equals-method-in-java/
and
https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/
There are many ways you can do this.
1.) After taking number you can loop back to check if it exist in the Arraylist.(NOT RECOMMENDED) as it have high runtime complexity.
2.) Simply you can use contains() method of arraylist to check if it is present already.
3) You can use a bitset for number and set it true when ever they are assigned.Later you can compare it with the bool value to check if it set or not. see https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html for more info on bitset

Is there a way to print a variable, alter the same variable and print the two of them in a list?

First off I'm sorry if this is a wierd one, but I don't exactly know what I'm trying to do in coding terms.
To clarify what I wish to do, I want to know a way to "Save" the value of receipt to either a list/set/array then go trough the process that determined the value of receipt and save that to the list again, and when I print the list the two different values of receipt are printed after eachoter.
Lets say first time the value of receipt was determined it was equal to x, then after I've saved that to a list and gone trough the same value determening process receipt= y and I add that to the list. Would it print: x and then y. Or y and y? And if it prints the new value of receipt twice, how do I make it print the two different values after eachother?
import java.util.Scanner;
public class TicketV005
{ // start of public class
public static void main (String [] args)
{ // start of main
Scanner keyboard = new Scanner(System.in);
int printedTickets,ticketTotal;
String fareType, purchaseLoc;
String answer1 =("null");
String receipt =("null");
int zoneAmount = 0;
double price = 0;
int answer2 = 0;
System.out.print("How many tickets do you wish to buy?(Answer with a number please.) ");
ticketTotal = keyboard.nextInt();
printedTickets = 0;
while (ticketTotal <= 0)
{
System.out.println("\nIncorrect input, try again.");
System.out.println("How many tickets do you wish to buy?(Answer with a number please.) ");
ticketTotal = keyboard.nextInt();
}
while(ticketTotal !=printedTickets )
{
System.out.print("Welcome! Are you buying a reduced fare ticket?(y/n) ");
answer1 = keyboard.next();
if (answer1.equals("y"))
fareType=("reduced fare");
else if (answer1.equals("n"))
fareType=("standard fare");
else
fareType=("null");
while (fareType.equals("null"))
{
System.out.println("\nIncorrect input, try again.");
System.out.println("Welcome! Are you buying a reduced fare ticket?(y/n) ");
answer1 = keyboard.next();
}
System.out.println("Would you like to purchase your ticket at 1. the automated services or at 2. the cashier? ");
answer2 = keyboard.nextInt();
if (answer2 ==1)
purchaseLoc=("automated services");
else if (answer2 ==2)
purchaseLoc=("cashier");
else
purchaseLoc=("null");
while (purchaseLoc.equals("null"))
{
System.out.println("\nIncorrect input, try again.");
System.out.println("Would you like to purchase your ticket at 1. the automated services or at 2. the cashier? ");
answer2 = keyboard.nextInt();
}
System.out.println("How many zones will you be travelling? (1-3) ");
zoneAmount = keyboard.nextInt();
while (zoneAmount <= 0 || zoneAmount > 3 )
{
System.out.println("\nIncorrect input, try again.");
System.out.println("How many zones will you be travelling? (1-3) ");
zoneAmount = keyboard.nextInt();
}
//Start of reduced fare
if (answer1.equals("y") && answer2 == 1 )
{ // Start of automated services reduced fare
for (int i= 1 ; i <= 3 ; i++)
{
if (zoneAmount == i)
price=(10*i)+10;
}
} //end off automated services reduced fare
if (answer1.equals("y") && answer2 == 2)
{ // Start of cashier reduced fare
for (int i= 1 ; i <=3 ; i++)
{
if (zoneAmount == i)
price=(14*i)+14;
}
} //End of cashier reduced fare
//End of reduced fare
//Start of standard fare
if (answer1.equals("n") && answer2==1)
{ //Start of standard fare automated services
for (int i = 1; i <=3 ; i++)
{
if ( zoneAmount ==i)
price=(18*i)+18;
}
} // end of standard fare automated servies
if (answer1.equals("n") && answer2==2)
{ // Start of standard fares cashier
for (int i = 1; i <=3 ; i++)
{
if( zoneAmount == i)
price=(22*i)+22;
}
} // End of standard fares cashier
//End of standard fare
System.out.println("");
receipt = (zoneAmount+" zone(s), "+ fareType+", bought at: "+ purchaseLoc+". Your price: "+price+" SEK.");
System.out.println(receipt);
printedTickets++;
System.out.println(""); //Empty line for when/if it repeats
} // end of while printedTickets is not equal to ticketTotal
}// end of main
}// end of public class
Edit1: Included full code for clarity.
Edit2: Better Clarification
It looks like you're asking two questions. One relates to whether you can save a variable and the other is about how to have a bunch of things aggregated together. From your code it's not clear what your aims are.
In java, the things you declare, like
String receipt
are references. This means they keep track of a piece of data. However, other things can also keep track of that same piece of data. So:
String receipt1 = "100EUR";
String receipt2 = receipt1;
In the above code, there's only one thing in memory with "100EUR" in it, and both receipt1 and receipt2 are looking at it. If something came along and modified one of them
receipt1 = "200EUR";
The other would be unaffected.
System.out.println(receipt1);
System.out.println(receipt2);
// output would be
200EUR
100EUR
In a lot of cases once something has been assigned to a reference via the = symbol, you can imagine that the reference is always going to have access to it, unchanged until the next time the = symbol is used to assign the reference to point to something else. However, in Java objects can change state, so if you had
List<String> myList = new ArrayList<String>():
and things started calling methods on myList to modify its contents, then the myList reference would feel like it's referring to something that changes. The reference itself is not changing, just the object it points to.
I brought the subject round to lists since you probably are trying to keep track of all receipts somewhere after creating them, and the list has an add function that will do that nicely for you.
If you want to print out the whole contents of the list, then you could have a loop:
for(String line:myList) {
System.out.println(line);
}
You can use a StringBuilder to append the new Strings. Alternatively, you can simply concatenate tow Strings with the +-Operator, but this is really inefficient in terms of execution time.
First you can declare an ArrayList of Strings:
ArrayList<String> receipts = new ArrayList<>();
Then add the value of the receipt variable:
receipts.add(receipt);
At the end you can print all elements of ArrayList
for (String s : receipts)
System.out.println(s);
I would use a StringBuilder, and keep on adding what you want in the loop, adding a newline to it at the end of the loop:
public static void main(String[] args)
{
StringBuilder receipt;
//Other variable initializations
Also, your while loop could probably be changed to a for loop:
for (int i = 0; i < ticketTotal; i++)
{
receipt.append(zoneAmount);
receipt.append(" zone(s), ");
receipt.append(fareType);
receipt.append(", bought at: ");
receipt.append(purchaseLoc);
receipt.append(". Your price: ");
receipt.append(price);
receipt.append(" SEK.\n");
}
Then when you need to just print your StringBuilder:
System.out.println(receipt.toString());

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources