Is there a way to initiate the array only once? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here's my code:
import java.util.Arrays;
import java.util.Scanner;
public class User
{
private static int [] users;
public User(){
users = new int[10];
Scanner input = new Scanner(System.in);
int InputNumber = input.nextInt();
int length = String.valueOf(InputNumber).length();
I have an method that calls this one, but I believe it's that everytime I do it, it creates an array, or that's what I think it does.
Down here is just a bunch of code to make verifications and add the number to the array.
if(length != 8 || InputNumber < 0){
System.out.println("That number isn't valid, try again, the number must have 8 digits");
User menu = new User();
return;
}else{
int i = -1;
do{
i++;
continue;
}while((users[i] != 0 && users[i] == InputNumber) );
if(i == users.length){
System.out.println("There's enough space, delete users");
}else if(users[i] != 0 && users[i] == InputNumber){
System.out.println("That user already exists");
}else{
System.out.println("The user " + InputNumber + " as been added!");
users[i] = InputNumber;
}
//show a menu
}
}
There aren't any errors and I can create a user but the thing is, every time I try to create another one it looks like it creates another array, I think. What I want to know is what can I change to make this work.

Since the array field is static and your initializing the array in the constructor everytime your creating a new User object your reinitializing the array and losing all the information that was there.
If you really need to have that field static simply initiate in the same line like this:
private static int [] users = new int[10];
Other thing you could do if you really want to initialize the field in the constructor is to check if the array is null or not:
if(users == null) {
users = new int[10];
}

With your example all you need is to initialize array once is to actually initialize it only once:
private static final int[] users = new int[10];

You can do 2 things:
replace this code for your static line
private static int [] users = new int[10];
and delete initialization in constructor
or you can check for null reference in constructor
if(users == null) users = new int[10];

Related

Trying to print out some sequence of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print out a sequence of numbers using this formula
Enter a number
if number is even divide number by 2.
But if number is odd multiply number by 3 and add 1
continue doing this until number becomes 1
sample input=3
Sample output=10 5 16 8 4 2
this is what I tried but still not getting it
package victor;
import java.util.Scanner;
public class proj {
public static void main(String[] args) {
Scanner put=new Scanner(System.in);
int temp=0;
boolean notOne=true;
System.out.println("input::: ");
int num=put.nextInt();
while(temp!=1){
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
else {
temp=num;
System.out.println(temp*3+1);
break;
}
}
if(temp!=1){
notOne=false;
}
}
}
It's not working because you keep re-assigining the variable temp to the initially scanned num.
You keep checking if the initially scanned num is odd or even, when you should check if temp is odd or even.
You also break out of the loop for no reason.
And finally, you're not saving the result of the operations, you're only printing out the result.
Try to understand the points I mentioned above by noticing the differences between your code and the following:
while(temp!=1){
if (temp%2==0){
temp = temp/2;
}
else {
temp = temp*3+1;
}
System.out.println(temp);
}
You are not updating the value of temp. You are just printing it. Take the following statement
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
Here you are setting temp to num and just printing temp/2 and never setting a value.
I wrote my version of it which is a bit more simpler. I hope this will help you. You can create a string to get a better output of course.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scan.nextInt();
while (number != 1) {
number = number % 2 == 0 ? number / 2 : ((number * 3) + 1);
System.out.println("Number became " + number);
}
}
}
Try this:
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
//Lets start the program, first we need
//the Scanner class to access to the input
Scanner stdin = new Scanner(System.in);
System.out.print("Type a num: ");
//I dont use: nextInt() because when asking for another input, will scan only
//the rest of the line (Maybe just \n - line break )
int num = Integer.parseInt(stdin.nextLine());
//Optional
int loops = 0;
while(num!=1){
//Pair, so num/2
if ( num %2 == 0){
num/=2;
}
else{
//num*3 +1
num=num*3 +1;
//Note that:
//1 + num*3
//Doesnt alter the result
}
System.out.println("num: "+num);
loops++;
}
System.out.println("total loops: "+loops);
}
}

Multiple Choice and True/False Quiz using loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to build a quiz for a user that has to have 5 multiple choice questions and 5 true/false questions. I must do this using loops (while loops). I've come to the point where I set up a separate method asking the user the questions and error checking for the true/false or multiple choice questions. I now have to somehow give the user a point if they answer each question correctly. Then in the end, I must give the user the the total amount of points they won. Then I have to ask if they want to play again in the end, if they say yes I have to go back to the first question and restart the game and if they say no the program has to close. Here is where I got to on my main method. I started putting a while loop for the first answer (correct answer being 3) and making a point variable but I'm not sure where to go from there and how to connect everything. I hope what I did so far is correct. Thanks!
UserInteraction input = new UserInteraction();
Questions ask = new Questions();
int answer1 = 0, answer2 = 0, answer3 = 0, answer4 = 0, answer5 = 0;
int a1 = ask.Question1(answer1);
int point;
while (a1==3)
{point = 1;
}
int a2 = ask.Question2(answer2);
int a3 = ask.Question3(answer3);
int a4 = ask.Question4(answer4);
int a5 = ask.Question5(answer5);
boolean answer6=false, answer7=false, answer8=false, answer9=false, answer10=false;
String a6 = ask.Question6(answer6);
String a7 = ask.Question7(answer7);
String a8 = ask.Question8(answer8);
String a9 = ask.Question9(answer9);
String a10 = ask.Question10(answer10);
For the Questions methods, I'll put two blank examples on here.
{public int Question1 (int answer1)
{String message = "";
int smallestValue = 1;
int largestValue = 4;
System.out.println("Q1) What is...?");
System.out.println("1: ....");
System.out.println("2: ......");
System.out.println("3: ......");
System.out.println("4: ......");
System.out.print("Enter the number");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer1 = input2.getIntValueFromUserBetween(message, smallestValue, largestValue);
return answer1;
}
public String Question6(boolean answer10)
{String message = "";
System.out.println("(Q10) ....(true/false)");
System.out.print("Enter your answer here: ");
Scanner input = new Scanner(System.in);
UserInteraction input2 = new UserInteraction();
answer10 = input2.confirm(message);
return "" + answer10;
}
}
Sorry if I misunderstand your question, but I don't understand why you're using a loop here.
while (a1==3)
Your program is either going to get stuck here or never use it. What I mean is that if the user answers the question correctly (i.e 3), they will be stuck in the while loop until you set a1 != 3.
What I think is a better solution is using selection. For example:
if (a1 == 3) {
point += 1; // point = point + 1
// Or whatever functionality you need here
}
Edit: If you really must use a loop, then having a Boolean flag would be the way to go. For example:
Boolean flag = false;
if (a1 == 3) {
flag = true;
while (flag) {
point += 1; //point = point + 1
// Make sure that you set flag equals to false at the end of the loop though, otherwise it will infinitely loop
// Include any other functionality needed
flag = false;
}
}
Is this similar to what your looking for?
int correct;
public void quiz() { // this is so you can restart quiz easily
String[] answers = String[5];
//add answers to array, set them to variables/constant first then index
String[] questions = String[5];
// add questions to array
for(int i = 0; i <= questions.length; i++) { // stops after all questions have been asked, make sure its "<="
System.out.println(questions[i]); // prints question 1 first loop then 2 and so on
// read input from user
if(input == answers[i]) { // you may have to convert input to correct type
correct += 1;
}
}
}
System.out.println("You got " + correct + " correct answers");
System.out.println("Would you like to play again?");
if(input == yes) {
quiz(); //starts quiz again // starts quiz method again
P.S. sorry if I've misunderstood the question
To ask different questions you can just change the String variables then call quiz() to ask those questions. nice and simple :)

Creating a random output from an user input array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.

Not able to take user input when using while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this code bellow which is supposed to take a user input and store it in an array, and I was just wondering why it is not allowing me to input any numbers.
Should the input part be inside the if statement? Also what is the best way to make it work properly?
import java.util.*;
public class fun_with_loops {
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
int numberSize = 0;
System.out.print("Enter a few numbers please\n");
while (numbers.length < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
}
}
Problem
The following expression on loop's control is always evaluated as false:
while (numbers.length < 10)
since array's length is in fact equals 10 as when declared.
Solution
In order to program work as expected you have to use numberSize variable as control:
while (numberSize < 10)
since it grows based on number of inputs.
As Am_I_Helpful stated, you are using a while loop on a value that will not change. I am not sure if the use while is needed in this case. Since you want to loop a specific amount of times you might want to use a for loop. If the amount of times will depend on the size of your array, you could still replace the "10" by your array length (numbers.length).
for (int i; i< 10; i++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[numberSize] = input;
numberSize++;
}
else
{
break;
}
}
Hoping it helped!
Dan
a short and sweet summary of when to use each loop:
http://mathbits.com/MathBits/CompSci/looping/whichloop.htm
but of course it always depends of your goal while coding so it's sometimes hard to say which is best if you are not the one coding.
Because the array is initialized to size 10, the length will always be 10. A counter variable needs to be used. Here is the code:
static Scanner scan = new Scanner(System.in);
public static void main (String[] args) throws java.io.IOException
{
int[] numbers = new int[10];
System.out.print("Enter a few numbers please\n");
int count = 0;
while (count < 10)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[count] = input;
count++;
}
else
{
break;
}
}
The length property returns the size of the array, not the number of elements that are present in the array. You need to keep track of number of elements in the array on your own.
for(int eleCount = 0; eleCount < 10; eleCount++)
{
int input = scan.nextInt();
if (input != 0)
{
numbers[eleCount] = input;
}
else
{
break;
}
}

Accessing a variable from inside a do-while loop [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
How can I access a variable from inside a do-while loop in Java?
The code below writes out a value until the value entered is not is between 0 and 10.
Here is my code :
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int total +=0;
}while (a>0 && a<10);
System.out.println("Loop Terminated");
System.out.println("The total is : "+total);
}
}
The loop continues to ask for input so long as the input is between 0 and 10. Once some other number is entered the loop terminates and displays the total of all inputted numbers.
try like (declare the variable a outside the loop):
int a = -1;
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
}while (a>0 && a<10);
To access a variable beyond the loop, you need to declare/initialize it outside of the loop and then change it inside the loop. If the variable in question wasn't an int, I would suggest that you initialize it to null. However, since you can't initialize an int variable to null, you'll have to initialize it to some random value:
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
int a = 0; //create it here
do {
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
} while (a>0 && a<10);
System.out.println("Loop Terminated");
// do something with a
}
}
NOTE: If you simply declare the variable before the loop without initializing it (as per #Evginy's answer), you'll be able to access it outside the loop but your compiler will complain that it might not have been initialized.
try this
Scanner in = new Scanner(System.in);
int a;
do {
System.out.println("Enter a number between 0 an 10");
a = in.nextInt();
} while (a > 0 && a < 10);
System.out.println("Loop Terminated");

Categories