How to override the array? - java

I am writing a game where a user has to input 5 numbers ranging from 1 to 50. These numbers are being saved in the array intPlayersNumbers. If the conditions are not met the user has to enter the numbers again. Why is the array intPlayersNumbers not being overwritten? It is saving only the numbers that were entered for the 1st time.
public class Game {
int chosenNumbers = 5;
int chosenNumber;
String numbers;
int[] raffleArray = new int[chosenNumbers];
public void askForNumbers(){
Scanner in = new Scanner(System.in);
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
int[] intPlayersNumbers = new int[playersNumbers.length];
for(int a =0; a<playersNumbers.length; a++ ){
intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
}
//checking the numbers
checkTheNumbers(intPlayersNumbers);
}
public int[] checkTheNumbers(int[] intPlayersNumbers){
//if there is 5 numbers
if(intPlayersNumbers.length==5){
//if the numbers are form 1 to 50
for(int i = 0; i<intPlayersNumbers.length; i++){
if(intPlayersNumbers[i]<50 && intPlayersNumbers[i]>0){
continue;
}else{
System.out.println("Please enter 5 nums from 1 to 50.");
askForNumbers();
}
}
}
else{
System.out.println("Please enter 5 numbers");
askForNumbers();
}
return intPlayersNumbers;
}

I think a do-while makes more sense here. Additionally, I think it makes more sense that checkTheNumbers returns a boolean as it performs a validation. The solution below will continuously ask for numbers until checkTheNumbers returns true.
public int[] askForNumbers(){
int[] intPlayersNumbers;
Scanner in = new Scanner(System.in);
do {
System.out.println("Please enter 5 nums from 1 to 50.");
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
intPlayersNumbers = new int[playersNumbers.length];
for(int a =0; a<playersNumbers.length; a++ ){
intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
}
} while (!checkTheNumbers(intPlayersNumbers));
return intPlayersNumbers;
}
public boolean checkTheNumbers(int[] intPlayersNumbers) {
if(intPlayersNumbers.length==5) {
for(int i = 0; i < intPlayersNumbers.length; i++) {
if (intPlayersNumbers[i] > 50 || intPlayersNumbers[i] <= 0) {
System.out.println("Please enter 5 nums from 1 to 50.");
return false;
}
}
} else{
System.out.println("Please enter 5 numbers");
return false;
}
return true;
}

I think you can easily solve this using recursion. Since the context of your question is not completely clear i did one or two assumptions. If you want a slightly different solution you can use the comments as hints.
public void askForNumbers() {
Scanner in = new Scanner(System.in);
// use the sout before the system.in waits for you first input
System.out.println("Please enter 5 nums from 1 to 50.");
numbers = in.nextLine();
String[] playersNumbers = (numbers.split(" "));
int[] intPlayersNumbers = new int[playersNumbers.length];
// check if the array has lenght 5 directly after the split.
if (intPlayersNumbers.length != 5) { // if the split.length != 5 start over
askForNumbers();
}
else {
for (int a = 0; a < playersNumbers.length; a++) {
int i = Integer.parseInt(playersNumbers[a]); //beware this can cause a numberFormatException !!!
if (i > 0 && i < 51) { // if one of the number is not in range start over.
intPlayersNumbers[a] = i;
}
else {
System.out.printf("%d was not between 0 and 50", i); // print which integer was the culprit
askForNumbers();
return; //return so this method ends here;
}
}
raffleArray = intPlayersNumbers; // or return intPlayersNumbers , you will have to change the return type of the method as well
}
}
I you have any questions about this solution, just leave a comment.

Related

Else statement not printing, wondering if I am calling from setter method incorrectly in java

I'm trying to make a program in java which creates an array. I am trying to have OOP approach. I've made a class file which contains a setter method and my array:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
The elements of the array is taken from the user in my main method:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
int num;
while(choice !=6){
switch (choice){
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((a < 2) || (a > 12)){
System.out.println("Please enter an amount between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
else{myMonths[index++] = a;}
}
calc.setMyMonths(myMonths); //creating the object
break;
I am trying to create a function which displays all the elements of the array. If the array is empty I want it to display a message stating this. However, my else statement will not run. I am trying to figure out why this is & am I calling the array incorrectly? Please see my code below:
case 2:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
Any help would be great! Thanks in advance
Your code :
for(int i=0; i < myMonths.length; i++){
if(myMonths.length != 0){ //if the array is not empty display all items
System.out.println(myMonths[i] + " ");
}
else{System.out.println("No values entered");} //if array is empty display this message
}
if myMonths.length > 0 then it will check for length !!
your code should be:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
UPDATE:
before you create your Array .. Ask the User for Size,
then you can check if empty or not
System.out.println("inter the size:");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] arr = new int[size];
if (arr.length > 0) {
// do your loop
System.out.println("Not Empty");
} else {
// Empty array
System.out.println("Empty");
}

Having trouble processing an int input to a boolean array

In my program, I'm asking the user to input multiple integers to represent the inclusion of chapters in a book like "1 0 1 0 0 1" to represent read chapters 1, 3, 6 or "1 1 1 0 1" to represent 1-3, 5. I' not sure how to process that kind of input into a boolean array and then print the statement.
This is the code I have so far:
import java.util.Scanner;
public class WhichChaptersToRead {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int chapters = -1;
String chapterOut = " ";
boolean[] chpSelect = new boolean[15];
boolean rightInput = false;
System.out.println("Enter the chapters to read: ");
while(!rightInput){
if(keyboard.hasNextInt()){
chapters = keyboard.nextInt();
if(chapters > 1 || chapters < 0){
System.out.println("Out of scope of the inclusion or exclusion of chapters");
System.out.println("Enter either 0 or 1");
}else{
chapterOut = formatChapter(chapters, chpSelect);
}
}else{
System.out.println("Wrong type of input.");
System.out.println("Enter integers 0 or 1");
}
}
}
public static String formatChapter(int chapters, boolean[] chpSelect){
}
}
Thanks for all the help.
I reimplemented your logic. Sorry, I couldn't think of an easier way to do it. There are of course, multiple ways to solve this problem.
Step one, ask for the chapters to read.
Step two replace everything that is not zero or one with nothing (that is only allow 0 and 1 - don't validate).
Step three create a boolean[] to store the zero and one values into boolean[] (which is what you asked for).
Step four keep count of how many chapters were assigned so we can use the correct plural for output.
Step five, use a StringJoiner to build the list of output chapters.
Like,
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the chapters to read: ");
String line = keyboard.nextLine();
line = line.replaceAll("[^01]", "");
int selectedCount = 0;
boolean[] selected = new boolean[line.length()];
for (int i = 0; i < line.length(); i++) {
selected[i] = line.charAt(i) == '1';
if (selected[i]) {
selectedCount++;
}
}
if (selectedCount == 0) {
System.out.println("There are no assigned chapters.");
return;
} else if (selectedCount == 1) {
System.out.print("Read chapter ");
} else {
System.out.print("Read chapters ");
}
StringJoiner sj = new StringJoiner(", ");
for (int i = 0; i < selected.length; i++) {
if (selected[i]) {
sj.add(String.valueOf(i + 1));
}
}
System.out.println(sj);

Checking whether a number is an Unique number or not

I have written a program to check if a number is an Unique number.
[A Unique number is a number with no repeating digits and no leading zeros.]
I have written the following code:
Scanner sc=new Scanner(System.in)
System.out.println("Enter the number to be checked: ");
String num=sc.nextLine();
if(num.charAt(0)!='0')
{
Outer:
for(int i=0;i<num.length();i++)
{
for(int j=0;j<num.length();j++)
{
if(num.charAt(i)==num.charAt(j))
{
System.out.println("No, "+num+" is not a Unique number.");
break Outer;
}
}
if(i==num.length()-1)
{
System.out.println("Yes, "+num+" is a Unique number.");
}
}
}
else
System.out.println("No, "+num+" is not a Unique number as it has leading zeros.");
The problem is that is shows any number as NOT Unique, even 12345.
I would like to know where I have gone wrong.
Your code will always find "duplicate" characters when i == j.
You should change the indices of the loop in order not to compare a character to itself:
for(int i=0;i<num.length();i++) {
for(int j=i+1;j<num.length();j++) {
if(num.charAt(i)==num.charAt(j))
...
Besides, you should only output the "...is a Unique number." message after you are done with the outer loop.
Lets assume , length of input number to be 10 and "i" has reached the value of 5 in the for loop.
Now "j" will have the values 0 to 9.
So when "j" is equal to 5 , the if condition becomes true as you are comparing the digit at 5th position with itself (which is always true).
If you add i != j condition , it will fix the issue :-
if(num.charAt(i)==num.charAt(j) and i != j)
Alternatively, you can modify the loop for j to start from i + 1 so
that there are no overlaps.
for(int j=i+1;j<num.length();j++)
The second option is much better as it will reduce the number of comparisons from (n*n)
to (n * (n - 1))/2) , where n is the number of digits in the input number.
A possible solution is to use Stream to convert your String in a Set of char, then if the size of the set is the same as the length of your string, it is unique:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked: ");
String num = sc.nextLine();
boolean unique = Stream.of(num.split(""))
.map(s -> new String(s))
.collect(Collectors.toSet()).size() == num.length();
// With "1234" -> print true
// With "12342" -> print false
System.out.println(unique);
You can use below short and handy approach:
String a = "123452";
String[] split = a.split("");
List<String> list = Arrays.asList(a.split(""));
Set<String> set = new HashSet<>(list);
System.out.println("Unique: " + (list.size() == set.size()));
import java.util.*;
public class spnum
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
String num = sc.next();
int ctr = 0;
boolean isNumUnique = true;
for(int i = 0; i < num.length(); i++)
{
for(int j = 0; j < num.length(); j++)
{
if(num.charAt(i) == num.charAt(j))
{
ctr++;
}
}
if(ctr > 1)
{
isNumUnique = false;
}
ctr = 0;
}
if(isNumUnique == true)
{
System.out.println("Number is a unique number");
}
else
{
System.out.println("Number is not a unique number");
}
}
}
this code would give the right answer

program that reads integers between 1 and 100 and counts the occurrence of each

Write a program that reads integers between
1 and 100 and counts the occurrence of each (you should store the numbers in an array). Output should be in ascending order. Assume the input ends when the user enters a 0.
Hi guys, I know that this question has been posted before, perhaps a lot of times, but as I am a complete beginner at java, I don't completely understand the complexity of the codes that are posted. I just started taking Java classes, and would appreciate if you could help me figure out how to get my program to output the correct occurrences at the end. I'm so close to getting the answer but I can't figure it out for the life of me!! Thanks in advance!
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
//declarations
int [] myArray = new int [100];
int input = 5;
Scanner keyboard = new Scanner(System.in);
//input and processing
System.out.println("Please enter integers between 1 and 100 (enter 0 to stop): ");
while (input != 0)
{
input = keyboard.nextInt();
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] = input;
}
}
}
//output (This is where I need help!!!!)
for (int k = 0; k < myArray.length; k++)
{
if (myArray[k] != 0)
{
System.out.print(k + " occurs " + myArray[k] + " time");
if (myArray[k] > 1)
{
System.out.println("s");
}
else
System.out.println("");
}
}
keyboard.close();
}
}
You are storing the number entered by the user in the array. Instead, you should store a counter in each position of the array for the corresponding integer. When the user inputs a number, you should increase the corresponding counter.
The second part of your code (output results) seems ok. It is the first one that needs fixing.
I think the first for loop should be something like this:
for (int i = 0; i < myArray.length; i++)
{
if (input == i)
{
myArray[i] += 1;
}
}
}
This should store add 1 to the array everytime the numbers occurs.
hey this my source code that worked out or me.
package test2;
import java.util.Arrays;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// ask for user to input numbers
System.out.println("Enter some integers between 1 and 100 (and 0 when done): ");
int[] myArray = new int[1000];//create a new array for user inputs
int number;//variable for user inputs
int count = 0;
do
{
number = input.nextInt();
myArray[count] = number;
count++;
}
while (number != 0);
int[] mySort = new int [count - 1]; //create a new array with only the numbers
for(int i = 0; i< (count-1); i++) { //get the array until 0th number into new
mySort[i] = myArray[i];
}
java.util.Arrays.sort(mySort);// sort the array in ascending order
int n = 0;
for(int i = 0; i < mySort.length; i++) {//check if the number have checked before
int occurance = 0;
if(n >= mySort[i]) {
continue;
}
else {
n = mySort[i];//if a new number found do the calculation+
for (int j=0; j<mySort.length; j++)
if (n == mySort[j])
occurance++;
System.out.print(n + " occurs " + occurance );
{
if (occurance == 1) {
System.out.println(" time.");
}
else {
System.out.println(" times.");
}
}
}
}
}
}

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

Categories

Resources