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);
}
Related
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).
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);
}
}
}
}
public class ArrayMethodsTest
{
public static void main(String[] args)
{
int[] tester = {0,1,2,3,4,5};
ArrayMethods test = new ArrayMethods(tester);
for(int element : test)
{
System.out.print(element + " ");
}
test.shiftRight();
for(int element : test) //error: for-each not applicable to expression type
{
System.out.print(element + " ");
}
}
}
I figure what the problem is. Thanks to jigar joshi. However I still need to use the ArrayMethods methods for the tester that I created. I know that they work but how can it be possible to provide a tester class for an object that isn't an array since the methods are for arrays.
public class ArrayMethods
{
public int[] values;
public ArrayMethods(int[] initialValues)
{
values = initialValues;
}
public void swapFirstAndLast()
{
int first = values[0];
values[0] = values[values.length-1];
values[values.length-1] = first;
}
public void shiftRight()
{
int first = 0;
int second = first;
for(int i =0; i < values.length; i++)
{
if(i < values.length-1)
{
first = values[i];
second = values[i+1];
values[i+ 1] = first;
}
if(i == values.length)
{
values[i] = values[0];
}
}
}
}
//0,1,2,3,4,5
//5,0,1,2,3,4
test is reference of ArrayMethods which is not an Iterable or an array type and so is the error
You've already encountered the issue in which you can't iterate over an ArrayMethods, since it's not iterable. What it seems like you want to do is iterate over its values instead, considering that values is a public field.
for(int element : test.values) {
System.out.print(element + " ");
}
this is what I have so far
public class RandomCharacter
{
public static char getRandomUpperCaseLetter()
{
int ascii = (int) (Math.random()*26) + (int) 'A';
return (char)ascii;
}
public static char getRandomDigitCharacter()
{
int digit = (int)(Math.random()*10) + (int) '0';
return (char)digit;
}
public static void main(String [] args)
{
for (int i = 1; i <= 100; i++)
{
System.out.print(getRandomUpperCaseLetter());
if(i%10 == 0)
System.out.print("\n");
}
}
}
I have no clue how to specifically order this alphabetically, I have tried for hours but could not find anything for this. Would someone be able to use my code to teach me how this works?
To sort the values, you must first store them in some data structure eg.an array list before sorting them. Then , if you have used a sortable collection such as the array list, you can use the .sort() method and the list will be sorted automatically.
eg/ref:
http://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/
For natural ordering you can just add the generated alphabets in string and call Collections.sort(listVariable) . This should answer your question.
Sample program
import java.util.*;
public class Details {
public static void main(String args[]){
ArrayList<String> listofcountries = new ArrayList<String>();
listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");
/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
/* Sort statement*/
Collections.sort(listofcountries);
/* Sorted List*/
System.out.println("After Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
}
}
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.