1.Output: print remainder when sum is divided by max element.
2.Constraints: 1<=n<=100;
0<=A[i]<=1000
I need this code to validate array elements as such:
pseudocode:
if (arr_elmt>=0 and arr_elmt<=1000) ->Then execute succeeding commands.
else ->stop program, even though other elements obey constraint
3.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
int i=0;
for(i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(i=0;i<A.length;i++)
{ //Second constraint
if(A[i]>=0 && A[i]<=1000)
{
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(i=0;i<A.length;i++)//i=1 can work
{
if(A[i]>largest)
{
largest=A[i];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.print("\n"+ rem);
}
}
}
}
}
e.g: input: 3;
Values: 2988 67 5.
I expect an error due to 2988>1000, but the code
still runs and gives me output! output obtained:(2988+67+5)mod(2988)
Hi so your problem is that you do not specified that program should stop (or do whatever you want) when find number which does not match your second constraint.
So right now when does not match second constraint for 2688 it keeps iterating to second item and keep executing rest of your code.
So to make your program end when second constraint is not match you should add something like this
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
for(int i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(int i=0;i<A.length;i++)
{ //Second constraint loop through all elements of A[]
// if one of it does not obey constraint exit the program
if(A[i]<=0 || A[i]>=1000) // notice here I change '>'
{
System.exit(0); // this else is attached to your second constraint
}
}
for(int i = 0; i < A.length; i++){
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(int j=0;j<A.length;j++)//i=1 can work
{
if(A[j]>largest)
{
largest=A[j];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.println(rem);
}
}
}
}
Related
Learning about Arrays. I am not able to figure out why a new number is not added to the back of my existing array. I read in two textfiles in file_1.txt are the numbers '1 2 3' and in file_2.txt is the number '91'. Basically without the method of Void addBack() the program does what I expect, however by adding the method it seems not make a new Array. Even when I go over the elements[i] = elements[i-1] it won't print it as a whole. I am expecting to print for the first part
The numbers are: 1 2 3 and the second part The numbers are: 1 2 3 91.
public class ExampleLecture {
IntRow readIntRow(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.add(input.nextInt());
}
return result;
}
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while(input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
void print(IntRow row) {
for (int i = 0; i < row.numberOfElements; i++) {
System.out.printf("%d ", row.elements[i]);
}
System.out.printf("\n");
}
void start() {
Scanner in = UIAuxiliaryMethods.askUserForInput().getScanner();
Scanner in2 =UIAuxiliaryMethods.askUserForInput().getScanner();
IntRow row = readIntRow(in);
IntRow row2 = setBack(in2);
System.out.printf("the numbers are: ");
print (row);
System.out.printf("the new numbers are: ");
print (row2);
}
public static void main(String[] args) {
new ExampleLecture().start();
}
}
package examplelecture;
class IntRow {
static final int MAX_NUMBER_OF_ELEMENTS = 250;
int[] elements;
int numberOfElements;
IntRow() {
elements = new int[MAX_NUMBER_OF_ELEMENTS];
numberOfElements = 0;
}
void add(int number) {
elements[numberOfElements] = number;
numberOfElements += 1;
}
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
elements[i] = number;
}
}
}
You have 2 successive assignments which write to the same position:
elements[i] = elements[i-1];
elements[i] = number;
The value is alway overwritten with number, so the first statement has no effect.
Also in your addBack method your for cycle:
for (int i = numberOfElements; i>0; i--) {
What happens if numberOfElements is 0?
You call it addBack but it looks like a better name for the method is addFirst. Usually index 0 is considered the front, not the back.
First off, both the readIntRow() and setBack() methods create new IntRow objects row and row2. If you want the result to be appended to the first IntRow object created i.e. to row , you should call:
IntRow row = readIntRow(in);
IntRow row2 = row.setBack(in2);
and setBack() needs to be modified to:
IntRow setBack(Scanner input) {
while(input.hasNext()) {
this.add(input.nextInt());
System.out.println("here");
}
return this;
}
Note that in setBack(), if you are trying to append numbers to the end of the IntRow object, you should call add() instead of addBack() as above. If you are trying to add to the front, you should call addBack() [and it might be better to call it addFront() instead].
Also, in the implementation of addBack(), if you are trying to add to the front of the IntRow object, the element[i] = number operation should take place only once, after the loop. Otherwise all the values in indices <= numberOfElements would be overwritten with number.
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
}
elements[0] = number;
}
Admittedly it is not entirely clear what you are trying to accomplish. But you may have several problems. The first is as follows:
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
IntRow has nothing in it since it is new. So all you are doing is iterating over the new file which has just 91 in it. Remember, result has no items. So it won't even iterate once in addBack.
So just do the following:
Change your addBack method to just add the numbers. Why use a loop to cascade down the elements since you are doing this within the same instance of IntRow? Just add it on to the end using the numberofElements as the next index.
void addBack(int number) {
elements[numberOfElements++] = number;
}
If you want to copy the contents of one IntRow object to another you would need another method in the IntRow class. Something like:
public void copy(IntRow r) {
for (int i = 0; i < r.numerOfElements; i++) {
elements[i] = r.elements[i];
}
numerOfElements = r.numberOfElements;
}
And keeping with good design it might be better to return numberOfElements in a method such as public int size();
I just want to write a program that sorts 3 integers. The integers are entered from the input dialog. My code is really simple. I just need to get some data and put them in array called num. and then I create a method to sort the data by using bubble-sort logic. that method called sort. I have added command to display the sorted result with System.out.println("Sorted Result : "+Arrays.toString(num)) but that's not working.
The output just let me input data and then nothing happen.
Can anyone please tell me something I miss or what I did wrong?
Thank you.
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
for(int i=0;i<=num.length-1;i++){
for(int j=0;j<=num.length-i;j++){
if(num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
}
I believe you need a boolean flag to implement a bubble sort as you cannot know in advance how many times the loop will perform the swapping of consecutive elements.
Try this:
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
boolean swapped = true;
while(swapped){
swapped = false;
for(int i=0;i<num.length-1;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
Note that it can still be slightly improved: each time around the loop the largest number will end up as far as it can get towards the end of of the array: there's no need to check or swap till the end each time.
By using a variable as the upper limit of the index i and decreasing its value after the for loop you can reduce the total number of iterations.
int end = num.length-1;
while(swapped){
swapped = false;
for(int i=0;i<end;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
end--;
}
I'm trying to swap an array in ascending order but somewhere I'm going wrong. I'm taking input using
int n = Integer.parse.int(args[0]);
but it isn't working. Below is the full code.
package tech;
import java.util.*;
import java.io.*;
public class Techgig {
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Amount Mark has:");
int rs=50;//Integer.parseInt(args[0]);
//int a=0;
System.out.println(rs);
// for(int k=0;k<ta.length;k++)
//System.out.print("\t"+ ta);
int min,temp;
for(int i=0;i<ta.length;i++)
{
min=i;
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
for(int k=0;k<ta.length;k++)
{
System.out.print("\t"+ ta[k]);
}
}
}
You should replace variable i with j here:
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
Reason is you are comparing 'i'th index with itself which you assigned to min variable and hence it will never go in your if condition to swap.
You could resolve this as below by using i and j as index and checking between the two:
for(int i=0;i<ta.length;i++)
{
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[j]<ta[i])
{
temp=ta[j];
ta[j]=ta[i];
ta[i]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
Your logic of comparison is wrong.
Refer to the below code. Instead of applying so much logic. Why not just call upon sort method like below?
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
// print all the elements available in array
for (int number : ta) {
System.out.println("Number = " + number);
}
// sorting array
Arrays.sort(ta);
System.out.println("The sorted int array is:");
for (int number : ta) {
System.out.println("Number = " + number);
}
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.
My assignment was to write a Java class that creates an array of integers, fills it with values, prints the unsorted values, sorts the values into ascending order, and finally prints the sorted values.
For the most part I have done that and my output is fine. However I have not been able to define the array locally within the main(), and pass it as a parameter to the other methods.
I try to define it as a static member of the class which cannot be done.
Can anyone help me out? I need to define the array in the main() and pass it as a parameter to the methods. But I just cannot figure it out despite tireless research.
Here is what I have so far.
public class ArraySort {
private static Object sc;
int[] array;
// creates question and int for user input
/**
*
*/
public void fillArray() {
Scanner keyboardScanner = new Scanner(System.in);
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
array = new int[n];
// creates new question by including int
System.out.println("Enter " + n + " values" );
// creates for loop for repeating question based on array size
for (int i=0; i<n; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg) {
System.out.println(msg);
for (int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
}
// defines method
public void sortArray() {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
ArraySort arraySort = new ArraySort();
arraySort.fillArray();
System.out.println();
arraySort.printArray("The unsorted values... ");
arraySort.sortArray();
System.out.println();
arraySort.printArray("The sorted values... ");
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
I have no errors, I just need help on how to define the array locally in the main()
Thanks.
Remove the int[] array; declaration from the class. Add it to the main method:
int[] array = new int[n];
And add an argument int[] array to each method which needs to access it. For example:
public void printArray(String msg, int[] array) {
...
}
You can declare your array locally in your main method. And pass it as a parameter to the method you are calling.
Since when you pass array as parameter to another method, its reference will be copied to the parameter. So any change you make to passed array in your method, will get reflected back in your main() method in your original array. Try using this. I don't think you will face any problem.
UPDATE: - Ok, here's the modified code: -
import java.util.Scanner;
public class ArraySort {
private static Object sc;
private static Scanner keyboardScanner = new Scanner(System.in);
// creates question and int for user input
/**
*
*/
public void fillArray(int[] array) {
// creates for loop for repeating question based on array size
for (int i=0; i<array.length; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] array) {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
int[] array = new int[n];
ArraySort arraySort = new ArraySort();
arraySort.fillArray(array);
System.out.println();
//I still get an error saying " cannot find symbol"
arraySort.printArray("The unsorted values... ", array);
//same here
arraySort.sortArray(array);
System.out.println();
//and here
arraySort.printArray("The sorted values... ", array);
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
Update public void printArray(String msg) { and public void sortArray() { to accept int [] as
/ prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] argsArray) {
// sets up to output in ascending order
for (int i=0; i<argsArray.length; i++) {
for (int j=i+1; j<argsArray.length; j++) {
if (argsArray[i] > argsArray[j]) {
int temp = argsArray[i];
argsArray[i] = argsArray[j];
argsArray[j] = temp;
}
}
}
}
And you may want to leave array = new int[n]; in fillArray as local as:
int[] array = new int[n];
and remove it from class variable declaration.
You've said that you need to define the array in the main() and pass it as a parameter to the methods. If so, then you'll need to change those methods, e.g.:
public void printArray(String msg, int[] argsArray)
public void sortArray(int[] array)
fillArray is different, because you create the array in the method based on a size which is input by the user, so you can't simply pass the array as an argument. You can return the new array:
public int[] fillArray()
{
int[] array;
// ...
return array;
}
But if you're only trying to test your class then note that you have access to the ArraySort.array field from main: you can set the field to an array that you create in main.
So in main:
ArraySort arraySort = new ArraySort();
arraySort.array = new int[]{ 5, 4, 3, 6, 7};
// and remove the fillArray call
// ...
Note that if you want to set the array like this, then you should also remove the fillArray call, which tries to set the array from user-entered values.