Want to find the output as given below using Java program? - java

Input text: are you ready
Output text: ArE YoU ReAdY
Help me what i am missing.
Below is the code which I am using:
import java.util.Scanner;
import java.lang.*;
public class Testdemo{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String result = "";
System.out.println("enter the string");
String name =sc.nextLine();
String[] words = name.split("\\s");
for(int i=0;i<words.length;i++){
String med = words[i];
for(int j=0;j<med.length;j++){
if(i%2 == 0){
result = result + Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1) + " ";
}
else{
result = result + Character.toLowerCase(words[i].charAt(0)) + words[i].substring(1) + " ";
}
}
}
System.out.println(result);
}
}

Scanner sc = new Scanner(System.in);
StringBuffer result = new StringBuffer();
System.out.println("enter the string");
String name = sc.nextLine();
String[] words = name.split("\\s");
for (int i = 0; i < words.length; i++) {
String med = words[i];
for (int j = 0; j < med.length(); j++) {
if (j % 2 == 0) {
result.append(Character.toUpperCase(words[i].charAt(j)));
} else {
result.append(Character.toLowerCase(words[i].charAt(j)));
}
}
result.append(" ");
}
System.out.println(result);

Related

Can this lengthy if-else Java code be improved by using arrays?

I'm trying to simplify this Java code by adding arrays, but I'm having difficulty.
The code that I have so far that works:
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
char number0 = '0';
char number1 = '1';
char number2 = '2';
char number3 = '3';
char number4 = '4';
char number5 = '5';
char number6 = '6';
char number7 = '7';
char number8 = '8';
char number9 = '9';
int count0 = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == number0) {
count0++;
}
else if (line.charAt(i) == number1) {
count1++;
}
else if (line.charAt(i) == number2) {
count2++;
}
else if (line.charAt(i) == number3) {
count3++;
}
else if (line.charAt(i) == number4) {
count4++;
}
else if (line.charAt(i) == number5) {
count5++;
}
else if (line.charAt(i) == number6) {
count6++;
}
else if (line.charAt(i) == number7) {
count7++;
}
else if (line.charAt(i) == number8) {
count8++;
}
else if (line.charAt(i) == number9) {
count9++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
System.out.println(" 0 " + count0);
System.out.println(" 1 " + count1);
System.out.println(" 2 " + count2);
System.out.println(" 3 " + count3);
System.out.println(" 4 " + count4);
System.out.println(" 5 " + count5);
System.out.println(" 6 " + count6);
System.out.println(" 7 " + count7);
System.out.println(" 8 " + count8);
System.out.println(" 9 " + count9);
System.out.println(" -----------");
}
}
}
However, it's kind of a brute-force attack. The spot of difficulty I'm running into is figuring out where to create and pass arrays. Since the code has to read the external file, should the arrays be created and passed in the while statement?
For further reference, the text file that is being read looks like this:
Thistle Map
The goal is to count the occurrences of digits only.
As you stated, you could use arrays.
I would suggest 2 arrays
One to hold the digits to catch
Second one for the counts
Initialization of the arrays
char[] numbers = new char[10];
//initialize of numbers(char) to count
for(int i = 0; i < numbers.length; i++) {
numbers[i] = (char) ('0' + i);
}
int[] counts = new int[10]; //no initialization needed because int is default 0
In the for-loop where you iterate over the line, add a nested for loop, that iterates over the numbers-array. Here is the whole while loop:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
for(int j = 0; j < numbers.length; j++) {
if(line.charAt(i) == numbers[j]) {
counts[j]++;
}
}
}
}
For the output just use another for over the arrays:
for(int i = 0; i < numbers.length; i++) {
System.out.println(" "+ numbers[i] +" " + counts[i]);
}
Edit: Another solution using a Map
//...
Map<Character, Integer> charCounts = new HashMap<>();
for (int i = 0; i < 10; i++) {
charCounts.put((char) ('0' + i), 0);
}
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
charCounts.computeIfPresent(line.charAt(i), (key, val) -> val + 1);
}
}
//...
for (Character number : charCounts.keySet()) {
System.out.println(" " + number + " " + charCounts.get(number));
}
With this solution you can easily extend your program to count any occuring character. Just remove the initialization of the map and add this line below the computeIfPresent.
charCounts.putIfAbsent(line.charAt(i), 1);
With Java 8 you can use Files.lines to get a Stream of all the lines in a file.
Then you can transform the stream to a stream over every char using flatMap and in the end collect it to a map that has the Character as key and the count of the character as value.
try (Stream<String> stream = Files.lines(Paths.get(fileName)) {
Map<Character, Long> charCountMap = stream
.flatMap(line -> line.chars().mapToObj(c -> (char) c))
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(" 0 " + charCountMap.getOrDefault('0', 0));
} catch (IOException e) {
e.printStackTrace();
}
Probably the way I would do it in a real world scenario, because it's short, but just for practice the other answers are better.
Yes. I would say it can be simplified a great deal with an array. You don't need seperate sentinels for the values, you can check they are in range and then use Character.digit to parse them. Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) >= '0' && line.charAt(i) <= '9') {
count[Character.digit(line.charAt(i), 10)]++;
}
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < count.length; i++) {
System.out.printf(" %d %d%n", i, count[i]);
}
System.out.println(" -----------");
}
You can use a single array for this and index notation. Each array index should hold the quantity of digits. Much more clear.
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Homework4A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter name of the input file: ");
String fileName = scan.next();
try (Scanner inFile = new Scanner(new FileReader(fileName))) {
int[] count = new int[10];
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
try {
int c = Character.getNumericValue(line.charAt(i));
count[c] += 1;
} catch (Exception e) { }
}
}
System.out.println("\n-= Count of Thistles in =-");
System.out.println("-= the Hundred Acre Wood =-\n");
System.out.println(" -----------");
System.out.println(" type count");
System.out.println(" -----------");
for (int i = 0; i < 10; i++)
System.out.println(" " + i + " " + count[i]);
System.out.println(" -----------");
}
}
}

Why is it that my character counter not increasing when the for loop goes?

I'm currently coding a program that takes in a string and a single character (if you decide to put a single one in that is) and (is supposed) to check how many times that character is in the string and at the end print out the amount of times it is in there. For some reason it isn't working and I would like some help; thank you!
import java.util.Scanner;
public class HowManyChars {
public HowManyChars() {
Scanner sc = new Scanner (System.in);
String askPhrase;
String askChar;
int charCounter = 0;
System.out.println("Enter a phrase");
askPhrase = sc.nextLine();
System.out.println("Enter a letter");
askChar = sc.nextLine();
for (int i = 0; i < askPhrase.length(); i++) {
if (askPhrase.substring(i, i + 1) == askChar) {
charCounter = charCounter + 1;
}
}
System.out.println("There are " + charCounter + " " + askChar + " in " + askPhrase);
}
}
I give credit for this answer to #Mushif, who correctly figured out the problem. Your current comparison logic is comparing a string against a character:
for (int i=0; i < askPhrase.length(); i++) {
// String char
if (askPhrase.substring(i, i + 1) == askChar) {
charCounter = charCounter + 1;
}
}
Try iterating the character set of the input word and then compare apples to apples:
for (int i=0; i < askPhrase.length(); i++) {
if (askPhrase.charAt(i) == askChar) {
charCounter = charCounter + 1;
}
}
You could also use an enhanced loop directly on the input's character set:
for (char chr : askPhrase.toCharArray()) {
if (chr == askChar) {
charCounter = charCounter + 1;
}
}
import java.util.Scanner;
public class HowManyChars {
public HowManyChars() {
Scanner sc = new Scanner (System.in);
String askPhrase;
char askChar;
char[] askChars;
int charCounter = 0;
System.out.println("Enter a phrase");
askPhrase = sc.nextLine();
askChars = askPhrase.toCharArray();
System.out.println("Enter a letter");
askChar = sc.next().charAt(0);
sc.close();
for (int i = 0; i < askChars.length; i++) {
if (Character.toLowerCase(askChar) == Character.toLowerCase(askChars[i])) {
charCounter ++;
}
}
System.out.println("There are " + charCounter + " " + askChar + " in " + askPhrase);
}
}

Print specific characters

I have a string input which, that input have a team name and score separated by one space. e.g bb 3 , teamd 5 the winner should be teamd
In order to get the winner team that scored highest score, i'm doing following:
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String str = "";
String winnerTeam = "";
int winnerScore = 0, countedChar = 0;
for (int i = 0; i < cases; i++) {
str += scanner.nextLine();
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
countedChar++;
if (arr[i] == ' ') {
if (str.charAt(i + 1) > winnerScore) {
winnerTeam = "";
winnerScore = (int) str.charAt((int) i + 1);
for (int j = 0; j < countedChar; j++) {
winnerTeam += str.charAt(j);
}
countedChar = 0;
} else {
//winnerTeam = "";
countedChar = 0;
}
}
}
System.out.println(winnerTeam);
}
But it's not work prefect, It's print wired result, how to make that work as expect ?
I haven't tried your code, But I would imagine a big problem is the concatenation of str += scanner.nextLine(); The new line is going to be appended straight onto the end of the previous lines number
Have a look at this
Scanner sc = new Scanner(System.in);
int bestScore = Integer.MIN_VALUE;
String team = "Nothing entered";
System.out.println("how many teams");
int count = sc.nextInt();
sc.nextLine();
while (count-- > 0) {
System.out.println("Entered team,score");
String line = sc.nextLine();
String arr [] = line.split(" ");
// check size - TBD
if (Integer.parseInt(arr[1]) > bestScore) {
bestScore = Integer.parseInt(arr[1]);
team = arr[0];
}
}
System.out.println("nest team is " + team + " with a score of " + bestScore);
If I have to do something like that I will do it like this:
import java.util.*;
public class winner {
public static void main (String args []) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String winnerTeam = "";
String Team="";
int winnerScore = 0, score = 0;
for (int i = 0; i < cases; i++) {
Team = scanner.next();
score = scanner.nextInt();
if(score > winnerScore){
winnerTeam = Team;
winnerScore = score;
}
}
System.out.println("Winner team" + winnerTeam + "Score:" + winnerScore);
}
}

I need this program to find the longest word in a String in Java

import java.util.*;
class Exam3
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String word1 = "", word2 = "";
int l1 = 0, l2 = 0;
while(sc.hasNext())
{ word1 = sc.next();
l1 = word1.length();
if(l1 > l2)
{
l2 = l1;
word2 = word1;
}
}
System.out.println("Longest Word: " + word2);
System.out.println("Length of Word: " + l2);
}
}
The code isn't working. Prompting the user is successful, but nothing else happens. If you input a String and press Enter, it goes to the next line, where you can input again, etc. etc.
There should be a exit condition in the loop. Please use the following code.
import java.util.Scanner;
public class LongestString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String word1 = "", word2 = "";
int l1 = 0, l2 = 0;
while (sc.hasNext()) {
word1 = sc.next();
// type exit finish the loop
if (word1.equals("exit"))
break;
l1 = word1.length();
if (l1 > l2) {
l2 = l1;
word2 = word1;
}
}
sc.close();
System.out.println("Longest Word: " + word2);
System.out.println("Length of Word: " + l2);
}
}
This approach worked for me
public class actual {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String: ");
int largestLength = 0;
String largestWord = "";
String a = sc.nextLine();
for(String b:a.split(" ")){
if (largestWord.length() == 0) {
largestLength = b.length();
largestWord = b;
} else if (b.length() >= largestLength) {
largestLength = b.length();
largestWord = b;
}
}
sc.close();
System.out.println("Longest Word: " + largestWord);
System.out.println("Length of Word: " + largestLength);
}
}

how to find common suffix in java by using method

How to find common suffix in java by using method
public static String commonSuffix (String s1, String s2)
I can't return the result in method. Please help me
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
//HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1="";
String reverse2="";
System.out.println("Please enter the first string: ");
String s1=input.nextLine();
System.out.println("Please enter the second string: ");
String s2=input.nextLine();
int l1=reverse1.length();
int l2=reverse2.length();
for ( int i = s1.length() - 1 ; i >= 0 ; i-- )
{
reverse1 = reverse1 + s1.charAt(i);
}
for ( int i = s2.length() - 1 ; i >= 0 ; i-- )
{
reverse2 = reverse2 + s2.charAt(i);
}
if(l1<l2){
int l3=l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
else {
int l3=l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
}
public static String commonSuffix (String reverse1, String reverse2,int l3){
String suffixies="";
for(int k=0; k<=l3 ; k++){
if(reverse1.charAt(k)!=reverse2.charAt(k)){
}
else{
suffixies+=reverse1.charAt(k);
}
}
return suffixies;
}
}
Can someone help me fix this code??
Your issue is that you return inside of the for loop. You should return after the for loop terminates.
Please see the following code (I have tested it):
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
// HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1 = "";
String reverse2 = "";
System.out.println("Please enter the first string: ");
String s1 = input.nextLine();
System.out.println("Please enter the second string: ");
String s2 = input.nextLine();
for (int i = s1.length() - 1; i >= 0; i--) {
reverse1 = reverse1 + s1.charAt(i);
}
for (int i = s2.length() - 1; i >= 0; i--) {
reverse2 = reverse2 + s2.charAt(i);
}
int l1 = reverse1.length();
int l2 = reverse2.length();
if (l1 < l2) {
int l3 = l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
} else {
int l3 = l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
}
}
public static String commonSuffix(String reverse1, String reverse2, int l3) {
String suffixies = "";
for (int k = 0; k < l3; k++) {
if (reverse1.charAt(k) != reverse2.charAt(k)) {
break;
} else {
suffixies += reverse1.charAt(k);
}
}
// Reverse again
String reverse = "";
for (int i = suffixies.length() - 1; i >= 0; i--) {
reverse = reverse + suffixies.charAt(i);
}
return reverse;
}
}
Output:
Please enter the first string:
caption
Please enter the second string:
action
noitpac noitca
tion
This could be the best
**
package com.tm;
import java.util.Scanner;
public class CommSuffix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str[] = scan.nextLine().split(",");
String commSufffix=null;
if(str[0].trim().length() > str[1].trim().length()) {
String temp = str[0].trim();
str[0] = str[1].trim();
str[1] = temp;
}
for(int i=0;i<str[0].length();i++) {
String subStr = str[0].substring(i,str[0].length());
if(str[1].endsWith(subStr)) {
commSufffix = subStr;
break;
}
}
System.out.println(commSufffix);
}
} **

Categories