output comes out to an integer when I want a string - java

import java.util.Scanner;
public class QuestionTwo{
public static void main(String[] args) {
Integer number;
Character first, middle, last;
Scanner keyboard = new Scanner(System.in);
System.out.print("First name: ");
first = keyboard.next().charAt(0);
System.out.print("Middle name: ");
middle = keyboard.next().charAt(0);
System.out.print("Last name: ");
last = keyboard.next().charAt(0);
System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
number = keyboard.nextInt();
if (number == 1) {
System.out.println("Sort order: 1");
if ((first) < (middle) && (first) < (last)) {
if ((middle) < (last)) {
System.out.println(first + middle + last);
}
if ((last) < (middle)) {
System.out.println(first + last + middle);
}
}
if ((middle) < (first) && (middle) < (last)) {
if ((first) < (last)) {
System.out.println(middle + first + last);
}
if ((last) < (first)) {
System.out.println(middle + last + first);
}
}
if ((last) < (middle) && (last) < (first)) {
if ((middle) < (first)) {
System.out.println(last + middle + first);
}
if ((first) < (middle)) {
System.out.println(last + first + middle);
}
}
}
if (number == 2) {
System.out.println("Sort order: 2");
if ((first) > (middle) && (first) > (last)) {
if ((middle) > (last)) {
System.out.println(first + middle + last);
}
if ((last) > (middle)) {
System.out.println(first + last + middle);
}
}
if ((middle) > (first) && (middle) > (last)) {
if ((first) > (last)) {
System.out.println(middle + first + last);
}
if ((last) > (first)) {
System.out.println(middle + last + first);
}
}
if ((last) > (middle) && (last) > (first)) {
if ((middle) > (first)) {
System.out.println(last + middle + first);
}
if ((first) > (middle)) {
System.out.println(last + first + middle);
}
}
}
}
}
The output that I get from this is a large integer value, whereas what the program should do is ask for a first name, then middle name, then last name. It should then ask for which sort order, 1 being ascending and 2 being descending. What this means is that once it gets the name it looks through the names and counts the number of letters per name. It will then give the answer as the name sorted in the order that the user selected.
For example:
if I tell it my name is David H. Anderson, and click 1 for ascending order, my result should be "H. David Anderson", as H. is 2 symbols, David is 5 and Anderson is 8.
What it currently does is all of the above except for giving me the last line int he format I want (I end up just getting a number).

I would change a few things to get you started.
Firstly, your input should probably be a String
Secondly, remove .charAt(0)
Then compare the String lengths before printing them.

Try this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main2 {
private static ArrayList<String> splitAndSortFullName(String fullName, int sortOrder) {
String[] names = fullName.split(" "); //Split names by space character.
//Create a list with only non-empty names:
ArrayList<String> namesList = new ArrayList();
for (int i=0; i<names.length; ++i)
if (!names[i].isEmpty())
namesList.add(names[i]);
switch (sortOrder) {
case 1: Collections.sort(namesList); break;
case 2: Collections.sort(namesList, (a, b) -> { return b.compareTo(a); }); break;
}
return namesList;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = keyboard.nextLine(); //Read the full name. For example "John D. Doe".
System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
int number = keyboard.nextInt();
System.out.println(splitAndSortFullName(fullName, number));
//For use with many full names, just re-call the method splitAndSortFullName(...). For examples:
System.out.println("Full examples:");
System.out.println(splitAndSortFullName("John D. Doe", 1));
System.out.println(splitAndSortFullName("Alice K. Example", 2));
System.out.println(splitAndSortFullName("Martin T. Anderson", 1));
}
}
In this code, the user enters his complete name fully.

import java.util.Scanner;
public class QuestionTwo
{
public static void main(String[] args)
{
Integer number;
String first, middle, last;
Scanner keyboard = new Scanner (System.in);
System.out.print("First name: ");
first = keyboard.next();
System.out.print("Middle name: ");
middle = keyboard.next();
System.out.print("Last name: ");
last = keyboard.next();
System.out.print("Which type of sort order would you like (1 for ascending and 2 for descending)? ");
number = keyboard.nextInt();
int firstLength = first.length();
int middleLength = middle.length();
int lastLength = last.length();
if(number == 1)
{
System.out.println("Sort order: 1");
if(firstLength < middleLength && firstLength < lastLength)
{
if(middleLength < lastLength)
{
System.out.println (first + " " + middle + " " + last);
}
if(lastLength < middleLength)
{
System.out.println (first + " " + last + " " + middle);
}
}
if(middleLength < firstLength && middleLength < lastLength)
{
if(firstLength < lastLength)
{
System.out.println (middle + " " + first + " " + last);
}
if(lastLength < firstLength)
{
System.out.println (middle + " " + last + " " + first);
}
}
if(lastLength < middleLength && lastLength < firstLength)
{
if(middleLength < firstLength)
{
System.out.println(last + " " + middle + " " + first);
}
if(firstLength < middleLength)
{
System.out.println(last + " " + first + " " + middle);
}
}
}
if(number == 2)
{
System.out.println("Sort order: 2");
if(firstLength > middleLength && firstLength > lastLength)
{
if(middleLength > lastLength)
{
System.out.println (first + " " + middle + " " + last);
}
if(lastLength > middleLength)
{
System.out.println (first + " " + last + " " + middle);
}
}
if(middleLength > firstLength && middleLength > lastLength)
{
if(firstLength > lastLength)
{
System.out.println (middle + " " + first + " " + last);
}
if(lastLength > firstLength)
{
System.out.println (middle + " " + last + " " + first);
}
}
if(lastLength > middleLength && lastLength > firstLength)
{
if(middleLength > firstLength)
{
System.out.println(last + " " + middle + " " + first);
}
if(firstLength > middleLength)
{
System.out.println(last + " " + first + " " + middle);
}
}
}
}
}
Listening to the comments and with help from thanopi57, I was able to get the proper answer. The first thing I did was to remove the ".AtChar(0)" and define the variables as Strings, not Characters. I then defined the variables as variable length, with variable xxxx becoming int xxxxLength=xxxx.Length();, doing this for all three variables (which converted them from String to Int). I then replaced the subsequent concatenation operands with my newly defined variables, I also added " " for spaces inbetween operands in the println lines.

Related

Printing results from an array seperately from user input in java

So I'm trying to create a program that takes in the student's GPA and prints out if they are graduating at an honor's level, graduating, or not graduating. I have most of the code figured out, but I am trying to make it so that ALL of the input is first, and then it will go back and print out whether each student is graduating. But what I am getting is printing out the graduation status for each student immediately after the input for that student.
I'm getting this:
Enter the number of GPAs: 3
GPA #0: 3.99
Student #0: Summa Cum Laude
GPA #1: 3.1
Student #1: Graduating
GPA #2: 2
Student #2: Graduating
When I want this:
Enter the number of GPAs: 3
GPA #0: 3.99
GPA #1: 3.1
GPA #2: 2
Student #0: Summa Cum Laude
Student #1: Graduating
Student #2: Graduating
Here is my code:
System.out.print("Enter the number of GPAs: ");
int size = sc.nextInt();
int array[] = new int[size];
double gpa;
for (int i = 0; i < size; i++) {
System.out.print("GPA #"+ i + ": " );
gpa = sc.nextDouble();
if (gpa >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (gpa >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (gpa >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (gpa >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}}
First you need to fill the array with values GPA we declare an array of double
double array[] = new double[size];
We iterate through for loop and we ask user to enter GPA and we fill our array with those values
for (int i = 0; i < size; i++) {
System.out.print("GPA #" + i + ": ");
gpa = sc.nextDouble();
array[index++] = gpa;
}
Now we have array with our values filled so what should we do know we print it by checking array values with our if statements.
for(int i=0;i<array.length;i++){
if (array[i] >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (array[i] >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (array[i] >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (array[i] >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}
}
FULL CODE
System.out.print("Enter the number of GPAs: ");
int size = sc.nextInt();
double array[] = new double[size];
double gpa;
int index = 0;
for (int i = 0; i < size; i++) {
System.out.print("GPA #" + i + ": ");
gpa = sc.nextDouble();
array[index++] = gpa;
}
for(int i=0;i<array.length;i++){
if (array[i] >= 3.90) {
System.out.println("Student #" + i + ": Summa Cum Laude");
} else if (array[i] >= 3.70) {
System.out.println("Student #" + i + ": Magna Cum Laude");
} else if (array[i] >= 3.50) {
System.out.println("Student #" + i + ": Cum Laude");
} else if (array[i] >= 2.0) {
System.out.println("Student #" + i + ": Graduating");
} else {
System.out.println("Student #" + i + ": Not graduating");
}
}
}
}
It sounds like you want to have one list of GPA's immediately followed by another list of status'. If that is the case, then you have 2 separate lists, which will require 2 separate loops.
Make a loop that prints out your GPA's, then after that loop finishes, have another loop that prints out the status'. Also, you will need some way to store those values from the first loop. Maybe an array?

How to end the while loop with either player1 or player2 entering "Q"?

I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn

how do I pass a user inputted integer through methods?

Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}

Getting a string from a scanner when a number is entered

I am trying to write a program that ask a user for 2 numbers and then ask the user to pick a command from a menu by entering the correspond number to the command.
I can write the program if i take the input as an Int but cannot figure it out for a string, also it has to be a string.
I am having problems when it enters the while loop to validate the user input it does not stop when the statement is false it will stay in the loop I can not figure out what i am doing wrong.
Here is the code i have.
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
System.out.println();
while (!input.equals(1) && !input.equals(2) && !input.equals(3) && !input.equals(4)) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
System.out.println();
if (input.equals(1)) {
System.out.print(L + " * " + R + " = " + (L * R));
} else if (input.equals(2)) {
System.out.print(L + " / " + R + " = " + (L / R));
} else if (input.equals(3)) {
System.out.print(L + " + " + R + " = " + (L + R));
} else {
System.out.print(L + " - " + R + " = " + (L - R));
}
}
stdIn.close();
}
}
Any help would be much appreciated.
Thank you in advanced.
The line input = stdIn.next(); is taking input as String
while your comparison is against integer. So a String never equals Int
You may try changing your while loop condition to:
while (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
note the double quote around the numbers
Is answered, but check this
import java.util.Scanner;
public class ab {
public static void main(String[] args) {
System.out.println("-------------------------------------");
Scanner stdIn = new Scanner(System.in);
double L;
System.out.print("Enter the left operand: ");
L = stdIn.nextDouble();
double R;
System.out.print("Enter the right operand: ");
R = stdIn.nextDouble();
System.out.println("-------------------------------------");
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subraction");
System.out.println("-------------------------------------");
String input;
System.out.print("Choose one of the following commands by enterning the corresponding number: ");
input = stdIn.next();
while (true) {
if (!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4")) {
System.out.print("Invalid entry, please type a valid number (1, 2, 3 or 4): ");
input = stdIn.next();
} else {
if (input.equals("1")) {
System.out.print(L + " * " + R + " = " + (L * R));
break;
} else if (input.equals("2")) {
System.out.print(L + " / " + R + " = " + (L / R));
break;
} else if (input.equals("3")) {
System.out.print(L + " + " + R + " = " + (L + R));
break;
} else {
System.out.print(L + " - " + R + " = " + (L - R));
break;
}
}
}
stdIn.close();
}
}

Java String letter counter not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my code for a program that should count the number of each letter in an inputted string. When I run the program, it says that there is 0 of each letter, no matter what I input. Thanks for the help in advance!
import java.util.Scanner;
public class stringprogram {
public static void stringinputmethod()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
int strslength = strs.length();
int numa = 0;
int numb = 0;
int numc = 0;
int numd = 0;
int nume = 0;
int numf = 0;
int numg = 0;
int numh = 0;
int numi = 0;
int numj = 0;
int numk = 0;
int numl = 0;
int numm = 0;
int numn = 0;
int numo = 0;
int nump = 0;
int numq = 0;
int numr = 0;
int nums = 0;
int numt = 0;
int numu = 0;
int numv = 0;
int numw = 0;
int numx = 0;
int numy = 0;
int numz = 0;
for(int i = 0; i <= strslength; i++)
{
if (strs.substring(i, i) == "a")
{
numa = numa + 1;
}
if (strs.substring(i, i) == "b")
{
numb = numb + 1;
}
if (strs.substring(i, i) == "c")
{
numc = numc + 1;
}
if (strs.substring(i, i) == "d")
{
numd = numd + 1;
}
if (strs.substring(i, i) == "e")
{
nume = nume + 1;
}
if (strs.substring(i, i) == "f")
{
numf = numf + 1;
}
if (strs.substring(i, i) == "g")
{
numg = numg + 1;
}
if (strs.substring(i, i) == "h")
{
numh = numh + 1;
}
if (strs.substring(i, i) == "i")
{
numi = numi + 1;
}
if (strs.substring(i, i) == "j")
{
numj = numj + 1;
}
if (strs.substring(i, i) == "k")
{
numk = numk + 1;
}
if (strs.substring(i, i) == "l")
{
numl = numl + 1;
}
if (strs.substring(i, i) == "m")
{
numm = numm + 1;
}
if (strs.substring(i, i) == "n")
{
numn = numn + 1;
}
if (strs.substring(i, i) == "o")
{
numo = numo + 1;
}
if (strs.substring(i, i) == "p")
{
nump = nump + 1;
}
if (strs.substring(i, i) == "q")
{
numq = numq + 1;
}
if (strs.substring(i, i) == "r")
{
numr = numr + 1;
}
if (strs.substring(i, i) == "s")
{
nums = nums + 1;
}
if (strs.substring(i, i) == "t")
{
numt = numt + 1;
}
if (strs.substring(i, i) == "u")
{
numu = numu + 1;
}
if (strs.substring(i, i) == "v")
{
numv = numv + 1;
}
if (strs.substring(i, i) == "w")
{
numw = numw + 1;
}
if (strs.substring(i, i) == "x")
{
numx = numx + 1;
}
if (strs.substring(i, i) == "y")
{
numy = numy + 1;
}
if (strs.substring(i, i) == "z")
{
numz = numz + 1;
}
}
System.out.println("Number of a's: " + numa + "\n" + "Number of b's: " + numb + "\n" + "Number of c's: " + numc + "\n" + "Number of d's: " + numd + "\n" + "Number of e's: " + nume + "\n" + "Number of f's: " + numf + "\n" + "Number of g's: " + numg + "\n" + "Number of h's: " + numa + "\n" + "Number of i's: " + numi + "\n" + "Number of j's: " + numj + "\n" + "Number of k's: " + numk + "\n" + "Number of l's: " + numl + "\n" + "Number of m's: " + numm + "\n" + "Number of n's: " + numn + "\n" + "Number of o's: " + numo + "\n" + "Number of p's: " + nump + "\n" + "Number of q's: " + numq + "\n" + "Number of r's: " + numr + "\n" + "Number of s's: " + nums + "\n" + "Number of t's: " + numt + "\n" + "Number of u's: " + numu + "\n" + "Number of v's: " + numv + "\n" + "Number of w's: " + numw + "\n" + "Number of x's: " + numx + "\n" + "Number of y's: " + numy + "\n" + "Number of z's: " + numz);
}
public static void main(String[] args)
{
stringinputmethod();
}
}
Correct usage of the substring method:
strs.substring(i, i)
needs to be
strs.substring(i, i + 1)
because the char at lastIndex is not included in the output.
Correct comparison of Strings in Java
Also, as pointed out in the comments to this answer, you are comparing Strings with the == operator.
This will only works as long as both your Strings are the same object. For proper comparison you need to use strs.substring(..).equals()
Proper storing of data
Additionally, as already suggested in a comment to your question, you should start using arrays to save data like this.
Instead of
int numa = 0;
....
int numz = 0;
you should use arrays, or even better Map<Character,Integer>.
strs.substring(i, i) == "a" have two problems:
substring(i, i) creates string from i (inclusive), till i (exclusive) which means it creates empty string ""
this is not how we compare Strings. == may work sometimes if strings are pooled, but for dynamically created strings you need to use equals instead of == because Strings are objects, or even better use charAt(i) to get primitive char which you can be able to compare like strs.charAt(i) == 'a' (notice ' instead of ").
You can also use enhanced for loop on array of characters representing your string to avoid charAt. You should probably also be working on lower case characters as pointed in this comment. So your code can look more like
for (char ch : strs.toLowerCase().toCharArray()){
//do something based on value of `ch`
}
Try this:
It is a little bit shorter than your implementation (which is very good, but still a little bit verbose). Use Java 8 with this code, otherwise it won't compile.
What does it do?
If you understand that a string is nothing more but an array you can iterate over that array and see what kind of value is at the given index. The value at this index is put in a map (remember, a map is a key-value-store). So if you put the Integer 1 in the map where its key is "a", that means "a" occurs 1 time.
By reading the values at the appropriate indexii (very sophisticated plural form of index) with HashMap.get("a") and then incrementing the value by one, we have a nice little letter counter... without the need to predefine numa=0 and so forth. Give it a try and let me know if it werx.
package lettercounter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
*
* #author edm
*/
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
String strs = scan.nextLine();
//this map will be populated with the occurrence of the letters in the string.
HashMap<String, Integer> countenLetters = new HashMap<>();
//the next line generates a key-value-store whose key is the letter in the string
//and the value is the accumulated occurrence of said letter.
Arrays.asList(strs.split("")).stream().forEach((String letter) -> {
Integer count = 0;
try {
count = countenLetters.get(letter).intValue();
} catch (Exception e) {
//tried to access a non existing value in the map
//this happens if there is a letter which was not set in the map until now.
//i.e. the first time the letter is encountered.
//this is no error. could have done it with an if also.
}
countenLetters.put(letter, ++count);
});
//do with this stuff what you want;
countenLetters.forEach((k,v) -> {
System.out.println("Letter "+k+" occurs "+v+" times in the string.");
});
}
}

Categories