Error message saying that the array has been exceeded - java

I was wondering if you guys can give me pointers on how to fix my code. I am trying to put an out an error message that the size of the array has been exceeded when you entered too many numbers. I know I wrote two posts about this, and many people told me to be specific and do it by myself and I decided to do this program by myself instead of asking for help. So I wrote the code, and it came out nice, but how would I do it when it says, "Enter the number 11:" then I enter a number, and it says it has been exceeded and prints out the 10 arrays on the next line.
Input:
import java.util.Scanner;
public class FunWithArrays
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 11; // Size of the array
// Create an array.
int[] numbers = new int[ARRAY_SIZE];
// Pass the array to the getValues method.
getValues(numbers);
System.out.println("Here are the " + "numbers that you entered:");
// Pass the array to the showArray method.
showArray(numbers);
}
public static void getValues(int[] array)
{
// Create a Scanner objects for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " + array.length + " numbers.");
// Read the values into the array
for (int index = 0; index < array.length; index++)
{
// To tell users if they exceeded over the amount
if (index > 9)
{
System.out.print("You exceeded the amount " + " ");
}
else
{
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
}
public static void showArray(int[] array)
{
// Display the array elements.
for (int index = 0; index < array.length; index++)
System.out.print(array[index] + " ");
}
}
output:
Enter a series of 11 numbers.
Enter the number 1: 3321
Enter the number 2: 3214
Enter the number 3: 213
Enter the number 4: 21
Enter the number 5: 321
Enter the number 6: 321
Enter the number 7: 3
Enter the number 8: 213
Enter the number 9: 232
Enter the number 10: 321
You exceeded the amount Here are the numbers that you entered:
3321 3214 213 21 321 321 3 213 232 321 0

OK, here is the code to your need, bare in mind that 11th element is not put into an array at all.
public static void main(String[] args) {
final int ARRAY_SIZE = 11; // Size of the array
// Create an array.
int[] numbers = new int[ARRAY_SIZE];
// Pass the array to the getValues method.
getValues(numbers);
System.out.println("Here are the " + "numbers that you entered:");
// Pass the array to the showArray method.
showArray(numbers);
}
public static void getValues(int[] array) {
// Create a Scanner objects for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " + array.length + " numbers.");
// Read the values into the array
for (int index = 0; index < array.length; index++) {
// To tell users if they exceeded over the amount
if (index >= 10) {
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
System.out.println("\nYou exceeded the amount " + " ");
} else {
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
}
public static void showArray(int[] array) {
// Display the array elements.
for (int index = 0; index < array.length-1; index++) {
System.out.print(array[index] + " ");
}
}
}
And I have no idea, why do you want it like this.

Related

How to solve Cannot invoke "String.compareTo(String)" because "<parameter1>[<local3>]" is null?

import java.util.Scanner;
public class Search {
static Scanner scanner = new Scanner(System.in);
static Scanner kb = new Scanner(System.in);
static Scanner kb2 = new Scanner(System.in);
public static void main (String[] args)
{
int choice;
System.out.print("Choose a number of students: ");
int n = scanner.nextInt();
String name[] = new String[n+1];
String course[] = new String[n+1];
int ID[] = new int[n+1];
for(int i=1;i <= n; i++)
{
System.out.print("Enter ID number " + i + ": ");
ID[i] = scanner.nextInt();
System.out.print("Enter Student name " + i + ": ");
name[i] = kb.nextLine();
System.out.print("Enter Student course " + i + ": ");
course[i] = kb2.nextLine();
System.out.println("----------------------------------------");
}
do
{
choice = menu();
if(choice == 1)
{
sortID(ID);
printValues(ID);
}else if(choice == 2)
{
nameSort(name,n);
printName(name,n);
}else if(choice == 3)
{
}
}while(choice !=0);
}
public static int menu()
{
System.out.print("\n1. Sort by ID\n2. Sort by Name\n3. Search by ID\n4. Search by Name\n5. Search by Course\n6. Display Records In table Form.\nYour Choice: ");
return scanner.nextInt();
}
public static void sortID(int []id)
{
int temp;
int index, counter;
for (counter=0; counter < id.length -1; counter++) {
for (index=0; index < id.length - 1 - counter; index++) {
if (id[index] > id[index+1]) {
temp = id[index];
id[index]=id[index+1];
id[index+1]=temp;
}
}
}
}
public static void printValues (int[]array) {
System.out.println ("\nSorted Id Number: ");
for(int i = 1; i < array.length; i++){
System.out.print ("\n" + array[i]);
}
}
public static void printName (String[]array,int a) {
for (int i = 0; i <= a - 1; i++)
{
System.out.print(array[i] + ", ");
}
}
public static void nameSort(String[] name,int a)
{
String temp;
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++) {
if (name[i].compareTo(name[j])>0)
{
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
}
}
The sorting works on the id but i have problems in my names it wont push through the bubble sort and say its null, im just starting learning this language and it would be a great help. Ive been working on this since last night and ive tried transffering it under the if else(choice == 2) still it says null.
Choose a number of students: 2
Enter ID number 1: 123
Enter Student name 1: Mark JAw
Enter Student course 1: JSJS
----------------------------------------
Enter ID number 2: 221
Enter Student name 2: Ak akw
Enter Student course 2: jdj
----------------------------------------
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 1
Sorted Id Number:
123
221
1. Sort by ID
2. Sort by Name
3. Search by ID
4. Search by Name
5. Search by Course
6. Display Records In table Form.
Your Choice: 2
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.compareTo(String)" because "name[i]" is null
at Search.nameSort(Search.java:95)
at Search.main(Search.java:41)
PS C:\Users\Bingus\Documents\Projects>
String name[] = new String[n+1];
Suppose for example that you read in a value of 3 for n. This code means that you will allocate 3+1 = 4 elements in name (and likewise in the other arrays). You do not want to allocate 4 elements. You will read 3 names, so you want to allocate 3 elements.
The valid indices for your array will be 0, 1, 2 and 3. You do not want 3 to be a valid index for your array. You want only 0, 1 and 2 to be valid indices, which if you count, you will notice makes 3 different indices.
for(int i=1;i <= n; i++)
In this loop, you will use values of 1, 2 and 3 for i, and thus assign to indices 1, 2 and 3 of name (as well as the other arrays). You do not want to do this. The result is that name[0] will remain null. You want to start the loop at 0 so that you use every element of the arrays. You want to use i < n as your loop condition, because once you correctly only have n elements in the array, n is no longer a valid index.
for (int i = 0; i < a; i++)
{
for (int j = i + 1; j < a; j++) {
if (name[i].compareTo(name[j])>0)
When the exception happens, it happens because you correctly start scanning the array from the beginning, but have incorrectly filled (and sized) the array. You pull a null value out of the array (that shouldn't be there) and try to .compareTo another value (which doesn't work, because you can't call a method on a null). A similar problem would occur (if you got that far) in your other sorting method.
(Unless it is for an assignment, you should not implement sorting yourself. You should use java.util.Arrays.sort.)

How to create random.txt file then randomly 500 random integers in the file then use that file to run common algorithms on them?

The code given below is not working:
My tasks are to,
Write a program that generates 500 Random Integers and stores them into an array. Integer values will be between 1 - 1000.
Print the 500 Random Integers to .txt file
The main method will control the run of the program. (menu, etc.)
Create a menu using the if/else ladder or switch case to control the operation of the program. The menu should be in main.
Create a “programmer created class” called Common_Algo
Read the 500 Random Integers from th .txt file you created in Task
2:
Use the class constructor to fill the array with random integers from the .txt file. The 500 integer array (arr[500]) will be an instance variable in the “programmer created class” - Common_Algo
All methods below will be encapsulated together with the 500 integer array in the Common_Algo class.
The main method from outside the Common_Algo class will control the
operation of the program.
Implement methods to achieve each outcome given below.
(Your menu will call the methods. All methods will operate on the same Array.)
Enter 1. Output all values
Enter 2. Output Sum of All Values and the Mean Average of Values
Enter 3. Output all odd numbers
Enter 4. Output all even numbers\
Enter 5. Output Middle Values (Values in the Middle)
Enter 6. Output First Value in the Array
Enter 7. Output Last Value in the Array
Enter 8. Enter a Search Value
Enter 9. Output Sorted Array
Enter 10. Output the Highest Value and its location in the array.
Enter 11: Output Lowest Value and its location in the array.
Enter 12: Exit
**Following is what I have implemented so far but it does not compile on the command prompt.**
import java.io.*;
import java.util.*;
public class Common_Algo
{
private int i;
int [] arr;
public Common_Algo()
{
try {
FileReader file = new FileReader("random.txt");
Scanner scanner = new Scanner(file);
arr = new int [500];
i = 0;
while (scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
void printAllValues()
{
for (i = 0; i<500; i++)
{
System.out.println(arr[i]);
}
}
void sumAndMean()
{
// calculate the sum
int sum = 0;
float average = 0;
for (int i = 0; i< arr.length; i++){
sum = sum + arr[i];
}
System.out.println("The sum of all the elements in the array " + sum);
// calculate the average
average = sum/arr.length;
System.out.println("Average of all vlaues of an array:" + average);
}
void oddNumber()
{
System.out.println("Odd numbers in array is:");
for(int i = 0; i<arr.length; i++)
{
if (arr[i]%2 ==0)
{
System.out.println(arr[i]);
}
}
}
void evenNumber()
{
System.out.println("Even numbers in array is:");
for(int i=0; i<arr.length; i++)
{
if (arr[i]%2==0)
{
System.out.println(arr[i]);
}
}
}
void middleValue(){
int m = 0;
if (arr.length%2 == 1)
{
m=(arr[(arr.length + 1)/2-1]);
}
else
{
m=(arr[arr.length/2-1]+arr[arr.length/2])/2;
}
System.out.println("Middle Value = "+ m);
}
void firstValue(){
System.out.println("The first value in the array is: " + arr[0]);
}
void lastValue()
{
System.out.println("The last value in the array is: " +arr[arr.length-1]);
}
void searchValue()
{
Scanner scanner = new Scanner (System.in);
int search_Value,flag=0;
System.out.println("Enter search value: ");
search_Value = scanner.nextInt();
//this does linear search for searching the value in array
for (int i = 0; i<arr.length; i++)
{
if (search_Value == arr[i])
{
System.out.println("Value " + search_Value +" is found at location "+ i);
flag = 1;
}
}
if (flag == 0)
{
System.out.println("Value " + search_Value + " is not found inside the array");
}
}
void sortArray()
{
Arrays.sort(arr);
System.out.println("The sort array list: ");
//sort array list
for (i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
void highValue()
{
int max = arr [0];
for (int i = 1; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
System.out.println("The highest value of array is: " + max);
}
}
}
void lowValue()
{
int min = arr[0];
for (int i = 1; i <arr.length; i++)
if (arr[i] < min)
min = arr[i];
System.out.println("The lowest value in the array: " + min);
}
}
class RandomData
{
public static void main(String[] args) {
int i,choice;
Scanner scanner = new Scanner(System.in);
Random rnum = new Random();
try {
PrintWriter fileout = new PrintWriter(new FileWriter ("random.txt"));
for (i = 0; i<500; i++)
{
fileout.println(rnum.nextInt(1000));
}
fileout.close();
}
catch (Exception e)
{
System.out.println(e);
}
Common_Algo object = new Common_Algo();
do
{
System.out.println("Enter 1 for: Output of all values ");
System.out.println("Enter 2 for: Ouput of Sum and mean Average values");
System.out.println("Enter 3 for: Output of all odd numbers");
System.out.println("Enter 4 for: Output of all even numbers" );
System.out.println("Enter 5 for: Output of middle values");
System.out.println("Enter 6 for: Output of first value in the array");
System.out.println("Enter 7 for: Output of last vlaue in the array");
System.out.println("Enter 8 for: Output of the entered search value");
System.out.println("Enter 9 for: Output of the Sorted Array");
System.out.println("Enter 10 for: Output of the highest value and its location in the array");
System.out.println("Enter 11 for: Output of lowest value and its location in the array");
System.out.println("Enter 12 for: Exit");
System.out.println("Please enter your choice");
choice = scanner.nextInt();
switch(choice)
{
case 1:
object.printAllValues();
break;
case 2:
object.sumAndMean();
break;
case 3:
object.oddNumber();
break;
case 4:
object.evenNumber();
break;
case 5:
object.middleValue();
break;
case 6:
object.firstValue();
break;
case 7:
object.lastValue();
break;
case 8:
object.searchValue();
break;
case 9:
object.sortArray();
break;
case 10:
object.highValue();
break;
case 11:
object.lowValue();
break;
case 12:
System.exit(0);
}
}
while(choice!=12);
}
}
Do not try to do everything at once in one big jump. Do it step by step. Your instructor has kindly already broken the problem up into steps. Write code for each step separately. Test that code to make sure it works, fixing any errors you find. Yes, this does mean reading and understanding any compile errors you find. Because you are only writing one piece at a time, there should not be too many errors in each piece.
When you have a tested and working piece of code, integrate it with the other pieces you have written so far and test the new combined code. Again, fix all errors.
This stepwise approach means you never have a big blob of code to fix, just small pieces which are a lot easier to work with. You build your final program piece by piece, testing and fixing all the way.

Bingo game Java

I'm trying to write a java code with(bingo game),(bullseye game)
the rules are simple:
computer picks 4 numbers
user input 4 numbers
must check the user input is between 1 to 10
If the user input exists in the computer randomized numbers it will be 1 bulls
If a number exist in the same location of the computer randomized number it will show 1 "eye"
Max limit is 20 tries until the user is considered "failed"; I need to print each round how many bulls were and how many eye were by the user input;
Example:
if the pc randomizing 1 4 6 7
and the user type 3 4 1 7
the output will be 3 bulls and 2 eyes.
my code prints 0 and 0 at the end.
Thanks for the help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
int[] pcGuess = new int[4];
int[] playerGuess = new int[4];
int countGuess = 0, bulls = 0, eye = 0;
final int maxGuess = 20;
System.out.println("Please press enter to begin");
in.nextLine();
boolean areNumbersCorrect = true; // a boolean value to define if the user input are correct (values between 1 to 10)
for (; countGuess < maxGuess; countGuess++) {
System.out.println("Please enter 4 numbers between 1-10");
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = in.nextInt();
pcGuess[i] = r.nextInt(10)+1;
if (playerGuess[i] < 0 || playerGuess[i] > 10) { // an if statement to check if the user input are correct
areNumbersCorrect = false;
do { // do while loop if the boolean is not true. (force the user to enter correct values)
System.out.println("Please try again");
for (int j = 0; j < playerGuess.length; j++) {
playerGuess[j] = in.nextInt();
if (playerGuess[j] > 0 && playerGuess[j] < 10) {
areNumbersCorrect = true;
continue;
}
}
} while (!areNumbersCorrect); // end of do while loop
}
for (int j=pcGuess.length; j>0; j--) { // for loop to check each number from the user and computer.
if (playerGuess[i] == pcGuess[i]) {
eye++; // if the user number exist in the same location evaluate eye++
if (playerGuess[i]%pcGuess[j]== 0) {
bulls++; // if the user number exist in the randomized number but not in the same location evaluate bulls++
}
}
}
System.out.println(
eye+" Hits!(same pc number and location)"+" And: "+bulls+" Numbers exist");
} if(eye==4&&bulls==4) {
break;
}
}
System.out.println("It took you: "+countGuess+" Times to guess the numbers");
}
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ArraysEx1 {
public static void main(String[] args) {
ArrayList<Integer> randNumbers = new ArrayList<>();
Random random = new Random();
String input;
int number;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please press enter to begin");
input = sc.nextLine();
}while (!input.equals(""));//loop while user doesn't press ENTER
for (int i = 0; i < 4; i++){
randNumbers.add(random.nextInt(10) + 1);//loop to fill the randNumbers arraylist with random numbers
}
/*
randNumbers.add(3);
randNumbers.add(2);
randNumbers.add(9);
randNumbers.add(9);
*/
System.out.println("My random numbers: " + randNumbers.toString());
int counter = 0;
int bulls = 0;
int eyes = 0;
do {
System.out.println("Please enter 4 numbers between 1-10");
number = sc.nextInt();
if (number > 0 && number <= 10){
//System.out.println("index of rand: " + randNumbers.indexOf(number));
//System.out.println("count: " + counter);
if (randNumbers.indexOf(number) == counter){
eyes++;
System.out.println("eyes++");
}else if (randNumbers.contains(number)){
bulls++;
System.out.println("bulls++");
}
counter++;
System.out.println("Number " + counter + " introduced. " + (4 - counter) + " more to go.");
}else {
System.out.println("Wrong number.");
}
}while (counter < 4);//loop for user to introduce valid numbers
System.out.println("You scored " + bulls + " bulls and " + eyes + " eyes.");
}
}
Try this piece of code. Note that I used ArrayList rather than an array, as it offers methods such as .contains() and .indexof().
WARNING: Code will fail if the randNumbers arraylist contains two numbers that are equals, such as the 3-2-9-9 array that is commented when you input 9-9-9-9 as your number guesses. This is because .indexof() method:
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
Meaning the code fails to account the last 9 as it will compare the count index (3) to the first occurrence of 9 in the randNumbers, which is 2, making it false and not increasing eyes count.
Since I'm short on time, and this is an assigment you have and just copying it won't teach you much, I'll leave it to you to solve this specific case (I already told you what's wrong, won't be difficult to solve).

Counting how many times each number was typed

Im trying to count how many times each number between 0 to 9 was typed in a loop, when press -1 it will stop the loop, I made it work with the long term, Also I would have to print which of the numbers was typed the most.
For now I only have the couting code:
int pickedNum,counter_0=0,counter_1=0,counter_2=0,counter_3=0,counter_4=0,counter_5=0,counter_6=0,counter_7=0,counter_8=0,counter_9=0;
do{
System.out.println("Please enter a numbr between 0-9 , -1 to exit:");
pickedNum=s.nextInt();
if(pickedNum==0){
counter_0++;
}
if(pickedNum==1){
counter_1++;
}
if(pickedNum==2){
counter_2++;
}
if(pickedNum==3){
counter_3++;
}
if(pickedNum==4){
counter_4++;
}
if(pickedNum==5){
counter_5++;
}
if(pickedNum==6){
counter_6++;
}
if(pickedNum==7){
counter_7++;
}
if(pickedNum==8){
counter_8++;
}
if(pickedNum==9){
counter_9++;
}
}
while(pickedNum != -1);
System.out.printf("The number 0 appears: %d \n"
+ "The number 1 appears: %d \n"
+ "The number 2 appears: %d \n"
+ "The number 3 appears: %d \n"
+ "The number 4 appears: %d \n"
+ "The number 5 appears: %d \n"
+ "The number 6 appears: %d \n"
+ "The number 7 appears: %d \n"
+ "The number 8 appears: %d \n"
+ "The number 9 appears: %d \n",
counter_0,counter_1,counter_2,
counter_3,counter_4,counter_5,
counter_6,counter_7,counter_8,counter_9);
as you can see, It works fine, But I know there is a way better option to do this thing.
And as I mentioned, I also need to print the largest number counts(which number was type the most), and It will take a long way to reach that with my way of programming this.
I would like to get any tip or notes to improve this to work easier and faster.
Any notes would be appriciated.
EDIT:
Forgot to mention to use only basics, and not advanced methods, array and loops are fine.
int count[] = new int[10];
do{
counter[pickedNum]++;
} while(pickedNum != -1);
And then use counter[0], counter[1] etc in your print statement.
Don't forget that you can have more than one number that was typed the most, take a look at this :
public static void main(String[] args) throws ParseException {
int pickedNum, highestCounter = 0;
Scanner s = new Scanner(System.in);
int count[] = new int[10];
while (true) {
System.out.println("Please enter a numbr between 0-9 , -1 to exit:");
pickedNum = s.nextInt();
if (pickedNum != -1) {
count[pickedNum]++;
} else {
break;
}
}
int index1 = 0;
for (int i : count) {
System.out.println("The number " + index1 + " appears : " + i);
index1++;
}
// Finding the number was typed the most
for (int counter : count) {
if (counter > highestCounter) {
highestCounter = counter;
}
}
// In case if you have more than one number that was typed the most
Integer[] indexes = new Integer[10];
int index2 = 0;
for (int counter : count) {
if (highestCounter == counter) {
indexes[index2] = index2;
}
index2++;
}
System.out.print("The number(s) was typed the most is/are : ");
for (Integer i : indexes) {
if (i != null) {
System.out.print(i + ", ");
}
}
}
And the output :

Identifying if the user presses <enter>

I have been working on this for several days and I'm super frustrated. This is my first course in Java so please bear with me on lack of knowledge still. I'm supposed to write a program that contains an array of 10 grades entered by the user and I calculate the average. In particular I'm having problems with what is down below.
You should not read doubles numbers from the user, you should read a string. Here is the process:
Read a string from the user
trim the string and get the length
if the length <1 then the user hit and you get out
if the length is >0 then you convert the string into a double using
d =Double.parseDouble(S);
So far I just have this. I have been adding and deleting a lot of coding to this for the past week. And I still cant seem to get it to work. Any help would be much appreciated!
import java.util.*;
import java.io.*;
public class Arrays {
public static void main(String[] args) {
double d = 0;
final int SIZE = 10;
Scanner reader = new Scanner(System.in);
String[ ] grades = new String[SIZE];
System.out.println("Please enter up to 10 grades.");
for (int i = 0; i < grades.length; i++){
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine( );
}
System.out.println("\nNumber of valid grades entered: " + grades.length);
}
}
Try this
for (int i = 0; i < grades.length; ){
System.out.print("Grade " + (i + 1) + ": ");
String str = reader.nextLine();
if(str.trim().length() > 0){
try{
grades[i] = Double.parseDouble(str);
i++;
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
System.out.println("\nNumber of valid grades entered: " + i);
IMHO i think grades should be an array of double ie
double[] grades=new double[SIZE];
You can try it in following way
int correctGrades=0;
double[] grades=new double[SIZE]; //Create array of double instead of String
for (int i = 0; i < SIZE; i++){
System.out.print("Grade " + (i + 1) + ": ");
String str=reader.nextLine();
if(str.length() > 0){ // If length is greater than 0 then its correct grade
grades[i]=Double.parseDouble(str);
correctGrades++;
}
}
System.out.println("\nNumber of valid grades entered: " + correctGrades);
As per my understanding this should be your for loop
for (int i = 0; true; i++) {
System.out.print("Grade " + (i + 1) + ": ");
grades[i] = reader.nextLine();
if (grades[i].equals("")) {
break;
}
//check for number format exception if user enters invalid input
try {
d = Double.parseDouble(grades[i]);
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
}
System.out.println("The value of double entered is : " + d);
}
Here you run the loop for infinite number of times but with every loop you check the user input.
Now if the user enters an empty string you exit the loop using the break statement

Categories