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;
Related
I am trying to compare two different strings, one character at a time. I need to return the correct number of digits until they do not equal each other anymore. However, I can't include the character of '.' in the return statement. How would I go about doing this?
import java.util.Scanner;
import java.math.BigDecimal;
public class PiEstimate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a;
String b;
char y;
char c;
char d;
String userInput;
do {
System.out.print("Enter a number of randomly generated points:");
userInput = in.nextLine();
if (!isValid(userInput)) {
System.out.print("\n" + "You entered an invalid integer. Please enter a valid integer greater than 0: ");
userInput = in.nextLine();
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
} else {
BigDecimal estimate = new BigDecimal((Math.PI / 4) * 4);
estimate.toString();
System.out.println("\n" + "Your estimate is: " + calculation(userInput));
System.out.println("\n" + "Accuracy of digits is :" + comparison(estimate.toString(),userInput));
}
System.out.println("\n" + "Would you like to play again? Enter 'Y' for yes or 'N' for no: ");
String optionToPlay = in.nextLine();
c = optionToPlay.charAt(0);
d = Character.toUpperCase(c);
if (d == 'n' || d == 'N') {
BigDecimal estimate2= new BigDecimal( (Math.PI / 4) * 4);
System.out.println("\n" + "The best estimate is: " + estimate2);
}
} while (d == 'Y');
} // end psvm
public static boolean isValid(String a) {
boolean isFlag = true;
char holder;
for (int i = 0; i < a.length(); i++) {
holder = a.charAt(i);
if (!Character.isDigit(a.charAt(i))) {
return false;
} if (i == 0 && holder == '-') {
return false;
}
} // end for
return isFlag;
} // end isValid
public static double calculation(String a) { // String a means 'looking for a string
double calc = Double.parseDouble(a);
int i;
double x;
double y;
double c = 0;
double runningCounter = 0;
double totalCounter;
for (i = 0; i < calc; i++) {
x = Math.random();
y = Math.random();
c = Math.sqrt((x * x) + (y * y));
if (c <= 1) {
runningCounter++;
}
} // end for
totalCounter = ((runningCounter / calc) * 4);
calc = totalCounter;
return calc;
}
public static int comparison (String bear, String userInput) {
int i = 0;
String s = calculation(userInput) + "";
int b;
int counter2 = 0;
for (i=0; i < s.length(); i++) {
if (s.charAt(i) != bear.charAt(i)) {
return i;
}
}
return i;
} // end comparison
} // end class
Code from IDE
I'm a first year in Computer Science Engineering, and I'm currently taking a Java programming course. It's the first programming language I've ever tried learning and I'm completely stuck. I had to design a program for class that takes a credit card number input from the user and determines whether or not it is valid. I've somehow messed up my loops, and now the whole thing keeps repeating at least 5 times more than I need it to. How could I fix this? It's due by 3:00 and I'm freaking out. Here is my code:
package osu.cse1223;
import java.util.Scanner;
public class Project07 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Enter a credit card number (enter a blank line to quit):");
String cardNumber = in.nextLine();
int length = cardNumber.length();
if (length != 16 && length > 0) {
System.out.print("ERROR! Number MUST have exactly 16 digits");
}
else if (length <= 0) {
System.out.println("Goodbye!");
}
else {
char checkDigitChar = cardNumber.charAt(15);
int checkDigit = Character.getNumericValue(checkDigitChar);
int pos = 0;
while (pos < 16) {
char digit = cardNumber.charAt(pos);
int number = Character.getNumericValue(digit);
int doubled = number * 2;
pos = pos + 2;
int sum = 0;
if (doubled > 9) {
String sub = Integer.toString(doubled);
char one = sub.charAt(0);
char two = sub.charAt(1);
int numOne = Character.getNumericValue(one);
int numTwo = Character.getNumericValue(two);
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
int newPos = 1;
int newSum = 0;
while (newPos < 16) {
char digitForSum = cardNumber.charAt(newPos);
int individualNum = Character.getNumericValue(digitForSum);
newPos = newPos + 2;
newSum = individualNum + newSum;
}
int total = sum + newSum;
String subTwo = Integer.toString(total);
char onesPlace = subTwo.charAt(1);
int ones = Character.getNumericValue(onesPlace);
int realCheckDigit = 10 - ones;
System.out.println("Check digit should be: " + realCheckDigit);
System.out.println("Check digit is: " + checkDigit);
if (checkDigit == realCheckDigit) {
System.out.println("Number is valid");
}
else {
System.out.println("Number is not valid");
}
}
}
}
}
You are not ending your first loop in the right place.
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
}// ADD THIS TO END THE FIRST WHILE LOOP
And remove a } from the bottom of the code.
This loop repeats 8 times, but in fact it should be stoped after the first cycle. There are two ways to do this. First, you can add "break;" in the end of the last cycle. Second, you can not use "while (pos < 16) {}" loop at all. Both variants will give you the same result.
Here is the variant:
public class Various {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter a credit card number (enter a blank line to quit):");
String cardNumber = in.nextLine();
int length = cardNumber.length();
if (length != 16 && length > 0) {
System.out.print("ERROR! Number MUST have exactly 16 digits");
}
else if (length <= 0) {
System.out.println("Goodbye!");
}
else {
char checkDigitChar = cardNumber.charAt(15);
int checkDigit = Character.getNumericValue(checkDigitChar);
int pos = 0;
// while (pos < 16) {
char digit = cardNumber.charAt(pos);
int number = Character.getNumericValue(digit);
int doubled = number * 2;
// pos = pos + 2;
if (doubled > 9) {
String sub = Integer.toString(doubled);
char one = sub.charAt(0);
char two = sub.charAt(1);
int numOne = Character.getNumericValue(one);
int numTwo = Character.getNumericValue(two);
int doubleAdjusted = numOne + numTwo;
sum = sum + doubleAdjusted;
}
else {
}
int newPos = 1;
int newSum = 0;
while (newPos < 16) {
char digitForSum = cardNumber.charAt(newPos);
int individualNum = Character.getNumericValue(digitForSum);
newPos = newPos + 2;
newSum = individualNum + newSum;
}
int total = sum + newSum;
String subTwo = Integer.toString(total);
char onesPlace = subTwo.charAt(1);
int ones = Character.getNumericValue(onesPlace);
int realCheckDigit = 10 - ones;
System.out.println("Check digit should be: " + realCheckDigit);
System.out.println("Check digit is: " + checkDigit);
if (checkDigit == realCheckDigit) {
System.out.println("Number is valid");
}
else {
System.out.println("Number is not valid");
}
// break;
// }
}
}
}
I keep getting the error
"cannot find symbol
symbol : variable input
location: class CountNumbers" in my program and I have put it all throughout the program.
import java.util.Scanner;
public class CountNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char[] chars = createArray();
System.out.println("The numbers are:");
displayArray(chars);
int [] counts = countNumbers(chars);
System.out.println();
System.out.println("The occurences of each number are:");
displayCounts(counts);
}
public static char[] createArray() {
char[] chars = new char[100];
for (int i = 0; i < chars.length; i++)
chars[i] = input.nextInt();
return chars;
}
public static void displayArray (char[] chars) {
for (int i = 0; i < chars.length; i++) {
if ((i + 1) % 20 == 0)
System.out.println(chars[i]);
else
System.out.print(chars[i] + " ");
}
}
public static int[] countNumbers(char[] chars) {
int[] counts = new int[100];
for (int i = 0; i < chars.length; i++)
counts[chars[i] - 'a']++;
return counts;
}
public static void displayCounts(int[] counts) {
for (int i = 0; i < counts.length; i++) {
if ((i + 1) % 10 == 0)
System.out.println(counts[i] + " " + (char)(i + 'a'));
else
System.out.print(counts[i] + " " + (char)(i + 'a') + " ");
}
}
}
Thanks for the help.
input is a local variable to the main method which you then try to use in the createArray method. If you want input to be accessible in other methods, it needs to be a member or static variable.
Or in your case, since you only use input in createArray, you can move the creation of input to the createArray method.
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.
I did everything as far as concepts. I made my class, and my client class. The assignment is to make a program that allows the user to input 10 grades into a gradebook, and get the max, min, and average grade of class.
My only problem is I want to make sure the user cannot put anything in the program that is not an integer; do I put instructions like that in my class or client java doc?
This is my class:
import java.util.Arrays;
public class ExamBook{
int grades[];
int classSize;
int MIN = 0;
int MAX = 100;
public ExamBook(int[] gradeBook)
{
classSize = 10;
//instantiate array with same length as parameter
grades = new int[gradeBook.length];
for ( int i = 0; i <= gradeBook.length-1; i++ )
{
grades[i] = gradeBook[i];
}
Arrays.sort(grades);
}
//setter, or mutator
public void setClassSize( int newClass )
{
classSize = newClass;
}
//get return method
public int getClassSize()
{
return classSize;
}
//calculate highest grade
public int calculateMaxGrade()
{
int max = grades[0]; //assuming that the first index is the highest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] > max )
max = grades[i]; //save the new maximum
}
return max;
}
//calculate lowest grade
public int calculateMinGrade()
{
int min = grades[0]; //assuming that the first element is the lowest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] < min)
min = grades[i]; //save the new minimum
}
return min;
}
//calculate average
public double calculateAverageGrades()
{
double total = 0;
double average = 0;
for ( int i = 0; i < grades.length; i++ )
{
total += grades[i];
}
average = total/grades.length;
return average;
}
//return an assorted array
public int[] assortedGrades()
{
Arrays.sort(grades);
return grades;
}
//return printable version of grades
#Override
public String toString()
{
String returnString = "The assorted grades of the class in ascending order is this: " + "\t";
for ( int i = 0; i <= grades.length - 1; i++ )
{
returnString += grades[i] + "\t";
}
returnString += " \nThe class average is a/an " + calculateAverageGrades() + "." + "\nThe highest grade in the class is " + calculateMaxGrade() + "." + "\nThe lowest grade in the class is " + calculateMinGrade() + ".";
returnString += "\n";
return returnString;
}
}
**This is my client:**
import java.util.Scanner;
import java.util.Arrays;
public class ExamBookClient
{
public static ExamBook classRoom1;
public static void main( String[] args)
{
int MAX = 100;
int MIN = 0;
Scanner scan = new Scanner(System.in);
//create array for testing class
int[] grading = new int [10];
System.out.println("Please enter 10 grades to go into the exam book.");
if(scan.hasNextInt())
{
for (int i = 0; i < grading.length; i++)
{
int x = scan.nextInt();
if( x>MIN && x<MAX)
{
grading[i] = x;
}
}
}
classRoom1 = new ExamBook (grading);
System.out.println("The classroom size is " + classRoom1.getClassSize() + "."
+ "\n" + classRoom1.toString() + ".");
}
}
Prompt for scan.hasNextInt() in your for loop of your client instead of outside the for loop. Like this:
boolean failed = false;
for (int i = 0; i < grading.length; i++)
{
if (failed)
scan.nextLine();
failed = false;
if (scan.hasNextInt()) {
int x = scan.nextInt();
if(x >= MIN && x <= MAX)
{
grading[i] = x;
} else {
System.out.println("Grade must be from 0-100!");
i--;
continue;
}
} else {
// jump back to the start of this iteration of the loop and re-prompt
i--;
System.out.println("Number must be an int!");
failed = true;
continue;
}
}
You might want to do this in two parts - your API should specify that it works with only integers - perhaps the method which processes the grades will accept Integer arguments only. The parser of the String can specify in its Javadocs what it does when the argument passed to it is not an integer. You client should also validate that the input is an integer (maybe within the valid range). If the user input is incorrect, then maybe it can display a usage manual.
You can check using the below code. If you pass other than number it would throw NumberFormatException
public static boolean checkIfNumber(String input) {
try {
Integer in = new Integer(input);
} catch (NumberFormatException e) {
return false;
}
return true;
}
You can change this part as follows. This way the user can enter non-integers but in those cases you will print out warnings and you will ignore them.
System.out.println("Please enter 10 grades to go into the exam book.");
int i = 0;
int x = -1;
while (scan.hasNext() && i < 9) {
String sx = scan.next();
try {
x = Integer.parseInt(sx);
i++;
if (x > MIN && x < MAX) {
grading[i] = x;
}
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
classRoom1 = new ExamBook(grading);
Chech this link, it has the solution.
You must use the method hasNextInt() of Scanner.
If you do not want to use exceptions you can always use a Regex match to check that what you have in the string is a number valid for you.
Bearing in mind that your valid numbers are between 0 and 100, and 0 and 100 are not included seeing you code, the reg ex will be:
s.matches("[1-9][0-9]{0,1}")
Basically what this means is that you are going to have a character that is a number between 1 and 9 as first char, and then you could have one between 0 and 9, this way you do not allow 0 at the beginning (01 is not valid) and 0 by it self is also not valid. 100 has 3 chars so is not valid neither.