I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}
Related
Ask the user to "Input a number: " 4 times.
If the input is not a number, ask again.
Output "success." after they have entered 4 numbers.
Please answer this code for me using while, if, if else and do statements.
int counter; System.out.print("Input a number: ");
while(!(scan.hasNextInt()));{
for (int i = 0; i < 3; i++){
scan.next();
System.out.print("Input a number: ");
if (!(pass.equals(pass2))) {
counter++;
} else if (!(scan.hasNextInt())) {
}
}
if (counter >= 2) {
System.out.println("Input a number: ");
}
} else if (!(scan.hasNextInt())) { System.out.println("success."); }
This is very basic stuff but I am struggling.
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in);
int counter = 0;
while(counter < 4) {
System.out.println("Input a number: ");
String input = scan.next();
if(input.matches("[-]?[0-9]*")){ // Checking, if input is an integer
inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
counter++;
} else {
System.out.println("Input is not an integer");
}
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner
I need to do Football Results Generator. I created 4 arrays with 10 elements each, but I need to include a loop that allows the user to change their mind and stop input by typing "quit" after a certain number of entries. Could you please help - I am new to programming, so it must be dead simple.
import java.util.Scanner;//
public class Football_Results_Generator
{
public static void main(String[] args)
{
Scanner kbd = new Scanner (System.in);
String[] HomeTeam = new String[10];
String[] AwayTeam = new String[10];
int[] HomeScore = new int[10];
int[] AwayScore = new int[10];
int index = 0;
int sum = 0;
int sum1 = 0;
do
{
System.out.print("Enter Home Team Name: ");
HomeTeam[index] = kbd.nextLine();
System.out.print("Enter Away Team Name: ");
AwayTeam[index] = kbd.nextLine();
System.out.print("Enter Home Team Score:");
HomeScore[index] = kbd.nextInt();
System.out.print("Enter Away Team Score: ");
AwayScore[index] = kbd.nextInt();
kbd.nextLine();
} while(index < 10);
index = 0;
System.out.println();
do
{
System.out.println(HomeTeam[index] + " [" + HomeScore[index] + "]" + " | " + AwayTeam[index] + " [" + AwayScore[index] + "] ");
index = index + 1;
} while(index < 10);
kbd.close();
for(index = 0; index < 10; index++)
sum += HomeScore[index];
for(index = 0; index < 10; index++)
sum1 += AwayScore[index];
System.out.println();
System.out.println("Totals");
System.out.println("-------------------------------");
System.out.println("Total number of matches played: " + index);
System.out.println("Total of all home scores: " + sum);
System.out.println("Total of all away scores: " + sum1);
System.out.println("Total number of draws: ");
System.out.println("The highest home score: ");
System.out.println("The highest away score: ");
}
}
allow user to change his mind and stop input by typing quit after 5 tries.
Use a temp variable to capture String input:
String line;
do
{
System.out.print("Enter Home Team Name: ");
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
HomeTeam[index] = line;
.....
index = index + 1; //missed
}while(index < 10);
index = 0;
Here, "quit".equalsIgnoreCase(line) will ensure that irrespctive of case of line e.g. "Quit","QUIT","quit",etc will result true
What about integer input to array?? is it same concept ??
Well, you need to handle the exception in case input is neither quit nor int:
line = kbd.nextLine();
if("quit".equalsIgnoreCase(line)){
break;
}
try{
HomeScore[index] = new Integer(line);
} catch(NumberFormatException e){
//Error conversion string to int
}
Couple issues I am having with my fibonacci code. If I want to find the location of number 5 in the array (input), the system says its location is 5, but it should say 6? Also, if I enter a number that is not in the array, the system says it is found in location 20 (example input 200). System should say it is "not found"
int totalFibos=20;
int fibs[] = new int[totalFibos];
int a=0;
int b=1;
int fib=0;
fibs[0]=0;
fibs[1]=1;
int fibCounter=2;
while(fibCounter<totalFibos)
{
fib=a+b;
a=b;
b=fib;
fibs[fibCounter]=fib;
fibCounter++;
}
System.out.println("\n\nThe first "+ totalFibos + " fibonacci numbers are: ");
int i=0;
while(i<totalFibos)
{
System.out.print(fibs[i]+" ");
i=i+1;
}
System.out.println();
int userInput=0;
i=0;
Scanner sc= new Scanner(System.in);
int found=0;
while(userInput!=-1)
{
System.out.print("Enter a number to search,(enter -1 to end the search): ");
userInput= sc.nextInt();
while (i<totalFibos)
{
if(userInput==fibs[i])
{
found=1;
break;
}
i++;
}
if(found==1)
System.out.println("The number: " + userInput + " is found at location: "+ i++);
else if (found==0)
System.out.println("The number: "+ userInput + " is not found");
}
if(userInput==-1)
System.out.println("\nThanks");
}
}
Note that you have ";" sign after if statement in
if(userInput==fibs[i]);
{
found=1;
break;
}
That is why it expression in {} is always executed.
Remove the ";" and add i++; somewhere inside the while loop for this to work.
Update:
Also reset your counter and result after every input. This should be the first thing inside your while loop:
found = 0;
i = 0;
Here is your refactored code :
int totalFibos=20;
int fibs[] = new int[totalFibos];
int a=0;
int b=1;
int fib=0;
fibs[0]=0;
fibs[1]=1;
int fibCounter=2;
while(fibCounter<totalFibos)
{
fib=a+b;
a=b;
b=fib;
fibs[fibCounter]=fib;
fibCounter++;
}
System.out.println("\n\nThe first "+ totalFibos + " fibonacci numbers are: ");
int i=0;
while(i<totalFibos)
{
System.out.print(fibs[i]+" ");
i=i+1;
}
System.out.println();
int userInput=0;
i=0;
Scanner sc= new Scanner(System.in);
int found=0;
while(userInput!=-1)
{
System.out.println("Enter a number to search,(enter -1 to end the search): "); //Shouldnt this be println ?
userInput= sc.nextInt();
i=0; //Reset it, else the second search would fail
found=0; //Reset it, else the second search would fail
while (i<totalFibos)
{
if(userInput==fibs[i]);
{
found=1;
break;
}
i++; //Change state of i
}
if (found==1) { //Wheres your bracket ?
System.out.println("The number: " + userInput + " is found at location: "+ Integer.toString(i+1)); //Just to be sure...
}
else if (found==0) {
System.out.println("The number: "+ userInput + " is not found");
}
}
if(userInput==-1)
System.out.println("\nThanks");
}
Hope it works and helps you !
I have the following piece of code where I'm trying to get the user to only enter integers; if a string is entered then it would display a system out error message "please only enter numbers" and then it would show the "Enter your ID#:" again. I tried using the try/catch method but was not using it correctly -- still a beginner. I know I can use the "NumberFormatException" but not sure where. Can anyone help? Thanks!
//Get Customer ID and Account Number
do
{ System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
} while (!(match));
Exceptions should be for exceptional circumstances. I suggest you use a Scanner and hasNextInt() to just continue when it isn't an int. That is make a Scanner like,
Scanner input = new Scanner(System.in);
and then something like this would work,
do {
System.out.print("Enter your ID#: ");
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
custid = input.nextInt();
System.out.print("Enter your Account Number#: ");
custacctnum = input.nextInt();
if (!input.hasNextInt()) {
System.out.printf("%s is not an int.%n", input.nextLine());
continue;
}
If you really want to use try-catch it should look something like,
do
{
try {
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) &&
(people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname
+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println("" + (p+1) + ": " +cluster[p].year+","
+ cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname
+ ", what color car would you like?");
break;
}
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
} while (!(match));
#Elliott Frisch, I "played" around with it before I saw your answer and figured out how to use the try/catch. It was fairly simple, but I will look at the other option that you posted. With the updated code below when the user enters a string, it will display the error message and then take them to the "Enter your ID#" line to try again.
Thank you all so much for the quick response.
do
{
try{
System.out.print("Enter your ID#: ");
custid = Integer.parseInt(input.readLine());
System.out.print("Enter your Account Number#: ");
custacctnum = Integer.parseInt(input.readLine());
//validate the choice
for(int i=0; i<people.length; i++)
{ if ((people[i].custid == custid) && (people[i].custacctnum == custacctnum))
{ match = true;
System.out.println("Welcome " +people[i].firstname+ " to JJ Dealership!");
for(int p=0; p<cluster.length; p++)
System.out.println(+(p+1)+ ": " +cluster[p].year+"," +cluster[p].make+ "," +cluster[p].model);
System.out.println(people[i].firstname+ ", what color car would you like?");
break;
}
}
if (!match)
{ System.out.println("Invalid ID");
}
} catch (NumberFormatException e)
{System.out.println ("Error! Please enter a number!");}
} while (!(match));
I cannot figure this problem out. Everything in the program works the way i want it to except after i use the 'o' open account option, 'w' withdrawal accout options.. etc that after completion, repeats the loop as desired, but returns the else line "Command was not recognized; please try again." and then reprints the menu. If i use the 's' command it works fine. i removed the "balance = input.nextDouble();" line and it works correctly, but i can't figure out why it returns the else statement and reprints.
import java.util.Scanner;
import java.text.*;
public class Bank
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
String eol = System.getProperty("line.separator");
DecimalFormat df = new DecimalFormat("0.00");
int numAccounts = 1;
String number = "None Selected";
String userInput;
double balance = 0;
double amount = 0;
int i = 0;
int j;
BankAccount[] accounts = new BankAccount [100];
accounts[0] = new BankAccount (number, balance);
String BBalance = df.format(accounts[i].getBalance());
while (1 < 2){
if (numAccounts == accounts.length){
BankAccount[] tempArray = new BankAccount[accounts.length * 2];
for (int k = 0; k < accounts.length; k++){
tempArray[k] = accounts[k];
}
accounts = tempArray;
}
try{
System.out.print ( eol +
"-----------------------------------------------------" + eol +
"|Commands: o - Open account c - Close account|" + eol +
"| d - Deposit w - Withdraw |" + eol +
"| s - Select account q - Quit |" + eol +
"-----------------------------------------------------" + eol +
"Current account: " + accounts[i].getNumber() + " Balance: $" + df.format(accounts[i].getBalance()) +
eol );
}
catch(java.lang.Throwable t) {
System.out.println("Account number was not found");
}
userInput = input.nextLine().trim().toLowerCase();
if (userInput.substring(0).equals("o")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Initial Balance: ");
balance = input.nextDouble();
accounts[numAccounts++] = new BankAccount (number, balance);
i = numAccounts - 1;
continue;
}
else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
accounts[i].deposit(amount);
continue;
}
else if (userInput.substring(0).equals("s")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++){
if (accounts[i].getNumber().equals(number)){
break;
}
}
if (i != numAccounts){
System.out.print("Account number was not found");
}
continue;
}
else if (userInput.substring(0).equals("c")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
accounts[i] = accounts[--numAccounts];
continue;
}
else if (userInput.substring(0).equals("w")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
for (i =0; i < numAccounts; i++)
if (accounts[i].getNumber().equals(number))
break;
System.out.print("Enter Amount To Withdraw: ");
amount = input.nextDouble();
accounts[i].withdraw(amount);
continue;
}
else if (userInput.substring(0).equals("q")) {
System.exit(0);
}
else{
System.out.println("Command was not recognized; please try again.");
continue;
}
}
//System.out.print(userInput);
//System.out.print(accounts[0]);
}
}
Here's the BankAccount class:
public class BankAccount {
String number = "123-456";
double balance = 1.00;
public BankAccount(String accountNumber, double initialBalance){
number = accountNumber;
balance = initialBalance;
}
public void deposit (double amount){
balance += amount;
}
public void withdraw (double amount){
balance -= amount;
}
public String getNumber(){
return number;
}
public double getBalance(){
return balance;
}
BankAccount[] accounts = new BankAccount [100];
}
You're not skipping past the end of the lines when you're reading in the second numbers in the commands that require one.
Adding an input.nextLine() to those is one quick way around it (non I/O lines redacted).
// etc.
} else if (userInput.substring(0).equals("d")) {
System.out.print("Enter Account Number: ");
number = input.nextLine();
System.out.print("Enter Amount To Deposit: ");
amount = input.nextDouble();
input.nextLine();
continue;
} // etc.