Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}
public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}
i can't call a method with variable that is declared in a code block. (like in my case a if statement in a for loop)
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int input;
System.out.println("Enter 5 integers");
for (int i = 0; i <= 4; i++) {
input = scanner.nextInt();
arrayList.add(input);
}
isSorted(arrayList);
}
public static void isSorted(ArrayList<Integer> arrayList) {
boolean sorted;
boolean dSorted;
for (int i=0; i<=3; i++) {
if (arrayList.get((i+1)) > arrayList.get(i)) {
sorted = true;
} else if (arrayList.get((i+1)) < arrayList.get(i)) {
dSorted = true;
} else {
sorted = false;
}
}
printResult(sorted, dSorted);
}
public static void printResult(boolean sorted, boolean dSorted) {
if(sorted) {
System.out.println("This set of numbers is sorted in ascending order.");
} else if(dSorted) {
System.out.println("This set of numbers is sorted in descending order.");
} else {
System.out.println("This set of numbers is not sorted at all.");
}
}
}
compile error:
something like error:(33,21) java: variable sorted might not have been intialized
you should just initialize variable : sorted and dsorted
The problem is, that you can not guarantee that both variables are getting initialized in the loop. It depends on the list that is passed to the method.
Therefore you have to initialize those variables (probably false).
// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length
public class Jeux {
public static void main(String [] args) {
int nPlayer= 0;
String name;
boolean ok = false;
Player[] groupe = null;
do {
try {
System.out.print("How many player: ");
nPlayer= Clavier.lireInt();
ok = true;
} catch(NumberFormatException e) {
System.out.println("ERROR, enter a number");
}
} while(!ok);
groupe = new Player[nPlayer];
System.out.println(groupe.length);
for(int i=0; i<groupe.length; i++){
try{
System.out.print("Enter the name of the player " + (i + 1));
name = Clavier.lireString();
groupe[i].setNom(name);
} catch(NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
}
why can't I set the name for groupe[i] --> groupe[i].setNom(nom);. I get an exception.
I try to create multiple object without knowing the length of the array.
Maybe there's other possibility with array list and other method but im in school and we didn't see other method for the moment.
You need to instantiate each Player object in addition to instantiating the array which holds them:
name = Clavier.lireString();
groupe[i] = new Player(); // replace this with actual constructor
groupe[i].setNom(name);
Your code is catching a NullPointerException which is precisely what I would expect from your current code.
Hi i am writing a lottery method where the user has to enter in two numbers, n and k, as arguments. The lottery gets filled with a randomized queue that goes up to k. so if i put in k=10 the queue would hold 1,2,3,4,5,6,7,8,9,10. The argument n is the number of items that has to be removed randomly. so if i chose 3 then it could return 4,6,8 or it could be 1,3,10.
Now if n is greater than k it has to throw an error saying that there is not enough items in the queue to pull. So if i put n=5 and k=3, there are still 3 items in the queue but i can't select 5 from the queue because that's too many.
Now my problem is i have to return the items that are still in the queue. so n=5 and k=3 would return 1,3,2 or 2,3,1 and so forth. But i have to print an exception after i return that array. So far i am able to return the array but i can not get the try catch exception to work. Is there another method i can try that will return the array and then print out the exception after that so it looks like this:
%java Lottery 5 2 //calls the method with the arguments n=5 k=2
2 1 //still prints the items in the queue
java.lang.Exception: Not enough items in your queue. // returns the error as well
at Lottery.pickNumbers(Lottery.java:29) //dont pay attention to these line numbers, this was a test case given to us
at Lottery.main(Lottery.java:56)
Here's my code:
import java.util.*;
import java.math.*;
public class Lottery{
RandomizedQueue rq;
Random Rnum = new Random();
int [] Larray;
// constructs a Lottery class
public Lottery(){
}
// picks the numbers and store them in an array of integers
// int n: number of items to pick
// int k: maximum integer to be picked
public int [] pickNumbers(int n, int k) throws Exception{
rq = new RandomizedQueue();
int [] remainQueue = new int [k];
if(n>k)
{
for(int i=1; i<=remainQueue.length;i++)
{
rq.enqueue(i);
}
for(int i=0; i<remainQueue.length;i++)
{
remainQueue[i] = rq.dequeue();
}
return remainQueue;
}
for(int i =1;i<=k;i++)
{
rq.enqueue(i);
}
Larray = new int[n];
for(int i = 0;i< Larray.length;i++)
{
Larray[i] = rq.dequeue();
}
return Larray;
}
// Do not change main().
public static void main(String [] args) throws Exception{
if (args.length<2){
System.out.println("Please enter your input values.");
System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]");
}else{
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
Lottery l = new Lottery();
try{
int [] picked = l.pickNumbers(n,k);
for (int i = 0; i< picked.length; i++){
System.out.print(picked[i]+" ");
}
System.out.println();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
For this purpose you need to create your own custom Exception.
Follow the Steps.
-> Create an class that Extends Exception
-> write your own exceptions and handling
Say,
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
Here in your case
if(n
Change your main method like below code. In case of no exception you will get Result as expected in case of exception jut get previously populated Array and display that. In this way you will get populated result as well as exception both.
import java.util.*;
import java.math.*;
public class Lottery{
RandomizedQueue rq;
Random Rnum = new Random();
int [] Larray;
// constructs a Lottery class
public Lottery(){
}
// picks the numbers and store them in an array of integers
// int n: number of items to pick
// int k: maximum integer to be picked
public int [] pickNumbers(int n, int k) throws Exception{
rq = new RandomizedQueue();
int [] remainQueue = new int [k];
if(n>k)
{
for(int i=1; i<=remainQueue.length;i++)
{
rq.enqueue(i);
}
for(int i=0; i<remainQueue.length;i++)
{
remainQueue[i] = rq.dequeue();
}
return remainQueue;
}
for(int i =1;i<=k;i++)
{
rq.enqueue(i);
}
Larray = new int[n];
for(int i = 0;i< Larray.length;i++)
{
Larray[i] = rq.dequeue();
}
return Larray;
}
// Do not change main().
public static void main(String [] args) throws Exception{
if (args.length<2){
System.out.println("Please enter your input values.");
System.out.println("e.g. java Lottery [number of integers to pick] [Maximum integer to be picked]");
}else{
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
Lottery l = new Lottery();
try{
int [] picked = l.pickNumbers(n,k);
for (int i = 0; i< picked.length; i++){
System.out.print(picked[i]+" ");
}
System.out.println();
}catch (Exception e){
int [] picked = l.Larray;
for (int i = 0; i< picked.length; i++){
System.out.print(picked[i]+" ");
}
System.out.println();
e.printStackTrace();
}
}
}
}
You can't. Doing it doesn't even make sense. Exceptions are used for Exceptional behaviour. From what I understand asking for more items than is in the queue, is expected behaviour (ie. You have a use case which says "return the remaining queue". Thus if you want to handle the error, you should simply do something like.
if (picked.length != k)
{
System.out.println("You are attempting to choose more numbers than there are items (left) in the pool");
}
Alternatively since you know up front the values n and K you could simply do some input validation
if (k>n)
{
System.out.println("The amount of available numbers is smaller than the amount of numbers you wish to draw.")
}
Also you should probably use a Set instead of an Array.
This is how I would do it. Complete working code:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Lottery {
public void pickNumbers (int n, int k, List<Integer> values)
throws Exception
{
RandomizedQueue <Integer> rq = new RandomizedQueue <Integer> ();
for (int i = 0; i < k; i++)
rq.enqueue (i);
if (n <= k)
{
for (int i = 0; i < n; i++)
values.add (rq.dequeue ());
}
else
{
for (int i = 0; i < k; i++)
values.add (rq.dequeue ());
throw new Exception ("N > K");
}
}
public static void main (String [] args)
{
int n = Integer.parseInt (args [0]);
int k = Integer.parseInt (args [1]);
Lottery l = new Lottery ();
List <Integer> picked = new ArrayList <Integer> (n);
try
{
l.pickNumbers (n, k, picked);
}
catch (Exception e)
{
e.printStackTrace();
}
for (int i = 0; i < picked.size (); i++){
System.out.print (picked.get (i) + " ");
}
System.out.println();
}
private static class RandomizedQueue <T> extends ArrayList <T>
{
private final Random r = new Random ();
public void enqueue (T x)
{
add (x);
}
public T dequeue ()
{
return remove (r.nextInt(size ()));
}
}
}
Try this approach:
Create a list in main()
Pass that list to pickNumbers()
Make pickNumbers() return void and add the results to the list instead.
When you run into an error, throw the exception
In main(), catch the exception. The list will then contain all the results that have been computed so far.
Alternatively, write your own exception which accepts the existing results as arguments. main() can then read them from the exception.
You can either return value of throw Exception from a method, both can not be done at once.
You can create custom Exception class and where you can keep your processed result and throw that if exception arise.
public class MyException extends Exception{
private int[] processedResult;
public MyException(String str,int[] result){
this.processedResult = result;
}
...
#override
public String toString(){
....
}
}
...
public int [] pickNumbers(int n, int k) throws MyException{
int[] larray = new int[n];
try{
...
}catch(Exception ex){
new MyException("...",larray );
}
}
You can create your own Exception type which overrides setMessage
or simple instead of e.printStackTrace() use e.getMessage()
You can't both throw an exception and return a value at the same time.
Take a step back and look at what you are trying to achieve. You need to return multiple values from your method - a list of numbers and a status - which would suggest to me returning a complex object containing these values instead of a plain int[]:
public class LotteryPick {
public int status;
public int[] numbers;
}
public LotteryPick pickNumbers(int n, int k) {
...
}
In reality I'd use a Set<Integer> for numbers, an enum for status, and probably getter/setters for the fields.
Alternatively, if you must throw an exception, create a custom exception class (... extends IllegalArgumentException ?) that also has an int[] field to hold the picked numbers. I wouldn't recommend this approach though and it's functionally equivalent to the above in any case.