Java Array Beginner Menu - java

I am trying to make a menu where the user has an option to add numbers to the array and technically they can add how many values they want but one at a time. So when they pick to add a number to the array, they would enter one number, and then it would prompt the menu again. I'm having trouble with adding the number to the array & displaying the array. I'll add two numbers & display the array to look at it & I get 30000000000000000000000000000000000000000000000000000000000 because of my array max, I think. all I want is for it to add only the digits I enter to the array when I want to enter it & continue to do that from there.
how exactly would I fix that though? I want the user to have complete control to how big the array will be, etc.
import java.util.*;
public class arrayMenu
{
public static void main(String[] args)
{
Scanner kb;
int option;
kb = new Scanner(System.in);
option = menu(kb);
int[] myArray = new int[99];
while (option != 6)
{
switch (option)
{
case 1:
myArray = newNum(kb, myArray);
break;
case 2:
display(myArray);
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
option = menu(kb);
}
if (option == 6)
{
System.out.println();
System.out.println("Thank you. Have a nice day.");
}
}
public static int menu(Scanner kb)
{
int myOption = 0;
while (myOption != 1 && myOption != 2 && myOption != 3 && myOption != 4 && myOption != 5 && myOption != 6)
{
System.out.println();
System.out.println("Please select from the following menu choices.");
System.out.println();
System.out.println("1. Add a number to the array \n2. Display the mean \n3. Display the median \n4. Print the array to the screen \n5. Print the array in reverse order \n6. Quit");
System.out.println();
System.out.print("Choice --> ");
myOption = kb.nextInt();
kb.nextLine();
if (!(myOption == 1 || myOption == 2 || myOption == 3 || myOption == 4 || myOption == 5 || myOption == 6))
System.out.println("I am sorry that is an invalid menu choice.\nPlease try again");
}
return myOption;
}
public static int intNum(Scanner kb)
{
int num = -1;
while (!(num >= 0))
{
System.out.print("Please enter a non-negative integer -->");
num = kb.nextInt();
if (num < 0)
System.out.print("I am sorry that is not a non-negative integer. \n");
}
return num;
}
public static int[] newNum(Scanner kb, int[] array)
{
for (int i = 0; i < 1; i++)
{
System.out.print("Please enter a number:");
array[i] = kb.nextInt();
}
return array;
}
public static void display(int[] array)
{
for (int myValue : array)
{
System.out.print(myValue);
}
}
}

Well the newNum method looks very questionable. The loop is only going to around once since the loop counter test checks < 1. i will always be 0 and you will always be adding the new number to the [0] place in the array. You have no 'current index' variable to keep track of where your current place in the array is. The array is going to be 1 int and the rest of the values will be 0 - which looks like what you included in the posting.

Related

I want to write a program that allows the user to guess a number between 0 and 100 in 7 attempts. I don't know why is this not working

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.

How am i going to use while loop and if else if user enter the same input twice and it will try again

I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}

Using method to find an integer repeatedly

Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.

Can I use "return" in here or any ideas?

I'm really new to Java and most of my knowledge are self- taught. can you help me to figure out this.
Our teacher wants us to make a menu about Java. Where the output something like this..
Menu
1 - Java History
2- Java Keywords
3 - Java Arrays and so on. .
Do you want to read one (Yes/No):
//if yes
Please enter a menu number:
// then it will display an information..
//my problem is that how can I connect the new entered value to the first method so that I don't have write it all over again...
this is whats on my mind..
but im stuck..
import java.util.Scanner;
public class Program {
public static void main (String [] args) {
System.out.println("Please enter a number:");
int x = nextInt();
if (x == 1) {
for (int x = 5; x == 5;x++) // array of 1(first menu)
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 2) {
for loop of array 2
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 3) {
for loop of array 3
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
else if (x ==4) {
for loop of array 4
else if (x == 5) {
for loop of array 5
else if (x == 6) {
for loop of array 6
else if (x == 7) {
for loop of array 7
else if (x == 8) {
for loop of array 8
else if (x == 9) {
for loop of array 9
else if (x == 10) {
for loop of array 10
else {
//exit the program
If I understand correctly, you would want to implement the While or do while statement in your program.
Example of While and Do While Loops
Im not really sure what you are trying to accomplish with your program but here is a little example I made quickly of how to utilize the for loop in your case. `import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean keepGoing = true; //As long as this is true the while statement will continue;
while (keepGoing) {
System.out.println("Enter a number");
int x = scan.nextInt();
//logic
if (x == 1) {
System.out.println("X is equal to 1");
} else if (x == 2)
System.out.println("X is equal to 2");
//prompts the user if they want to keep going.
System.out.println("Would you like to keep going? Y/N");
String decision = scan.next();
if (decision.equalsIgnoreCase("y")) {
keepGoing = true;
} else {
System.out.println("Quitting...");
keepGoing = false;
}
}
}
}
`

Why am I getting nullpointer Exception in this Program?

I am new to Java , can anyone explain why i am getting a Null pointer Exception ?
Additionally can anyone explain other reliable input methods besides Scanner.
The Error
Exception in thread "main" java.lang.NullPointerException
at Theater.main(Theater.java:18)
import java.util.Scanner;
public class Theater
{
public static void main(String[] args) throws Exception
{
int Screen;
Screens[] X = new Screens[5];
Scanner input = new Scanner(System.in);
do
{
System.out.println();
System.out.println(" '0' to exit");
System.out.println(" '1-5' for Booking Seats");
System.out.println(" '10' for Displaying Seating Status");
System.out.println("Enter Screen Number : ");
Screen = input.nextInt();
if(Screen >= 1 && Screen <= 4)
X[Screen-1].bookSeat();
else if(Screen == 0)
{
System.out.println("Thank You for Booking Seats in PVR Cinemas.");
System.in.read();
System.exit(0);
}
}while(true);
}
}
class Screens
{
private
int[] Gold = new int[3];
int[] Platinum = new int[3];
int[] Diamond = new int[3];
int g,d,p;
Scanner input = new Scanner(System.in);
final int MAX=3;
public Screens()
{
for( int i=0;i<3;i++)
{
Gold[i] = 0;
Platinum[i] = 0;
Diamond[i] = 0;
g = d = p = 0;
}
}
public void bookSeat()
{
int n=0,choice,i;
System.out.println("\t\tMenu");
System.out.println("1.Gold \tAvailable Seats : "+(3-g));
System.out.println("2.Platinum \tAvailable Seats : "+(3-p));
System.out.println("3.Diamond \tAvailable Seats : "+(3-d));
System.out.println("4.Return to Main Menu");
System.out.println("Your Choice : ");
choice = input.nextInt();
if(choice>=1 && choice<=3)
{
System.out.print("How many Seats ? : ");
n = input.nextInt();
if( n<=0 )
{
System.out.println("Please Check your Input.");
return;
}
else if( n>=MAX )
{
System.out.println("The Maximum Number of Seats is : "+MAX);
}
}
switch(choice)
{
case 1:
if(g+n >3)
{
System.out.println("Housefull!");
break;
}
else
{
int total = 0;
System.out.print("Seat Numbers are : ");
for(i=0;i<n;i++)
{
Gold[g++] = 1;
System.out.print("\t"+g);
}
total = 100 * n;
System.out.println("Total Money to be paid : "+total);
}
break;
case 2:
if(p+n >3)
{
System.out.println("Housefull!");
break;
}
else
{
int total = 0;
System.out.print("Seat Numbers are : ");
for(i=0;i<n;i++)
{
Platinum[p++] = 1;
System.out.print("\t"+p);
}
total = 125 * n;
System.out.println("Total Money to be paid : "+total);
}
break;
case 3:
if(d+n >3)
{
System.out.println("Housefull!");
break;
}
else
{
int total = 0;
System.out.print("Seat Numbers are : ");
for(i=0;i<n;i++)
{
Diamond[d++] = 1;
System.out.print("\t"+d);
}
total = 150 * n;
System.out.println("Total Money to be paid : "+total);
}
break;
case 4:
break;
default:
System.out.println("Sorry, That's an invalid Choice!");
}
return;
}
public void viewSeats()
{
int i;
System.out.println("Gold Category : ");
for(i=0;i<3;i++)
System.out.print("\t "+Gold[i]);
System.out.println("Platinum Category : ");
for(i=0;i<3;i++)
System.out.print("\t "+Platinum[i]);
System.out.println("Diamond Category : ");
for(i=0;i<3;i++)
System.out.print("\t "+Diamond[i]);
}
}
You need to populate your Scrrens array. In other words you have only initialized your Scrren array but never initialized its elements.If you don't initialize its elements they get default values which in this case is null. Guess what happens when you invoke somemethod on null. Boom NPE you get.
Screens[] X = new Screens[5];
x[0] = new Screen();
Although you initialize the array X you do not initailize its members so when doing X[Screen-1] you are using a null object (even if the index is in the bounderies).
Because your array X doesn't have any elements in it, so by default every element is initialized to null. So basically you are trying to do this null.bookseat() which results in a NullPointerException.
It is also important to note that if Screen is ever 5 (which is allowed by your condition <= 5) then you will get an ArrayIndexOutOfBoundsException because your array only have indices 0,1,2,3,4 (5 total)
Your array X is being created, but the elements are not initialized, they are still null. I think you are expecting to have your array initialized like this:
Screens[] X = new Screens[5];
for (int x = 0; x < 5; x++) {
X[x] = new Screens();
}
You get a NullPointerException because you have declared an array to hold 5 screen objects but you have never initialized the 5 slots with an actual Screen object
Thus when you try to use the
X[Screen-1].bookSeat();
you are referencing a null element in the array and of course you cannot call a method of a null object
You could add a check before using the object and initialize the screen
if(Screen >= 1 && Screen <= 4) {
if (X[Screen-1] == null)
X[Screen-1] = new Screens();
X[Screen-1].bookSeat();
}
also there is something weird in your usage. Arrays start at zero index but you use the zero as a value to exit from the program, so the element at index zero is never used.
Because after Screens[] X = new Screens[5]; all 5 elements of array X are null!!
One more way to populate your Screens array
Screens[] X = { new Screens(), new Screens(), new Screens(),new Screens(), new Screens() };
you may find using List from Collections more useful.

Categories