Check if array is already created in Java - java

class CreateArray{
Scanner input = new Scanner(System.in);
public void Create(){
System.out.print("How many numbers numbers do you want to enter? Minimum of 5 and a maximum of 20 only: ");
int num = input.nextInt();
if (num >=5 || num >20){
int array[] = new int[num];
System.out.println("Enter the numbers you want: ");
if(array.length != 0){
for(int i = 0 ; i<array.length; i++){
array[i] = input.nextInt();
}
}
System.out.print("Your array of numbers are: ");
for(int i = 0 ; i<array.length; i++){
System.out.print(array[i] + " ");
}
}
else{
System.out.print("Please input a the right numbers of array");
} }}
I would like to know how to identify if array is already created so that i can display an error message. I have two classes as you can see above theres the class CreateArray and here is the main class: I am new to java actually so forgive me. And also the logic is that when user create an array then they decide to continue and check again the code will output "you have already created an array" Thank you so much for answering.
public class Lab3
{public static void main(String[] args){
Scanner ans = new Scanner(System.in);
String choice;
String choices;
do{
System.out.println("[1] Create Array");
System.out.println("[2] Insert Element");
System.out.println("[3] Search");
System.out.println("[4] Display");
System.out.println("[5] Delete");
System.out.println("[0] Stop");
System.out.print("\nEnter Choice: ");
choice = ans.nextLine();
if(choice.equals("1")){
CreateArray myObj = new CreateArray();
myObj.Create();
}
else{
System.out.print("Array has been created please procedd to other options!");
}
System.out.println();
System.out.print("Do you want to continue? : ");
choices =ans.nextLine();
}
while(!choices.equals("-1") || !choices.equals("-1"));
}}

You can check if an array is already created by using a global array variable that you can check from your main class.
Add this line int array[]; to the CreateArray class as a global variable, and replace int array[] = new int[num]; with array = new int[num]; so that it referances to the global vairable.
Then from your main/Lab3 class you can simply use if (myObj.array == null) to check if the array has NOT been created, or use if (myObj.array != null) to check if the array HAS been created.
Note, you also need to place the following code outside of the do{} while () loop CreateArray myObj = new CreateArray(); otherwise it will create a new object every loop and you will not be able to keep the inputs.
The complete code might look like this (with a few other changes to make more sense):
class CreateArray {
Scanner input = new Scanner(System.in);
//place a global variable here
int array[];
public void Create() {
System.out.print("How many numbers numbers do you want to enter? Minimum of 5 and a maximum of 20 only: ");
int num = input.nextInt();
//Fix this line as shown by Scary Wombat in comments:
if (num <= 5 || num <= 20) {
//Initialize the array here (This will make it a non null value)
array = new int[num];
System.out.println("Enter the numbers you want: ");
if (array.length != 0) {
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
}
System.out.print("Your array of numbers are: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
} else {
System.out.print("Please input a the right numbers of array");
}
}
}
And the Lab3 class could look like this:
public class Lab3 {
public static void main(String[] args) {
Scanner ans = new Scanner(System.in);
String choice;
String choices;
//Place the CreateArray object here so that it can be re-used between selecting options, otherwise you will lose all progress
CreateArray myObj = new CreateArray();
do {
System.out.println("[1] Create Array");
System.out.println("[2] Insert Element");
System.out.println("[3] Search");
System.out.println("[4] Display");
System.out.println("[5] Delete");
System.out.println("[0] Stop");
System.out.print("\nEnter Choice: ");
choice = ans.nextLine();
//Only call this method if it has not been created yet
if (choice.equals("1") && myObj.array == null) {
myObj.Create();
}
//If another option is chosen but the array has not been created, then give an error message
else if (myObj.array == null) {
System.out.print("Array has not been created yet, please choose option 1.");
}
else if (choice.equals("1")) {
System.out.print("THe array has already been created, please choose another option.");
}
//Place all other value checkes after the above checks:
else if (choice.equals("2")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("3")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("4")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("5")) {
System.out.print("This opetion is not yet supported.");
} else if (choice.equals("0")) {
System.out.print("This opetion is not yet supported.");
break;
} else {
System.out.print("Invalid option.");
}
System.out.println();
System.out.print("Do you want to continue? : ");
//What does this do?
choices = ans.nextLine();
} while (!choices.equals("-1"));
}
}

Related

Scan a number of names, print names (number==amount of names) and print Hello to each of them

I am new to Java and have a task: Scanner a number of "strangers' " names, then read these names and print "Hello+name" to the console. If number of strangers is zero, then print "Looks empty", if the number is negative, then print "Looks negative to me".
So the input and output to console should look like this:
3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel
So I have this code edited from someone with some related task, but it seems I miss something as I am new to Java...
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
while (num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
} while (num<0) {
System.out.println("Seriously? Why so negative?");
break;
}
String[] numbers = new String[num];
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +input.nextLine());
}
With using do while loop you can ask the number to the user again and again if it is negative number.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int num;
String name;
Scanner scan = new Scanner(System.in);
//The loop asks a number till the number is nonnegative
do{
System.out.print("Please enter the number of strangers: ");
num = scan.nextInt();
if(num<0) {
System.out.println("It cannot be a negative number try again.");
}else if(num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
}else{
String[] strangers = new String[num];
//Takes the names and puts them to the strangers array
for(int i=0;i<num;i++) {
System.out.print("Name " + (i+1) + " : ");
name = scan.next();
strangers[i] = name;
}
//Printing the array
for(int j=0; j<num; j++) {
System.out.println("Hello, " + strangers[j]);
}
break;
}
}while(num<0);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
if(num==0) {
System.out.println("Oh, it looks like there is no one here");
}
else if(num<0) {
System.out.println("Seriously? Why so negative?");
}
else {
String numbers[] = new String[num];
input.nextLine();
for (int i=0; i< num;i++) {
numbers[i]=input.nextLine();
}
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +numbers[i]);
}
}
}
}
This is how your code will look and you'll need to add member function input.nextLine(); to read newline character, so there can't be problem regarding input

I'm trying to get my program to continue asking for input and answering that input

I have this program here that reads a list of numbers from an input file, then asks the user to enter a number. The program then looks into the file and if the number that the user entered is in the file, it will display "This number is in the file" if the number is not in the file, the program will display, "Number is not in file." The program then has to keep asking the user to enter numbers and based on the number entered, the program needs to write back the appropriate response. The first time the user is asked to enter a number, the program works correctly and prints back the correct response, the problem is that after the program asks again to enter a number, it will print back the same response as the first number entered no matter what number is entered whether it's in the file or not. Are my while loops in the wrong place? Not sure how to fix this.
package classwork7_2;
import java.util.*;
import java.io.*;
public class ClassWork7_2 {
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(System.in);
int[] numbers = fileToArray();
Arrays.sort(numbers);
System.out.print("Enter a number in the file: ");
int numb = s.nextInt();
int i = Arrays.binarySearch(numbers, numb);
if(i < 0){
while(i < 0){
System.out.print("Number is not in file\n");
System.out.print("Enter number in the file: ");
s.nextInt();
}
}
else if(i >= 0){
while(i >= 0){
System.out.print("This number is in the file\n");
System.out.print("Enter number in the file: ");
s.nextInt();
}
}
}
public static int[] fileToArray() throws IOException{
Scanner s = new Scanner(System.in);
int[] array = new int[7];
System.out.print("Enter name of file: ");
String filename = s.nextLine();
File f = new File(filename);
Scanner inputFile = new Scanner(f);
int i = 0;
while(inputFile.hasNext()){
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
return array;
}
}
Try this
public static void main(String[] args)throws IOException {
Scanner s = new Scanner(System.in);
int[] numbers = fileToArray();
Arrays.sort(numbers);
while(true) {
System.out.print("Enter a number in the file: ");
int numb = s.nextInt();
int i = Arrays.binarySearch(numbers, numb);
if (i < 0) {
System.out.print("Number is not in file\n");
} else if (i >= 0) {
System.out.print("This number is in the file\n");
}
}
}
The problem is that you don't peform search after second input, so old result is printed out. You must re-assign user input and perform search for every input:
for(;;) { // infinite loop
System.out.println("Number is not in file");
num = s.nextInt(); // re-read user input
int i = Arrays.binarySearch(numbers, numb); // search again based on input
if (i < 0) {
System.out.println("Number is not in file\n");
} else {
System.out.print("This number is in the file\n");
}
}
Just remove the first input and do everything in the loop. The main will become:
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
int[] numbers = fileToArray();
Arrays.sort(numbers);
while (true) {
System.out.print("Enter a number in the file: ");
int numb = s.nextInt();
int i = Arrays.binarySearch(numbers, numb);
if (i < 0) {
System.out.print("Number is not in file\n");
} else {
System.out.print("Number is in file\n");
}
}
}
The problem is you don't have exit condition - it will ask forever. You might think for something ;)

I'm almost finished, but how to loop the entire program?

My cash register program is nearly complete, it can process sales and returns and adds or subtracts this to the money in the register.
My only problem is that once I'm done adding values for example, the program closes and i cant figure out how to loop it back to the choice menu. I tried using a do loop and a do while loop but it yelled at me saying it had invalid input (probably because you have to press F to stop when you're checking out).
How can I loop this whole thing?
import java.util.Scanner;
import java.util.ArrayList;
public class Assignment3_000848913
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Integer> Prices = new ArrayList<Integer>();
ArrayList<Integer> ReturnPrices = new ArrayList<Integer>();
int totalRegisterMoney = 0;
int Choice = 0;
System.out.print("What would you like to do?");
System.out.println();
System.out.print("Press 1. Process a sale");
System.out.println();
System.out.print("Press 2. Process a return");
System.out.println();
System.out.print("Press 3. Display Money in register");
System.out.println();
System.out.print("Press 4. Exit");
System.out.println();
Choice = in.nextInt();
if(Choice == 1)
{
//THIS LOOP READS IN ALL THE PRICES//
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the integer price of the item: $");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
int totalPrice = processSale(Prices);
totalRegisterMoney = totalRegisterMoney + totalPrice;
System.out.print("Your total comes to $");
System.out.println(totalPrice);
}
if(Choice == 2)
{
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the price of the returned item: $");
int j = in.nextInt();
ReturnPrices.add(j);
System.out.println();
}
while(in.hasNextInt());
int returnTotal = processReturn(ReturnPrices);
if(returnTotal > totalRegisterMoney)
{
System.out.print("Sorry, there's not that much money in the register.");
System.out.println();
}
else
{
totalRegisterMoney = totalRegisterMoney - returnTotal;
}
System.out.print("You've completed the return.");
System.out.println();
}
if(Choice == 3)
{
viewBalance(totalRegisterMoney);
}
}
//END OF MAIN
If you were getting that error when you did the do..while, you were doing it OK.
The problem is that after writing the 'F' to exit option 1 , the loop returns and tries to convert that 'F' into
Choice = in.nextInt();
This causes an error bucause a 'F' is not a number.
You would need to put an
in.next();
after your
while(in.hasNextInt());
This also would happen on option 2 in your code

Java: How to use a sentinel value to quit a program when the user wants

The only thing i am missing is to use a sentinel value, like zero, to quit the loop when the user wants, even without enter any gussing.
import java.util.Scanner;
import java.util.Random;
public class RandomGuessing {
//-----------------------------------------------------------------------------------------------
//This application prompt to the user to guess a number. The user can still playing until
//guess the number or want to quit
//-----------------------------------------------------------------------------------------------
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Random rand = new Random();
int randNum = rand.nextInt(100) + 1;
System.out.println(randNum);
System.out.println("\t\tHi-Lo Game with Numbers\t\t\n\t Guess a number between 1 and 100!!!\n");
String ans;
int attemptsCount = 0;
do {
System.out.print("Guess the number: ");
int input = scan.nextInt();
while(input != randNum){
attemptsCount++;
if(input < randNum){
System.out.println();
System.out.print("low guessing\nEnter new number: ");
input = scan.nextInt();
}
else{
System.out.println();
System.out.print("high guessing\nEnter new number: ");
input = scan.nextInt();
}
}
System.out.println();
System.out.println("Congrats!!! You guess right\nAttempts: "+attemptsCount);
System.out.println();
System.out.print("You want to play again (yes/no): ");
ans = scan.next();
randNum = rand.nextInt(100) + 1; //generate new random number between same above range,
//if the user wants to keep playing.
}while (ans.equalsIgnoreCase("yes"));
}
}
Here's a simple approach:
// inside do loop
System.out.print("Guess the number (-1 to quit): ");
int input = scan.nextInt();
if (input == -1) {
break;
}
Try using this code for exiting totaly:
System.exit(0);

array display method difficulty

newbie here. So i'm testing out arrays, it's the next topic in the tutorial that i have been reading. I made a simple program to specify how many numbers to get or to input. The problem is on the getArray() method, i can't seem to display it. It's giving me an exception in thread error. Any help and advice is much appreciated. :) Sorry for the newbie question. :))
So here's the code.
import java.util.Scanner;
public class ArrayNumbers {
Scanner input = new Scanner(System.in);
int totalNum, counter, count = 0, display;
double arrayNum[];
public void setArrayNum() {
System.out.print("How many numbers?: ");
totalNum = input.nextInt();
double arrayNum[] = new double[totalNum];
for (counter = 0 ; counter < arrayNum.length ; counter++) {
System.out.print("Num "+(count = counter + 1)+": ");
arrayNum[counter] = input.nextInt();
}
}
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
}
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Numbers NumbersObject = new Numbers();
ArrayNumbers ArrayNumbersObject = new ArrayNumbers();
String name;
int choice;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.println("Menu");
System.out.println("1. Math Operations");
System.out.println("2. Grade Computation");
System.out.println("3. Counting Numbers");
System.out.println("4. Array Numbers");
System.out.print("Enter choice: ");
choice = input.nextInt();
switch(choice) {
case 1:
System.out.println("Choose Operation");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter choice: ");
choice = input.nextInt();
NumbersObject.setNum();
if (choice == 1)
System.out.println("The answers is "+(NumbersObject.getNum1() + NumbersObject.getNum2()));
else if (choice == 2)
System.out.println("The answers is "+(NumbersObject.getNum1() - NumbersObject.getNum2()));
else if (choice == 3)
System.out.println("The answers is "+(NumbersObject.getNum1() * NumbersObject.getNum2()));
else if (choice == 4)
System.out.println("The answers is "+(NumbersObject.getNum1() / NumbersObject.getNum2()));
else
System.out.print("Invalid Input!");
break;
case 2:
NumbersObject.setNum();
System.out.println("Your average grade is "+((NumbersObject.getNum2() + NumbersObject.getNum2()) / 2));
break;
case 3:
System.out.println("Welcome to Counting Numbers!");
System.out.println("Enter 2 numbers to start and end!");
NumbersObject.setNum();
for (int counter = (int) NumbersObject.getNum1() ; counter <= NumbersObject.getNum2() ; counter++) {
System.out.println(counter);
}
System.out.println("End!");
break;
case 4:
ArrayNumbersObject.setArrayNum();
ArrayNumbersObject.getArray();
break;
default:
System.out.println("Mr/Ms "+name+" you entered an Invalid Choice!");
break;
}//end of switch
}// end of main
}// end of class
Sorry about that, for not including the main.
And here's the error:
Exception in thread "main" java.lang.NullPointerException
at ArrayNumbers.getArray(ArrayNumbers.java:23)
at MainProgram.main(MainProgram.java:67)
Guys, the only i problem i have is in the getArray()
It asks for what number in the array i want to see but when i input it, it gives an exception in the thread error. The only problem is how am i going to display the array[number i specified]? Sorry for the newbie questions.
It throws an exception because you create an array of size display and you try to print the element at the display position but arrays are 0 base indexed in Java.
This figure should be useful :
So imagine that display = 10 :
double arrayNum[] = new double[display]; //create an array that can holds 10 elements
System.out.print(arrayNum[display]); //try to access at the 10th element of the array but it doesn't exists !
You don't have to create a new array because you want to display the number in the arrayNum you created in your class.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
Also you need to check if display is in the correct bounds range [0,...,displayNum.length-1] before trying to access its elements.
Edit :
In setArrayNum() replace double arrayNum[] = new double[totalNum]; by arrayNum = new double[totalNum];
Arrays are 0-based. So if you create an array of size display you can access indexes 0..display-1
You are creating local array double arrayNum[] = new double[display]; within getArray() method.
You need to remove double arrayNum[] = new double[display]; from getArray() method.
After that your method like below.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
if(display >0 && display <=arrayNum.length){
System.out.print(arrayNum[display-1]);
}else{
System.out.print(display + " is out of range");
}
}

Categories

Resources