I am stuck. I have my array with data the user inputs. After their information is entered the program asks if they want to see items with characters above 10 or below. I can't seem to figure out this section. Below is where I am currently with the code.
import java.util.*;
import java.util.Scanner;
public class CategorizeStrings {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or press QUIT to quit.");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
boolean result = Arrays.stream(array).anyMatch("QUIT"::equals);
if(result)
{
break;
}
}
String str = null;
int len = -1;
System.out.println("Would you like to display strings with above 10 charaters (Above) or below 10 characters (Below)? Type Above or Below:");
String answer = s.nextLine();
if(answer == "Above"){
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
len ++;
if(array[i].charAt(i)>10)
for (int x = 0; x < len; x++) {
if(array[x] == str )
System.out.print(len);
System.out.print(array[x] + " ");
}
}
}
else
{
}
System.out.println();
}
}
The block of code I'm struggling with is:
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
len ++;
if(array[i].charAt(i)>10)
for (int x = 0; x < len; x++) {
if(array[x] == str )
System.out.print(len);
System.out.print(array[x] + " ");
}
Any help is appreciated.
If you just want to print the words that have above 10 characters
for (String value : array) {
if (value != null) {
if (value.length() > 10) {
System.out.print(value + " ");
}
}
}
This is how I would do it
Also note that Strings can't be compared using '=='
You should use equal or contentEquals
For example:
if (string1.equals(string2)) {
// Insert code here
}
or
if (string1.contentEquals(string2)) {
// Insert code here
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 10 months ago.
I was solving this question(the title) and I cant find the mistakes present so please help
Input : The buffalo is stuck in a soggy field and roads are flooded
everywhere.
Output : buffalo, soggy, flooded
There are 3 words that have consecutive letters.
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String str = sc.nextLine();
str = str.toUpperCase();
String s = " ";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ')
s = s + ch;
else {
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == s.charAt(j + 1)) {
System.out.println(s);
count++;
s = " ";
}
}
}
}
System.out.println("There are " + count + " consecutive words");
}
}
Output
Enter the sentence
I love apples
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:1512)
at com.company.Main.main(Main.java:18)
Process finished with exit code 1
I tried solving it but it gets complicated as such
Here:
for (int j = 0; j < s.length(); j++){
if (s.charAt(j) == s.charAt(j + 1)){
System.out.println(s);
count++;
s = " ";
}
}
You are looping through a string comparing the j index character with the j+1 index character. When j is the index of the last character j+1 will be out of range. If you want to do the comparation this way, you just have to go to the penultimate index (where you will compare the penultimate with the last).
This way the code should work:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
String str = sc.nextLine();
str = str.toUpperCase();
String s = " ";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ')
s = s + ch;
else {
for (int j = 0; j < s.length()-1; j++) {
if (s.charAt(j) == s.charAt(j + 1)) {
System.out.println(s);
count++;
}
}
s = " ";
}
}
System.out.println("There are " + count + " consecutive words");
}
And as you can see I have moved the s = " "; piece of code outside of the for and if block, leaving it just inside the else block. If you don't do that the string variable s will not be cleaned after each word.
Write a program that will read a line of text String and display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text.
For this purpose, you must use an array of type int of length 26, so that the element at index 0 contains the number of a’s, the element at index 1 contains the number of b’s, and so forth.
Allow both uppercase and lowercase letters as input, but treat uppercase and lowercase versions of the same letter as being equal.
Hint: Use the method chatAt(int index) in the String class to get the individual character in a string at the specified index.
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] letters = new int[26];
char choice;
while (true) {
// taking user input
System.out.println("Please enter text ending with period:");
String text = sc.nextLine();
// converting it lowercase
text = getActualText(text).toLowerCase();
char c = 'a';
for (int i = 0; i < letters.length; i++)
// increasing character by 1
letters[i] = countLetters(text, c++);
System.out.println("\nThe frequency of the letters");
c = 'a';
for (int i = 0; i < letters.length; i++) {
// showing only those letters whose frequnecy is greater than 0
if (letters[i] != 0)
System.out.println(c + ": " + letters[i]);
c++;
}
System.out.print("Would you like to try another text?(Y/N) ");
choice = sc.nextLine().charAt(0);
if (choice == 'n' || choice == 'N')
break;
}
}
private static int countLetters(String text, char c) {
int count = 0;
for (int i = 0; i < text.length(); i++)
// counting the frequency
if (text.charAt(i) == c)
count++;
return count;
}
/**
* This method will extract the first sentence from a text ending with full stop(.)
*/
private static String getActualText(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '.')
// breaking out of the loop if the full stop is found
break;
// adding it to the text
newText += text.charAt(i) + "";
}
return newText;
}
}
Try to change existing condition to below new condition:
Existing Condition: (Allowing frequencies which are not equal to 0):
if(letters[i] != 0) {//showing only those letters whose frequency is greater than 0
New Condition: (Allowing frequencies which are greater than or equal to 0):
if(letters[i] >= 0) {
It's enough to go through the text one time and count the occurrence of each letter. And then just show only letters with count >0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.print("\nEnter the text: ");
String str = scan.nextLine();
print(histogram(str));
} while (shouldContinue(scan));
}
private static int[] histogram(String str) {
int[] letters = new int[26];
for (int i = 0; i < str.length(); i++)
if (Character.isLetter(str.charAt(i)))
letters[Character.toLowerCase(str.charAt(i)) - 'a']++;
return letters;
}
private static void print(int[] letters) {
System.out.println("The frequency of the letters:");
for (int i = 0; i < letters.length; i++)
if (letters[i] > 0)
System.out.println((char)('a' + i) + ": " + letters[i]);
}
private static boolean shouldContinue(Scanner scan) {
while (true) {
System.out.print("Would you like to try another text (Y/N)? ");
String str = scan.nextLine();
if (str.length() != 1)
continue;
if ("Y".equalsIgnoreCase(str))
return true;
if ("N".equalsIgnoreCase(str))
return false;
}
}
I want to replace from String and print how many times it replaced.
for examples)
Input : aabba
from : aa
to : bb
ddbba
replaced : 1
Input : AAccaabbaaaaatt
from : aa
to : bb
ddccddbbddddatt
replaced : 4
I have a problem here:
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i))+1; // this part!
} else
continue;
} // for
My teacher said just use .indexOf and .replace, and .toLowerCase.
She gave some examples and they always replace two letters to two letters.
That's the reason why I put '+1' to find another letter.
If I remove that '+1', it counts 'aaa' twice.(aa a and a aa. And it replaced to 'dda', so it's wrong.)
But this time when I replace only one letter(ex.a), it counts less numbers than actually it has to be.(ex.'aaa' counts just two times.)
With the examples from teacher, it works well cuz all of them replace two letters.
But I want to improve this.
Here is all of my code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Input : ");
String input = scan.next();
System.out.print("from : ");
String curStr = scan.next();
System.out.print("to : ");
String chStr = scan.next();
String inputL = input.toLowerCase();
String curStrL = curStr.toLowerCase();
String chStrL = chStr.toLowerCase();
String output = inputL.replace(curStrL, chStrL);
int cnt = 0;
if (inputL.indexOf(curStrL) == -1) {
System.out.println("Do it again");
} else
System.out.println(output);
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i))+1;
// *** to make the code find from the next letter! ***
} else
continue;
} // for
if (cnt > 0)
System.out.println("replaced : " + cnt);
else
{System.out.println("can't replace. Do it again");
break;}
System.out.println("----------------");
} // while
} // main
Just increase the counter variable of your loop with the lenght of the string to be replaced.
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i)); // EDIT by Shraft
i = i + curStr.length() - 1; // EDIT
// *** to make the code find from the next letter! ***
} else
continue;
} // for
When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.
I want make like this:
input number[0][0]=201
input number[0][1]=202
input number[1][0]=203
input number[1][1]=204
input last = 203
then find if last input same with above, if true, s.o.p find, else not found
my code:
import java.util.Scanner;
public class array_input {
public static void main(String[] args) {
int a[][];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print("input number[" + i + "][" + j + "]");
int b = scan.nextInt();
a[i][j] = b;
}
}
System.out.print("input what u want");
if (a[i][j] == b) {
System.out.print("found");
} else {
System.out.print("not found");
}
}
}
Maybe you mean something like this ?
import java.util.Scanner;
public class array_input
{
public static void main(String [] args){
int a [][] = new int[2][2];
Scanner scan = new Scanner(System.in);
for(int i = 0;i < 2; i++){
for(int j = 0; j < 2; j++){
System.out.printf("input number[%d][%d]=", i, j);
int b = scan.nextInt();
a[i][j]=b;
}
}
System.out.print("input last = ");
int needle = scan.nextInt();
for (int[] row : a){
for (int col : row){
if(col == needle){
System.out.println("found");
return;
}
}
}
System.out.print("not found");
}
}
Ok, I guess that this is what you want. This checks if the last input of the array is in the array (excluding the last input).
boolean valueInArray = false;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
if(a[i][j]==b && (i != 2 || j != 2)){
valueInArray = true;
}
}
}
if(valueInArray){
System.out.print("found");
} else {
System.out.print("not found");
}