Second console prompt fails in Java - java

This is a class assignment where I have to get the user to input three names, then sort them alphabetically in descending or ascending order based again on user input.
I've got the input of the names down and managed to find a way to sort them but my code fails when I ask the user to choose between ascending and descending (ie: my following if statements don't execute). I'm sure it's a simple explanation but I haven't been able to figure out what I'm doing wrong.
Here's the code:
package javaapplication9;
import java.util.Scanner;
public class JavaApplication9 {
public static void main(String[] args) {
String a = getInput("Enter the first name: ");
String b = getInput("Enter the second name: ");
String c = getInput("Enter the third name: ");
String ascending = getInput("Enter [A] for Ascending and [D]"
+ "for Descending order.");
// find first name alphabetically
String min = "";
if (a.compareTo(b) <= 0 && a.compareTo(c) <= 0)
{
min = a;
}
else if (b.compareTo(a) <= 0 && b.compareTo(c) <= 0)
{
min = b;
}
else if (c.compareTo(b) <= 0 && c.compareTo(a) <= 0)
{
min = c;
}
// find middle name alphabetically (and by descending order)
String middle = "";
if (a.compareTo(b)*a.compareTo(c) <= 0)
{
middle = a;
}
else if (b.compareTo(a)*b.compareTo(c) <= 0)
{
middle = b;
}
else if (c.compareTo(b)*c.compareTo(a) <= 0)
{
middle = c;
}
// find last name alphabetically
String last = "";
if (a.compareTo(b) >= 0 && a.compareTo(c) >= 0)
{
last = a;
}
else if (b.compareTo(a) >= 0 && b.compareTo(c) >= 0)
{
last = b;
}
else if (c.compareTo(b) >= 0 && c.compareTo(a) >= 0)
{
last = c;
}
// This is where I am having difficulty. This part of the program
// never executes when I run the file and I can't seem to figure
// out why.
if (ascending == "a")
{
System.out.println(min + " " + middle + " " + last);
}
if (ascending == "d")
{
System.out.println(last + " " + middle + " " + min);
}
} // end main function
private static String getInput(String prompt)
{
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
}

To properly compare strings in Java you need to use the equals(String compare) method of the String class.
Because you tell the user to enter uppercase letters, use the equalsIgnoreCase method instead:
if(ascending.equalsIgnoreCase("a")) {
System.out.println(min + " " + mid + " " + last);
}

When comparing strings, use .equals(), not ==.
Use this:
if (ascending.equals("a")){
instead of:
if (ascending == "a")
Full Code:
if (ascending.equals("a"))
{
System.out.println(min + " " + middle + " " + last);
}
if (ascending.equals("d"))
{
System.out.println(last + " " + middle + " " + min);
}

Related

Java program that teaches kid simple addition and subtraction

I feel like I'm almost there with the code but the problem is the while loop I am not allowed to use break and continue statements for this program. The first output test its suppose to have 14 questions where you get 12 right and 2 wrong giving you 86%. As for the second test you get a perfect score while the last test takes you to 20 questions that being the max number of questions, 4 of the first 8 questions correctly and 4 of the first 8 incorrectly, and then the next 12 correctly giving you 80% Code below:
package proj3;
import java.util.Scanner;
public class Project4App {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int correctNum = 0;
int wrongNum = 0;
double percent = 0;
int subNumCorrect = 0;
int subNumWrong = 0;
int addNumCorrect = 0;
int addNumWrong = 0;
int totalQuestions = 0;
while(!(correctNum == 10 && totalQuestions == 10) && !(percent >= 85.0 && totalQuestions >= 10) && (totalQuestions != 20)) {
Question Quest = new Question();
System.out.println("What is the result?" + "\n" + Quest.toString());
int userInt = scnr.nextInt();
if((Quest.getOperator() == '+') && (userInt == Quest.determineAnswer())) {
addNumCorrect += 1;
}
else if(Quest.getOperator() == '+' && (userInt != Quest.determineAnswer())) {
addNumWrong += 1;
}
if((Quest.getOperator() == '-') && (userInt == Quest.determineAnswer())) {
subNumCorrect += 1;
}
else if((Quest.getOperator() == '-') && (userInt != Quest.determineAnswer())) {
subNumWrong += 1;
}
if(userInt == Quest.determineAnswer()){
correctNum += 1;
System.out.println("Congratulations, you got it correct!");
}
else if (userInt != Quest.determineAnswer()){
wrongNum += 1;
System.out.println("The correct answer for " + Quest.toString() + " is " + Quest.determineAnswer());
}
totalQuestions++;
percent = Math.round((double)(correctNum * 100) / (totalQuestions));
}
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: " + percent + "%");
scnr.close();
}
}
I think this largely does what you want. A number of the counters weren't being modified as was intended. This is partly due to the amount going on in your main method making it hard to see what's going on (too much information). I've extracted functionality to smaller, more well defined methods.
You had a whole lot of logic effectively saying you want the user to have achieved 85% with at least 10 questions answered - and stop when 20 questions are asked. You could factor this condition out to a method returning a boolean isGameComplete(totalQuestions) and put this in the while condition-expression.
I've taken the liberty of implementing a question class based on the functionality that I think achieves the intention.
The correctPercent was rounded to an int which made it impossible to be == to 85.5%, say. I've converted this to a double so if you get more than 85%, say 85.25%, the game completes successfully.
Probably some other stuff I've added, which I've tried to comment in-line, if significant. Hopefully this is what you were after.
If it ever gets too difficult to understand, extracting small chunks of code to well named methods (even long ones) helps enormously, since it reduces your mental load.
class Project4App {
static final Scanner scanner = new Scanner(System.in);
static int correctNum = 0;
static int wrongNum = 0;
static int subNumCorrect = 0;
static int subNumWrong = 0;
static int addNumCorrect = 0;
static int addNumWrong = 0;
static int totalQuestions = 0;
static double percentCorrect = 0;
public static void main(String[] args) {
/**
* answer at least 9/10 questions correctly (to get 85%)
*/
while (percentCorrect < 85.0 && totalQuestions >= 10 && totalQuestions <= 20) {
Question question = new Question();
int userInt = getUsersAnswer(question);
boolean isCorrect = question.determineAnswer(userInt);
updateStatistics(question, isCorrect);
printResults(); // can remove this/comment this out - added to help with debugging
}
System.out.println();
System.out.println("------------ Game Complete! ------------");
printResults();
}
private static void printResults() {
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: (" + (addNumCorrect+subNumCorrect) + "/" + totalQuestions +") " + percentCorrect + "%");
System.out.println("The percent wrong: (" + (addNumWrong+subNumWrong) + "/" + totalQuestions +") " + (100 - percentCorrect) + "%");
}
private static int getUsersAnswer(Question question) {
System.out.println("What is the result?" + "\n" + question.toString());
int userInt = scanner.nextInt();
return userInt;
}
public static void updateStatistics(Question question, boolean isCorrect){
if (question.getOperator() == '+') {
if (isCorrect) {
addNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
addNumWrong++;
wrongNum++; // newly added - unused variable originall
}
} else { // operator is '-'
if (isCorrect) {
subNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
subNumWrong++;
wrongNum++; // newly added - unused variable originall
}
}
totalQuestions++; // newly added
percentCorrect = (correctNum * 100) / totalQuestions;
}
}
class Question {
private static final int UPPER_LIMIT_ON_RANDOM_NUMBERS = 20;
private static final Random random = new Random();
private final int number1;
private final int number2;
private final char operator;
public Question() {
operator = Math.random()>0.5 ? '+' : '-';
number1 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // NOTE THE SUBTRACTION NUMBER COULD BE NEGATIVE IF number2
number2 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // IS GREATER THAN number1.
}
public char getOperator() {
return operator;
}
public boolean determineAnswer(int userAnswer) {
switch (operator) {
case '+':
return userAnswer == (number1 + number2);
case '-':
return userAnswer == (number1 - number2);
}
return false; // shouldn't end up here - would be better to throw an unchecked exception and crash the program - new RuntimeException()
}
#Override
public String toString() {
return number1 + " " + operator + " " + number2;
}
}
Output:
------------ Game Complete! ------------
Progress Report:
Addition:
You got 7 correct and 0 incorrect.
Progress Report:
Subtraction:
You got 2 correct and 1 incorrect.
The percent correct: (9/10) 90.0%
The percent wrong: (1/10) 10.0%

Command program, mostly working, bugs here and there

I'm writing a program to take in commands from the user, and output accordingly. The program keeps asking for input, until the user inputs "Quit" as a command.
Commands are:
Factorial # (takes one number as an argument)
Outputs the factorial of the number, Ex.
Factorial 5
5! == 120
GCD # # (Takes 2 numbers as arguments)
outputs the greatest common divisor between 2 numbers (Recursively.) Ex.
gcd 5 10
gcd(5, 10) == 5
Sorted # #... (Takes as many numbers as the user wants)
checks to see if the numbers after the command are in order. Ex.
sorted 1 2 3 4 5
That list is sorted.
sorted 1 2 3 5 4
Out of order: 4 after 5.
Now all this works pretty good. nothing wrong as of now, what im struggling with, when the user enters a letter instead of a number, it should try and catch an InputMismatchException, this kind of works. for example.
if the user enters a letter it would say this.
Factorial j
Not a number: For input string: j
BUT
Factorial 5 j
5! == 120
it would go on how it normally would, but it takes the "j" as the next command, for so if i type Factorial 5 quit, it would print the factorial then quit, i don't know why this is happening.
another thing is i want to throw and catch an exception if the arguments are too much for the command, so the user cant type Factorial 5 10, and it would just calculate the factorial of 5, it would print an error message, i dont know how to achieve this.
Heres my code as of now.
A09.java
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
*
* #author Amr Ghoneim (A00425709)
*
*/
public class A09 {
static int counter = 0;
#SuppressWarnings("resource")
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.next().toLowerCase();
// FACTORIAL
if (commands[1].startsWith(command)
&& commands[1].contains(command)) {
try {
int num = scnr.nextInt();
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// GCD
} else if (commands[2].startsWith(command)
&& commands[2].contains(command)) {
try {
int numA, numB;
numA = scnr.nextInt();
numB = scnr.nextInt();
System.out.println("gcd(" + numA + ", " + numB + ") == "
+ GCD(numA, numB));
} catch (InputMismatchException ime) {
System.out.println(
"Not a number: For input string: " + scnr.next());
}
// SORTED
} else if (commands[0].startsWith(command)
&& commands[0].contains(command)) {
try {
List<Integer> nums = new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(scnr.nextLine(),
" ");
while (st.hasMoreTokens()) {
nums.add(Integer.parseInt(st.nextToken()));
}
sorted(nums);
} catch (NumberFormatException nfe) {
System.out.println("Not a number: For input string: ");
}
// QUIT
} else if (commands[4].startsWith(command)
&& commands[4].contains(command)) {
isValid = false;
quit();
// HELP
} else if (commands[3].startsWith(command)
&& commands[3].contains(command)) {
help();
}
}
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order"
+ "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)"
+ "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #"
+ "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of
them."
+ "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to
largest."
+ "\n If not, then where the first out-of-order number is."
+ "\n - help" + "\n This help message." + "\n - quit"
+ "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after "
+ nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}
What im missing is finding out how many arguments the user is putting, if too much print a message, and for the sorted command, i cant get it to print the letter the user puts. and for some reason when i input "Factorial 5 5" is would print the ">>>" twice instead of once. theres just some bugs here and there, can someone guide me on how i would approach this stuff, or show some examples?
Thanks!
I have modified your code so that it will work as what you have described. Just look at the code comments for details. Feel free to comment for clarifications.
Modified code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static int counter = 0;
public static void main(String[] args) {
String command;
String[] commands = { "sorted", "factorial", "gcd", "help", "quit" };
Scanner scnr = new Scanner(System.in);
intro();
help();
System.out.println("Please type in your command below.");
boolean isValid = true;
while (isValid) {
System.out.print(">>> ");
command = scnr.nextLine().toLowerCase(); // instead of getting the input per space, get all the input per
// line
String[] userCommand = command.split(" "); // split the line by spaces
// check if the command has at least 2 parameters except for "help" and "quit"
if (!commands[3].equals(userCommand[0]) && !commands[4].equals(userCommand[0]) && userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
// since you know that the first word will be the command, you just have to get
// the value of index 0
// FACTORIAL
// use equals do not use startsWith or contains since it will hold true for
// inputs "FACTORIALINVALID 4"
if (commands[1].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 2 parameters
if (userCommand.length != 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the factorial and convert it into an int
int num = Integer.parseInt(userCommand[1]);
if (num >= 0) {
System.out.println(num + "! == " + factorial(num));
} else {
System.out.println("Error: " + num + "! undefined");
}
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// GCD
// use equals do not use startsWith or contains since it will hold true for
// inputs "GCDINVALID 4 5"
} else if (commands[2].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must have exactly 3 parameters
if (userCommand.length != 3) {
System.out.println("Invalid command: " + command);
continue;
}
try {
// get the number for the GCD and convert it into an int
int numA, numB;
numA = Integer.parseInt(userCommand[1]);
numB = Integer.parseInt(userCommand[2]);
System.out.println("gcd(" + numA + ", " + numB + ") == " + GCD(numA, numB));
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// SORTED
// use equals do not use startsWith or contains since it will hold true for
// inputs "SORTEDINVALID 4 5 6"
} else if (commands[0].equals(userCommand[0])) {
// check if the command has the correct number of parameters, in this case it
// must at least 2 parameters
if (userCommand.length < 2) {
System.out.println("Invalid command: " + command);
continue;
}
try {
List<Integer> nums = new ArrayList<Integer>();
// get the list
for (int i = 1; i < userCommand.length; i++) {
nums.add(Integer.parseInt(userCommand[i]));
}
sorted(nums);
} catch (NumberFormatException e) {
System.out.println("Not a number: For input string: " + command);
}
// QUIT
// use equals do not use startsWith or contains since it will hold true for
// inputs "QUITINVALID"
} else if (commands[4].equals(userCommand[0])) {
isValid = false;
quit();
// HELP
// use equals do not use startsWith or contains since it will hold true for
// inputs "HELPINVALID"
} else if (commands[3].equals(userCommand[0])) {
help();
}
}
scnr.close();
}
public static void intro() {
System.out.println("This program can calculate factorials, "
+ "\nGCD, and check to see if a list of numbers are in order" + "\n-----------------------------------"
+ "\nMade by Amr Ghoneim (A00425709)" + "\n-----------------------------------");
}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
int num = 1;
for (int i = 1; i <= n; i++) {
num *= i;
}
return num;
}
}
public static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
public static void help() {
System.out.println("Valid commands are:" + "\n - factorial #" + "\n The product of all numbers from 1 to #."
+ "\n (The argument must not be negative.)" + "\n - gcd # #"
+ "\n The greatest common divisor of the two numbers."
+ "\n The biggest number that divides evenly into both of them." + "\n - sorted #..."
+ "\n Whether the numbers are in order from smallest to largest."
+ "\n If not, then where the first out-of-order number is." + "\n - help"
+ "\n This help message." + "\n - quit" + "\n End the program.");
}
public static boolean sorted(List<Integer> nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i - 1) > nums.get(i)) {
System.out.println("Out of order: " + nums.get(i) + " after " + nums.get(i - 1));
return false;
}
}
System.out.println("That list is sorted.");
return true;
}
public static void quit() {
System.out.println("Good-bye.");
System.exit(0);
}
}

Guessing game loop

Here is the code for a guessing game I have made. My counter in not increasing past 1. I am passing the parameters choice and generatedNumber from a seperate controller class. Should the do while loop be in the controller class?
public String startGuessingGame(int choice, int generatedNumber) {
int count = 0;
final int attempts = 4;
String result = null;
do {
count++;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
}
else if (choice > 50 || choice < 0) {
result = "Out of range. "
+ "\nPlease choose a number between 1 and 50.";
}
else if (choice > generatedNumber) {
result = "Attempt " + count + " "
+ " - You have guessed too high!";
}
else if (choice < generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed too low!";
}
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
}
while(count < attempts);
return result;
}
}
There is no loop here.
You're looking for something like while(count < attempts).
Try this:
Incrementing the counter at the end before the while condition:
do{
...
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
count++;
}while(count < attempts);
return result;
...
You need to make count a class variable (member) of your controller class and have your do/while loop in that class so that the startGuessingGame only handles the validation of the user choice. Something like this but the code is far from complete
public class SomeControllerClass() {
final int attempts = 4;
int count = 0;
public void someMethod() {
int choice = 0;
do {
choice = getChoice();
count++;
String text = otherClass.startGuessingGame(choice, generatedNumber);
while (count < attempts);
}
and the method only does validation
public String startGuessingGame(int choice, int generatedNumber) {
String result = null;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
} else if (choice > 50 || choice < 0) {
//and so on
return result;
}

Why can't my binary search find the passwords I am generating for my array of strings?

import java.util.*;
import java.io.*;
public class A3 {
public static void main(String args[])
{
Accept inputScanner = new Accept();
Assign3 sortObj = new Assign3();
String lname[] = {"","","","",""};
String psw[] = {"","","","",""};
String input;
do
{
System.out.println("Password Generator");
System.out.println("Please enter 5 last names:");
for (int index = 0; index < lname.length; index++)
{
System.out.print("Please enter last name: ");
lname[index] = inputScanner.acceptInputString();
psw[index] = sortObj.generatePassword(lname, index);
}
sortObj.sortArrayDescending(lname);
sortObj.arrayDisplay(lname, psw);
Screen.scrollscreen(70, 1, '=');
System.out.print("Please enter name to search (e or E to exit):");
input = inputScanner.acceptInputString();
int password = sortObj.binSrch(lname, input);
if(password >= 0)
{
System.out.println("Name: " + input + " ===> " + "password: " + password);
System.out.println("++++++++++++++++++++++++++++++++++");
}
else
{
System.out.println(input + " is not found");
System.out.println("++++++++++++++++++++++++++++++++++");
}
}while(input.equals("e") && input.equals("E"));
}
public void sortArrayDescending(String[] lnameArray)
{ String temp;
for(int j = 1; j < lnameArray.length - 1; j++)
{
for(int index = 0; index < lnameArray.length - 1; index++)
{
if(lnameArray[index].trim().compareTo(lnameArray[index+1].trim())<0)
{
temp = lnameArray[index];
lnameArray[index] = lnameArray[index + 1];
lnameArray[index + 1] = temp;
}
}
}
}
public void arrayDisplay(String lnameContent[], String pswContent[])
{
for(int i = 0; i < lnameContent.length; i ++)
{
System.out.println(lnameContent[i] + " " + pswContent[i]);
}
}
public int binSrch(String strArr[], String search)
{
int mid = -1;
int first = 0;
int last = strArr.length - 1;
boolean found = false;
while(first <= last)
{
mid = (first + last) / 2;
if(strArr[mid].equalsIgnoreCase(search))
{
found = true;
break;
}
else if(strArr[mid].compareToIgnoreCase(search) < 0)
{
last = mid - 1; //use lower half
}
else
{
first = mid + 1; //use upper half
}
}
if(!found)
{
mid = -1;
}
return mid;
}
public String generatePassword(String[] str, int index)
{
String name = str[index];
char first = name.charAt(0);
char last = name.charAt(name.length()-1);
int mid = 0;
if(first != last)
{
mid = ( ((int)(first) + ((int)(last)) / 2) );
}
else
{
mid = ( ((int)(first) + ((int)(last)) / 3) );
}
Random rNum = new Random();
int randomNum = rNum.nextInt(5);
String password = (first + "" + (char)(mid) + "" + randomNum).toLowerCase();
return password;
}
public void duplicateCheck(String[] password)
{
}
}
OUTPUT
Password Generator
Please enter 5 last names:
Please enter last name: magnum
Please enter last name: bauer
Please enter last name: sahid
Please enter last name: austen
Please enter last name: reese
sahid m?0
reese b?0
magnum s¥4
bauer a?0
austen r¤0
======================================================================
Please enter name to search (e or E to exit):sahid
Name: sahid ===> password: 0
++++++++++++++++++++++++++++++++++
//this line is supposed to print out "m?0" because it is the password
that was generated for "sahid" so why is it printing "0"? And how can I make it
print out "m?0" or whatever random password my program generates for it?
Your code is correct. Remember that password is the index of the psw[] String Array and not the actual content of the Array.
You just have to write psw[password] instead of password in the following line:
System.out.println("Name: " + input + " ===> " + "password: " + password);
/* Correction Here : Replace password --> psw[password] */
Corrected code snippet:
if(password >= 0)
{
System.out.println("Name: " + input + " ===> " + "password: " + psw[password]);
System.out.println("++++++++++++++++++++++++++++++++++");
}
Now, you should get output as follows:
Name: sahid ===> password: m?0
EDIT : Also, as mentioned by #Gyanapriya you'll have to sort psw[] array in addition to the lname[] unless you are trying to assign the random passwords to the users.

String index out of bounds? (Java, substring loop)

This program I'm making for a COSC course isn't compiling right, I keep getting the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.substring(String.java:1765)
at VowelCount.main(VowelCount.java:13)
Here's my code:
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input, letter;
Scanner scan = new Scanner (System.in);
System.out.println ("Please enter a string: ");
input = scan.nextLine();
while (count <= input.length() ) {
letter = input.substring(count, (count + 1));
if (letter == "a") {
a++; }
if (letter == "e") {
e++; }
if (letter == "i") {
i++; }
if (letter == "o") {
o++; }
if (letter == "u") {
u++; }
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
To my knowledge this should work, but why doesn't it? Any help would be great. Thank you!
You may need to take out the = in the line
while (count <= input.length() ) {
and make it
while (count < input.length() ) {
because it is causing the substring to read beyond the length of the string.
===============
But I'll add a few extra bits of advice even though its not asked for:
do not use == to compare strings, use
letter.equals("a")
instead. Or even better, try using
char c = input.charAt(count);
to get the current character then compare like this:
c == 'a'
I think your loop condition should be count < input.length. Right now, the last iteration runs with count == length, so your substring call is given a start index after the last character in the string, which is illegal. These type of boundary errors are very common when writing such loops, so it's always good to double- and triple-check your loop conditions when you encounter a bug like this.
Also, comparing strings with the == operator usually won't do what you want. That compares whether or not the two variables reference the same object. Instead, you want to test string1.equals(string2), which compares the contents of the two strings.
Removing the equal sign should fix that.
while (count < input.length()) {
and since you want to get a single character, you should do this:
substr(count,1)
because the 2nd parameter is actually length, not index.
Fixed it with help from everyone, and especially Vincent. Thank you! Runs wonderfully.
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) {
int a = 0, e = 0, i = 0, o = 0, u = 0, count = 0;
String input;
char letter;
Scanner scan = new Scanner (System.in);
System.out.print ("Please enter a string: ");
input = scan.nextLine();
while (count < input.length() ) {
letter = input.charAt (count);
if (letter == 'a')
a++;
if (letter == 'e')
e++;
if (letter == 'i')
i++;
if (letter == 'o')
o++;
if (letter == 'u')
u++;
count++;
}
System.out.println ("There are " + a + " a's.");
System.out.println ("There are " + e + " e's.");
System.out.println ("There are " + i + " i's.");
System.out.println ("There are " + o + " o's.");
System.out.println ("There are " + u + " u's.");
}
}
Before loop,try below
if(input.length()>0){
//you code
}

Categories

Resources