This question already has answers here:
How to read integer value from the standard input in Java
(7 answers)
Closed 3 years ago.
I'm trying to have the user input 2 strings into this function so that they can be compared.
I am not too familiar with java more familiar with c++ and I'm not a dev.
public class Levenshtein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
// j == 0; nw = lev(i -1, j)
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static void main(String [] args) {
String [] data = { "kitten", "Mitten" };
for (int i = 0; i < data.length; i += 2)
System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
}
}
just use the args in main
public static void main(String [] args) {
for (int i = 0; i < args.length; i += 2)
System.out.println("distance(" + args[i] + ", " + args[i+1] + ") = " + distance(args[i], args[i+1]));
}
and run it with java -jar app.jar kitten mitten
Here's an example of how to use Scanner to read inputs in Java.
Scanner s = new Scanner(System.in);
String first = s.nextLine();
String second = s.nextLine();
String[] nextTwo = s.nextLine().split(" ");
System.out.println(first);
System.out.println(second);
System.out.println(nextTwo[0]);
System.out.println(nextTwo[1]);
s.close();
Sample input
I am a teapot
Short and stout
Here is my handle
Sample output
I am a teapot
Short and stout
Here
is
As for how to apply this in your program, simply do the following:
public static void main(String [] args) {
// Using this construct, the "try-with-resources" block, will automatically
// close the Scanner resource for you
try(Scanner s = new Scanner(System.in) {
System.out.println("Enter first word:");
String first = s.nextLine();
System.out.println("Enter second word:");
String second = s.nextLine();
System.out.println(String.format("The distance is: %d",distance(first, second)));
}//Scanner s is automatically closed here
}
Note that you should generally NOT close the System.in stream, as it will disallow you from reading input in the rest of the program. However, as your program terminates in the scope of the try-with-resources block, it is acceptable to do so in this scenario.
One approach you can take to close Scanners linked to your System.in stream is to wrap System.in in a CloseShieldInputStream, as seen here.
You can use the scanner object:
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
I use Scanner for inputs from the Console.
U can do:
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sx.nextLine();
System.out.println("distance(" + s1 + ", " + s2 + ") = " + distance(s1, s2));
sc.close();
Related
Input:
2,3,1
5,2,3
Expected Output:
2,5,3,2,1,3
All digits should be separated with a comma.
My code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
char[] elms1 = input1.toCharArray();
String input2 = scanner.nextLine();
char[] elms2 = input2.toCharArray();
for (int i = 0; i < elms1.length; i++)
System.out.print(elms1[i] + "," + elms2[i]);
}
Alas, it outputs an unexpected result with extra commas and it looks like:
Input:
2,3,1
5,2,3
My Output is:
2,5,,,3,2,,,1,3
How can I eliminate extra commas to get the right output?
What you have to do is to just make a little change in your print statement as:
for (int i = 0; i < elms1.length; i++) {
if (i == elms1.length - 1) {
System.out.print(elms1[i] + "," + elms2[i]);
} else {
System.out.print(elms1[i] + "," + elms2[i] + ",");
}
}
You can do:
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
List<Integer> elms1 = Arrays.stream(input1.split(",")).map(Integer::parseInt).collect(Collectors.toList());
String input2 = scanner.nextLine();
List<Integer> elms2 = Arrays.stream(input2.split(",")).map(Integer::parseInt).collect(Collectors.toList());
for (int i = 0; i < elms1.size()-1; i++) {
System.out.print(elms1.get(i) + "," + elms2.get(i) + ",");
}
System.out.print(elms1.get(elms1.size()-1) + "," + elms2.get(elms1.size()-1));
Output (based on your input):
2,5,3,2,1,3
You can change your print statement for your current code which would take 2 characters from each array at a time considering commas to be a valid character input. Here's your code fix:
for (int i = 0; i < elms1.length; i += 2) {
if (i == elms1.length - 1)
System.out.print(elms1[i]+","+elms2[i]);
else
System.out.print(elms1[i]+""+elms1[i+1]+""+elms2[i]+""+elms2[i+1]);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.
I want to make the following changes:
1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.
2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.
3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.
Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.
So this is my code so far:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}
Try this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// Whatever is the input it take the first character.
char searchKey = input.nextLine().charAt(0);
countString(str, searchKey);
}
public static void countString(String str, char searchKey) {
// The count show both number and size of occurrence of searchKey
String count = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count += str.charAt(i) + "\n";
}
System.out.println(count + "\nNumber of Occurrence of "
+ searchKey + " is " + count.length() + " in string " + str);
}
You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.
public class Count {
static final int MAX_CHAR = 256;
private static void countString(String str, Character character) {
int [] counts = new int[MAX_CHAR];
char [] chars = str.toCharArray();
for (char ch : chars) {
if (character!=null && character!=ch) {
continue;
}
counts[ch]++;
}
for (int i=0; i<counts.length; i++) {
if (counts[i]>0) {
System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
countString(str, 'e');
}
}
you can take input from user "which character he/she wants to count".
To show the occurrence of character see code below.
You need to import java.util.Scanner class.
Here is your code:
import java.util.Arrays;
import java.util.Scanner;
public class Count {
public static void countString(String str)
{
if(str!=null) {
int length = str.length();
// Create an array of given String size
char ch[] = str.toCharArray();
Arrays.sort(ch);
if(length>0) {
char x = ch[0];
int count = 1;
for(int i=1;i<length; i++) {
if(ch[i] == x) {
count++;
} else {
System.out.println("Number of Occurrence of '" +
ch[i-1] + "' is: " + count);
x= ch[i];
count = 1;
}
}
System.out.println("Number of Occurrence of '" +
ch[length-1] + "' is: " + count);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();//"geeksforgeeks";
countString(str);
}
}
See the snippet below for a way to do it in Java8
public static void main(String[] args) {
// printing all frequencies
getCharacterFrequency("test")
.forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
// printing frequency for a specific character
Map<Character, Long> frequencies = getCharacterFrequency("test");
Character character = 't';
System.out.println("Frequency for t: " +
(frequencies.containsKey(character) ? frequencies.get(character): 0));
}
public static final Map<Character, Long> getCharacterFrequency(String string){
if(string == null){
throw new RuntimeException("Null string");
}
return string
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
You just have to modify this line of code:
using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
Edit: modified based on your comment, if you want the whole code
import java.util.*;
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j]){
//System.out.println(str.charAt(i));
find++;
}
}
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksfeorgeeks";
str = input.nextLine();
countString(str);
}
}
output
g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
List<String> l = Arrays.asList(str.split(""));
// prints count of each character occurence in string
l.stream().forEach(character->System.out.println("Number of Occurrence of " +
character + " is:" + Collections.frequency(l, character)));
if(!(Character.toString(value).isEmpty())) {
// prints count of specified character in string
System.out.println("Number of Occurrence of " +
value + " is:" + Collections.frequency(l, Character.toString(value)));
}
}
And this is the code with requirements mentioned in comments
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
String[] arr = str.split("");
StringBuffer tempString = new StringBuffer();
for(String s:arr) {
tempString.append(s);
for(char ch:s.toCharArray()) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString.chars().filter(i->i==ch).count());
}
}
if(!(Character.toString(value).isEmpty())) {
StringBuffer tempString2 = new StringBuffer();
for(String s:arr) {
tempString2.append(s);
for(char ch:s.toCharArray()) {
if(ch==value) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString2.chars().filter(i->i==ch).count());
}
}
}
}
}
}
You can use this code below;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char searchKey) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count++;
}
System.out.println("Number of Occurrence of "
+ searchKey + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(searchKey);
}
if (count > 0) {
System.out.println(count);
}
}
}
I would create a method such as the one below:
public static String stringCounter(String k) {
char[] strings = k.toCharArray();
int numStrings = strings.length;
Map<String, Integer> m = new HashMap<String, Integer>();
int counter = 0;
for(int x = 0; x < numStrings; x++) {
for(int y = 0; y < numStrings; y++) {
if(strings[x] == strings[y]) {
counter++;
}
}m.put(String.valueOf(strings[x]), counter);
counter = 0;
}
for(int x = 0; x < strings.length; x++) {
System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
}
return m.toString();
}
}
Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:
I tested the method in the main method by entering the String "Hello world":
System.out.println(stringCounter("Hello World"));
And here is our final output:
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
You get the number of times each character occurs in the String and you can use either the Map or print the output.
Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:
Please enter a String:
Hello World
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
I'm a beginner and I've been really stuck on this problem. I'm not really sure how I can display the number of customer(in an arraySize) (customer #1, customer #2...) and ask for their name in a for loop.
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + arraySize + ": "
}
I've tried dinerArray.length and then i, arraySize with i, (i=0;i<=arraySize;i++) with arraySize/i.. but nothing seems to work. It would either only print once with customer#0 or print nothing at all
You need to change arraySize to i. That way it will produce customer#1,customer#2 etc....
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + i+ ": ");
}
If you just want to read them from the console, you can use a Scanner:
Scanner input = new Scanner(System.in);
int arraySize = 10;
String[] dinerArray = new String[arraySize];
for(int i = 0; i < arraySize; ++i)
{
System.out.print("Enter the name of customer#" + (i + 1) + ": ");
dinerArray[i] = input.nextLine();
}
input.close();
im no Java dev but this is pretty basic.
The problem is that your for loop is just running if i is equal to arraySize, but this never happen.
So, try to change your '==' to a '<='
My solution:
Scanner scan = new Scanner(System.in);
int arraySize = 5;
String[] dinerArray = new String[arraySize];
for(int i = 1; i <= dinerArray.length; i++) {
ystem.out.print("pleas enter name for customer#" + i);
dinerArray[i - 1] = scan.nextLine();
}
Im not sure about the scanner think.
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:
4
1 4 3 2
The code will need to reverse the second input to the following:
2 3 4 1
My solution is as follow:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
System.out.print(arr[reverse_i]);
if(reverse_i != 0){System.out.print(" ");}
}
}
My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.
The easy way to reverse a string is using the StringBuilder class:
One option is to remove the spaces at the end of the string eg. remove last char
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
Another option is to check whether you are at the last arr_i of your loop.
If so, then don't add a space
package stackoverflow.main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
for(int arr_i = 0; arr_i < n; arr_i++){
sb.append(in.nextInt());
if (arr_i != 3
sb.append(" ");
}
String normal = sb.toString();
String reversed = sb.reverse().toString();
System.out.println("normal: " + normal);
System.out.println("reversed: " + reversed);
}
}
First reverse the array and then print it with a for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int arr_i=0; arr_i < n; arr_i++)
{
arr[arr_i] = in.nextInt();
}
for(int i = 0; i < arr.length / 2; i++)
{
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
}
}
It is all about output formatting. You may use this examples and become familiar with all possible approaches.
Your code can be improved in next two ways :
1) Use \t instead of Empty Space (\t is a tabulation)
2) Create a constant with output format like this private static final String output = "%d " and use it in output line like this : String.format(output, number) where number is your number that should be printed.
I need help on my code in Java.
This is the problem :
Example input : AaaaaAa
Output : A appears 7.
The problem is I need it to ignore cases.
Please help me, my code works fine, except that it doesn't ignore cases.
import java.io.*;
public class letter_bmp{
public static BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
public static void main(String[] args) throws Exception
{
String string1;
String pick;
String ans;
do
{
int count=0;
System.out.print("En taro Adun, Executor! Input desired string : ");
string1 = input.readLine();
System.out.print("Now, Executor...which character shall I choose : ");
pick = input.readLine();
for(int counter = 0; counter < string1.length(); counter++)
{
if(pick.charAt(0) == string1.charAt(counter))
count++;
}
System.out.print("Executor...you picked '" + pick + "' it is used " + count + " times in the word "+string1+".");
System.out.println("\nWould you like to try again, Executor? (Yes/No): ");
ans = input.readLine();
}
while(ans.equalsIgnoreCase("Yes"));
}
}
Convert the string to lower case characters using the String.toLowerCase() method.
// ...
string1 = input.readLine().toLowerCase();
// ...
pick = input.readLine().toLowerCase();
// ...
The easiest solution is to make 2 new strings like this:
string1_lower = string1.toLowerCase();
pick_lower = pick.toLowerCase();
And use those two variables during comparison.
I understand that the question is old and the OP might have got his answer. But i am putting this out here just in case if anybody needs it in the future.
public static void main(String[] args) {
String s="rEmember";
for(int i = 0; i <= s.length() - 1; i++){
int count = 0;
for(int j = 0; j <= s.length() - 1; j++){
if(Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))){
count++;
}
}
System.out.println(s.charAt(i) + " = " + count + " times");
}
}