Aim is to get an array and arrange it accending, and print
package habeeb;
import java.util.*;
public class Habeeb {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int i, count=0, m;
System.out.println("Enter the integers, with 0 to end the array" );
for( i=0; i<num.length; i++){
num[i]= input.nextInt();
Zero breaks the array here
if(num[i]==0)
break;
count++;
Calling the function here\
}
Sorting(num, count);
The function sorting is here
}
public static void Sorting(int[] sort, int con){
if(con<0)
return;
int j, max=0, coun=0, temp;
for(j=0; j<con; j++){
if(sort[j]>max)
max=sort[j];
coun=j;
}
here am swaping the last value in the array for any index thats the highest
temp=sort[con];
sort[con]=sort[coun];
sort[coun]=temp;
Calling the function again here(recursive)
Sorting(sort, con-1);
Here am printing, why is it not printing
for(j=0; j<con; j++){
System.out.println(sort[j]);
}
}
}
Is there a reason not to use Arrays.sort() ?
All you have to do is call
Arrays.sort(num);
Be careful since this will modify your array and will not create a sorted coyp of it!
Related
My code will not compile and I can not figure out how to fix the error. It is a compile time run error I think. My error is in my method to print out array. Then, it says that there is something wrong with my closing bracket for the class. I am using a scanner class and I did import it, it is just not shown. Any help?
My code:
public static void main (String[] args){
int[] getArray; //reference to an int array of type and takes no parameters
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
int[] nums; //reference to nums array of type int
nums = new int[size]; /* new array of type int. assigned to nums.
size, to specify number of elements array will have */
for(int i=0; i<nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt(); //storing user input into array
return nums;
}//closing for loop
int[] minimumValue;
min = scan.nextInt();
min = nums[0]; //assigning min value to first element in array
return min;
for(int i=0; i<min.length; i++){
if(i<min){
min = nums[0];
}
}
return min;
public static void printArray (int[] getArray){ //method to print out array
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length); //print out array
}
}
public static void printArrayInReverse(int[] getArray){ //method for arrayInReverse
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
int[] numbers = getArray();// calling getArray method
public static void main (String[] args){
System.out.print("************");
printArray(numbers); //calling printArray method and passing numbers through it
printArrayInReverse(numbers);// calling printArrayInReverse method and passing numbers through it
System.out.print(minimumValue(numbers)); /* calling minVal through print statement and passing
numbers through it*/
}
}
}
It is very hard to tell what you are trying to accomplish here from your code. There is no class here which means your program will not even compile, please remember to post all applicable code to your question as it makes it easier for people to help you.
Firstly, you can only have one entry point (ie. main(String[] args) for each class. This is better explained here Can there exist two main methods in a Java program?.
Within this main method, you cannot have any other methods, you can only call other methods and perform operations ad such.
The variable "scan" cannot ever do anything if it is not instantiated prior to use. The variable getArray is being used as a method, which it is not.
Please take a look at Simple Java array program where it shows more in-depth how to use arrays.
Take a look at this as see if it even accomplishes what you want to do, which is still somewhat unclear. I shortened everything so that it is simpler, with a program this small multiple methods are not needed unless there is some logic to denote when to print the array or when to print the array reversed.
import java.util.Scanner;
public class CLASSNAME {
static Scanner scan = new Scanner(System.in);
static int[] nums;
public static void main(String[] args){
// Get Size Of Array
System.out.println("How many numbers would you like to enter?" );
int size = scan.nextInt();
nums = new int[size];
// Fill Array
for(int i = 0; i < nums.length; i++){
System.out.println("Enter a number." +(i+1)+ "left");
nums[i] = scan.nextInt();
}
// Set 0th Number To
System.out.println("Enter 0th Number");
int min = scan.nextInt();
nums[0] = min;
// Print Array
System.out.println("\n" + "Printing Array Index 0 -> ArraySize");
for(int i = 0; i < nums.length; i++){
System.out.print(nums.length);
}
// Print Array Reversed
System.out.println("\n" + "Printing Array Index ArraySize -> 0");
for(int i = nums.length - 1; i >= 0; i--){
System.out.print(nums[i]);
}
}
}
you need to create a Scanner object to use it
you can't create more than one main method
you must create methods outside the main method
Example:
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//code here
}
public static void method_name() {
//code here
}
//If you want to return integer value for example
public static int method_name() {
//code here
}
}
This is a program that takes these three arrays and sorts them using insertion sort and counting the number of comparisons and swaps performed for each array when sorted.
I'm now trying to test three other arrays that have been made on text files. The these three text files are just lists of numbers, the first text file is called "array4.txt" and its list of numbers contains 1 through 2000 in order.
The second file is called "array5.txt" and its list of numbers contains 2000 through 1 in descending order. Lastly, the third file is called "array6.txt" and its list of numbers contains a list of randomly mixed numbers from 1 to 2000, including 1 and 2000 with no repeats.
My goal is to read these files and put their values into an actual array and for my insertion sort method to read them, sort them, and count the number of comparisons and exchanges just as what I did with my first three arrays.
I'm very new to Java and don't know exactly how to do this.
import java.util.Scanner;
import java.io.*;
public class InsertionSort
{
public static void main(String args[]) throws IOException
{
int[] Array = {1,2,3,4,5,6,7,8,9,10};
int[] Array2 = {10,9,8,7,6,5,4,3,2,1};
int[] Array3 = {1,10,2,9,3,8,4,7,5,6};
System.out.println("Insertion Sort: ");
System.out.println();
System.out.println("Best Case Scenario: ");
printArray(Array);
insertionSort(Array);
System.out.println("Worst Case Scenario: ");
printArray(Array2);
insertionSort(Array2);
System.out.println("Average Case Scenario: ");
printArray(Array3);
insertionSort(Array3);
}
public static void insertionSort(int[] list)
{
int comps = 0, swaps = 0;
for(int i = 1; i < list .length; i++) {
int j = i;
// compare i with sorted elements and insert it
// sorted elements: [0..i-1]
while (j > 0 && list[j] < list[j - 1]) {
int temp = list[j];
list[j] = list[j - 1];
list[j - 1] = temp;
swaps++;
comps++; // loop condition true
j--;
}
comps++; // checking loop condition when false
}
//printArray(list);
System.out.println("Comparisons: " + comps
+ " Swaps: " + swaps);
System.out.println();
}
static void printArray(int[] array){
for(int i=0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
}
}
This is what I came up with. Hope it helps!
package com.company;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// Replace array.txt with the name of your txt file and your path
Scanner fileScanner = new Scanner(new File("array.txt"));
// Counter variable so we'll know the size of the array we'll need
int counter = 0;
// Iterate through the file counting the number of integers and incrementing the counter variable
while(fileScanner.hasNextInt()){
counter++;
fileScanner.nextInt();
}
// Reset the scanner to the beginning of the txt file
fileScanner = new Scanner(new File("array.txt"));
// Scan each integer into the array
int [] array = new int[counter];
for (int i = 0; i < array.length; ++i) array[i] = fileScanner.nextInt();
}
}
Here you go:
public void getIt() {
List<Integer> ints = new ArrayList(); //temporary holder
try (Scanner scanner = new Scanner("filename.txt")) { //open a scanner that will scan our file
scanner.forEachRemaining(line -> { //iterate through each line in our file
String[] numberStrings = line.split(","); // the comma is your presumed delimeter IF one exists
for (int x = 0; x < numberStrings.length; x++) { // loop through each item separated by a comma on each line
ints.add(Integer.parseInt(numberStrings[x])); // turn this string into an int and add it to your list
}
});
}
Integer[] integerArray = ints.toArray(new Integer[ints.size()]); //transform our list into an array
}
If it's only one number per line you don't need the for loop or the line.split inside of the forEachRemaining
so my program is supposed to access a text document then do all that jazz that currently works. The only problem that I can't figure out is how to shuffle the contents of an array without having them end up on top of each other. Both internets and multiple tries with random and for loops have been unfruitful. here is my code:
import java.io.*;
import java.util.*;
public class lab_6 {
public static void main(String[] args)throws FileNotFoundException {
Scanner input = new Scanner(System.in); //reads from keyboard
System.out.println("What is the name of your file. ");
String name = input.nextLine();
Scanner reader = new Scanner(new File(name));// Open text file
System.out.println("how many names are in your array");
int num = input.nextInt();
String[] names = new String[num];
for (int index = 0; index< names.length; index++)
{
names[index] = reader.nextLine();// Gets a line while there is one
}
System.out.println("\nOriginal List");
printList(names);
System.out.println("\nShuffled List");
shuffle(names);
printList(names);
System.out.println("\nSorted List");
Arrays.sort(names); // this is a built in method
printList(names);
System.out.println("What name are you looking for");
Scanner input1 = new Scanner(System.in); //reads from keyboard
String find = input1.nextLine();
int index = search(names,find);
if(index == -1)
System.out.println("The name was not there");
else
System.out.println(find+" was found at position "+index);
System.out.println("The average length of all the names is "+averageLength(names));
}
public static void printList(String[] array) // print the list of names numbered
{
for (int i=0; i<array.length; i++)
{
System.out.println((i+1)+") "+ array[i]);
}
}
public static void shuffle (String[] array) // mix-up the array
{
}
public static int search(String[] array, String find)
{
for(int i=0; i<array.length; i++) {
if (array[i].equals(find) ) return i;
}
return -1;
}
public static double averageLength(String[] array) //return the average length of the names
{
int sum=0;
for (int i=0; i<array.length; i++)
{
int l= array[i].length();
sum +=l;
}
int average = sum/(array.length);
return average;
}
}
String[] names = ...;
Collections.shuffle(Arrays.asList(names));
// done
Note that Arrays.asList() returns a modifiable (but fixed-length) list, backed by the array, and not a copy of the array. So the array will be shuffled.
Just use the Fisher-Yates shuffle (Knuth algorithm P):
private Random rand = new Random();
public static void shuffle(String[] array) { // mix-up the array
for (int i = array.length - 1; i > 0; --i) {
int j = rand.nextInt(i + 1);
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
See:
Knuth, D. 1969, 1998: Seminumerical Algorithms 1st & 3rd Eds. The Art of Computer Programming Series, Volume 2, p. 125.
Fisher, Ronald A.; Yates, Frank (1948) [1938]. Statistical tables for biological, agricultural and medical research (3rd ed.). London: Oliver & Boyd. pp. 26–27.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
https://stackoverflow.com/a/1520212/636009
You can use the Collections class, with the shuffle method. The documentation is available here.
Example
int[] values = {1,2,3,4,5};
List<Integer> valuesList = Arrays.asList(values);
Collections.shuffle(valuesList);
// valuesList is shuffled.
I know i can't pass arrays the way I'm doing it. Would I need to pass by reference if so how? The question is at the bottom for reference.
import java.util.Scanner;
public class MethodsArrays {
public static int[] fillArray() {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
int array[] = new int[size];
int pos=0;
for(int i=0; i<array.length; i++) {
pos=i+1;
System.out.println("Enter element " + pos);
array[i]=scan.nextInt();
}
return array;
}
public static int sumArray(int [] array) {
int sum=0;
for(int i=0; i<array.length-1; i++) {
sum=array[i]+array[i+1];
}
return sum;
}
public static int avgArray(int [] array) {
int avg=0;
int sum = sumArray(array);
avg = sumArray(array)/array.length-1;
return avg;
}
public static void printArray(int [] array) {
for(int i=0; i<array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
fillArray();
System.out.println("Sum=" + sumArray(array));
System.out.println("Average=" + avgArray(array));
printArray(array);
}
}
Write a Java program, called MethodsArrays that has 4 static methods
called fillArray(), sumArray(), avgArray(), and printArray(). The
fillArray() method should be called from the main method. The
fillArray() method should use a Scanner to take in a number
representing the length of the array and then read in numbers to fill
the array. The sumArray() method should take an int array as its input
parameter and returns an integer value that is the sum of all the
elements in the array. The avgArray() method should take an int array
as its input parameter and returns an integer value that is the
average of all the elements in the array. The printArray() method
should take an int array as its input parameter and has no return
value. It should then print out the elements of the array on the same
line separated by a space (“ “). All methods should work for integer
arrays.
Your code looks OK. You just need to assign the result of fillArray() to a variable, in order to use this result for further methods.
It would look like:
int[] array = fillArray();
System.out.println("Sum=" + sumArray(array));
System.out.println("Average=" + avgArray(array));
printArray(array);
Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}