How to print elements of two char arrays in a specific way? - java

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]);
}

Related

Problem: printing an index, value of index, length index in an array has a loop

import java.util.Scanner;
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String max = parts[0];
int max_box; int parts_L = parts.length;
int max_L; int i;
for (i = 1; i < parts_L; i++) {
if (parts[i].length() > max.length()) {
max = parts[i];
max_box = i;
max_L = parts[i].length();
}
}
/* the problem occurs in the next line where it does not print the max value,
and it considers max_L without a value which I did give it a value in the
loop and the I value should be the same as the index of the longest
string but it gives me the last index in the array */
System.out.print("The longest word is " + max + " contain " +
max_L + " letters, in box " + i);
input.close();
}
}
The problem is that you are mixing i with max_box. The following should work as you expect:
public class missYou {
public static void main(String[] args) {
System.out.println("Words");
System.out.print("Enter words: ");
Scanner input = new Scanner(System.in);
String word = input.nextLine();
String[] parts = word.split(" ");
String longestWord = parts[0];
int longestWordSize = longestWord.length();
int longestWordLocation = 0;
for (int i = 1; i < parts.length; i++) {
if (parts[i].length() > longestWordSize) {
longestWord = parts[i];
longestWordLocation = i;
longestWordSize = longestWord.length();
}
}
System.out.print("The longest word is " + longestWord + " contain " +
longestWordSize + " letters, in box " + longestWordLocation);
input.close();
}
}
Additionally, try to be explicit when naming your variables, max_L and max_box are not very good names because they are hard to understand.

How to accept arguments in java from the user [duplicate]

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();

Program counts dots(.) as alphabetic characters

So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}
I believe you meant to use isLetter, not isAlphabetic.
Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?

Last word/sentence on an Array Java

I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.
Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}
it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}

Java : Occurances of a character in a String

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");
}
}

Categories

Resources