public static void main (String args[])
{
String c = "Message";
int width;
int height;
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println("Enter your width: ");
width=sc.nextInt();
System.out.println("Enter your height: ");
height=sc.nextInt();
System.out.println();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (i == 0 || i == height-1) {
System.out.print(character);
} else if (j ==width-1) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
}
I am trying to make the MESSAGE display in the rectangle. Also, is there a way i can move my rectangle in the center of the screen too?
That code will do your trick but please notice that this is ugly.
First you are taking the whole user input line instead of the first character.
public static void main(String args[]) {
String c = "Message";
char character;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the character : ");
character = sc.next().charAt(0);
System.out.println();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 13; j++) {
if (i == 0 || i == 2) {
System.out.print(character);
} else if (j == 0) {
String middle = character + " " + c + " " + character;
System.out.print(middle);
}
}
System.out.println();
}
}
output :
aaaaaaaaaaaaa
a Message a
aaaaaaaaaaaaa
Don't use the [for loop], the StringUtils class in Apache Commons Lang3 can help you make repeating String.
See:
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html
there are 3 methods:
(1)static String repeat(char ch, int repeat)
Returns padding using the specified delimiter repeated to a given length.
(2)static String repeat(String str, int repeat)
Repeat a String repeat times to form a new String.
(3)static String repeat(String str, String separator, int repeat)
Repeat a String repeat times to form a new String, with a String separator injected each time.
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 am very new to java and I was wondering if you could help me out. Here is my code:
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
for (int i = 0; i <= length; i++) {
String letter = string.substring(i, ++i);
if (letter.equalsIgnoreCase("a")){vowels++;}
if (letter.equalsIgnoreCase("e")){vowels++;}
if (letter.equalsIgnoreCase("i")){vowels++;}
if (letter.equalsIgnoreCase("o")){vowels++;}
if (letter.equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
The number is off but I can't figure out why.
This here is wrong
string.substring(i, ++i)
because the variable i is already incremented in the for-loop
so you are basically skipping chars in the string
implement the right logic, use the right data type
int length = string.length();
for (int i = 0; i < length; i++) {
char letter = string.charAt(i);
System.out.println(letter);
if (letter == 'a') {
vowels++;
} else if (letter == 'e') {
vowels++;
} else if (letter == 'i') {
vowels++;
} else if (letter == 'o') {
vowels++;
} else if (letter == 'u') {
vowels++;
}
}
Here is another solution you could try:
The split method will split the string into a String array. Then in your for loop it will check every item in your array.
public static void main(String[] args) {
int vowels = 0;
Scanner input = new Scanner(System.in);
System.out.println ("Enter a string: ");
String string = input.nextLine();
int length = string.length();
String[] stringArray = string.split("");
for (int i = 0; i < length; i++) { //I took out the = sign in your for loop arguments.
if (stringArray[i].equalsIgnoreCase("a")){vowels++;}
if (stringArray[i].equalsIgnoreCase("e")){vowels++;}
if (stringArray[i].equalsIgnoreCase("i")){vowels++;}
if (stringArray[i].equalsIgnoreCase("o")){vowels++;}
if (stringArray[i].equalsIgnoreCase("u")){vowels++;}
}
System.out.println ("The number of vowels in " + string + " is: " + vowels);
}
I'm making a program that counts the frequency of letters from a user-entered string, and have recently encountered the 'Arithmetic Exception' error.
I cannot for the life of me figure out what's causing it, even though I know it's because something is being divided by 0.
Here's my code:
package day1.examples;
import java.util.Scanner;
public class rl_frequency_count {
public static int input;
public static void main(String[] args) {
System.out
.println("Please enter some text that you would like to work out the occurence for.");
System.out
.println("However, do remember that any other characters outside of the alphabet will NOT be counted.");
Scanner stringUser = new Scanner(System.in);
String input = stringUser.nextLine();
input = input.replaceAll("\\s+", "");
input = input.toLowerCase();
// counting occurrence of character with loop
int i;
int charCountA = 0;
int charCountB = 0;
int charCountC = 0;
int charCountD = 0;
int charCountE = 0;
int charCountF = 0;
int charCountG = 0;
int charCountH = 0;
int charCountI = 0;
int charCountJ = 0;
int charCountK = 0;
int charCountL = 0;
int charCountM = 0;
int charCountN = 0;
int charCountO = 0;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
charCountA++;
getOccurence(charCountA, "A");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'b') {
charCountB++;
getOccurence(charCountB, "B");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'c') {
charCountC++;
getOccurence(charCountC, "C");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'm') {
charCountM++;
getOccurence(charCountM, "M");
}
}
}
// method for the occurrence
public static void getOccurence(int number, String letter) {
double occ = number / input * 10; //
System.out.println();
System.out.println("Number of " + letter + "'s - " + number);
System.out.println("Occurence of " + letter + " - " + occ + "%");
}
}
I know that I only have ABC and M in at the moment but was gonna work those in later.
This is the first time i've posted on here and i'm still newish to Java so any help whatsoever is greatly appreciated!
I ran it and it says line 67. here is the total:
public static void getOccurence(int number,String letter){
double occ = number / input *10; //
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
To fix:
double occ = (number > 0) ? number/input * 10 : 0;
This sets occ to 0 in case of number being set to 0. Good luck.
Hope this helps.
The line of code causing the error is in your method:
public static void getOccurence(int number,String letter){
double occ = number / input *10; // <------ERROR FROM HERE (input is always 0)
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
The input variable is declared in your class here:
Line 6: public static int input;
Since you didn't initialize it nor does the value is being changed in your codes, the value of input remains as 0 through out the entire program. (Default value for an uninitialized int variable is 0)
Since it is always 0, you are always dividing a number with 0.
double occ = number / 0*10;
I am creating a program which acts as a translator for given words. I have created a text file with the data I am using, reading that into a 2D array (English in column 0, translation in column 1, 16 rows in total). I prompt the user to enter a string and pass that string, the 2D, and a blank String to hold the translation to my translation method (named: turnKlingon). I am using the String tokenizer to pick out specific words. My problem is that I cannot figure out how to search my 2D array in column 0 for the English and only print the column 1 translated word.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
System.out.println("Klingon Translator");
System.out.println();
System.out.println();
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
String Klingon = " ";
turnKlingon(Klingon, userString, translate);
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated to Klingon: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String Klingon, String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println("Number of Tokens: "+ numberOfWords);
int counter = 1;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
System.out.print(s2 + "_"); //string tokenizer
for(int r = 0; r < translate.length; r++)
{
for(int c = 0; c < translate[r].length; c++)
{
if (translate[r][c].compareTo(s2) == 0)
{
translate[0] = translate[1];
}
}
System.out.println(translate[0] + "," + translate[1]);
counter++; //string tokenizer
}//end while
}
}
}
After messing around with this code for a few hours I finally managed to solve my own problem. I also added a while true loop in the main method to allow the user to translating multiple times as well as an option to translate to another language (German) though I have omitted that method from this reply.
import java.util.*;
import java.io.*;
public class project9
{
public static void main(String[] args)
throws java.io.IOException
{
Scanner input = new Scanner(System.in);
System.out.println("English to Klingon/German Translator");
System.out.println();
System.out.println();
while (true)
{
int again = 999;
int language = 999;
String userString = " ";
userString = loadUserString();
String[][] translate = new String[16][2];
loadTranslateString(translate);
System.out.println("Would you like to translate to Klingon or German? \n Press 1 for Klingon: \n Press 2 for German: ");
language = input.nextInt();
if (language == 1)
{
turnKlingon(userString, translate);
}
else if (language == 2)
{
turnGerman(userString, translate);
}
else
{
System.out.println("Invalid input");
}
System.out.println();
System.out.println();
System.out.println("Would you like to translate another sentence? \n Press 1 for yes or 0 for no: ");
again = input.nextInt();
if (again == 0)
{
System.out.println("Goodbye!");
break;
}
else if (again == 1)
{
continue;
}
}
}
public static String loadUserString()
{
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a sentence that you would like translated: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadTranslateString(String[][] translate)
throws java.io.IOException
{
String filName = " ";
filName = "C:\\tmp\\transKling.txt";
Scanner input = new Scanner(new File(filName));
for (int row = 0; row < translate.length; row++)
{
for (int col = 0; col < translate[row].length; col++)
translate[row][col] = input.nextLine();
}
input.close();
}
public static void turnKlingon(String userString, String[][] translate)
{
String userStringPassed = userString;
String[][] translatePassed = translate;
String s2 = " ";
StringTokenizer st = new StringTokenizer(userStringPassed);
int numberOfWords = st.countTokens();
System.out.println();
System.out.println("Any words that cannot be directly \n translated will remain in English");
System.out.println("____________________________________");
System.out.println();
System.out.print("Translation: ");
int counter = 1;
boolean found = false;
int translateCounter = 0;
while (counter <= numberOfWords)
{
s2 = st.nextToken(); //string tokenizer
//string tokenizer
for(int r = 0; r < 16; r++)
{
for(int c = 0; c < 18; c++)
{
found = false;
if (translateCounter == 16)
{
System.out.print(s2+ " ");
translateCounter = 0;
break;
}
else if (translate[r][0].compareTo(s2) == 0)
{
found = true;
}
else if (translate[r][0].compareTo(s2) != 0)
{
found = false;
r++;
c = -1;;
translateCounter++;
continue;
}
if (found == true)
{
System.out.print(translate[r][1]+ " ");
translateCounter = 0;
c = -1;
r = -1;
break;
}
}
counter++;//string tokenizer
break;
}//end while
}
}