Question

Write a Java method that will take an array of integers of size n and shift...

Write a Java method that will take an array of integers of size n and shift right by m places, where n > m. You should read your inputs from a file and write your outputs to another file. Create at least 3 test cases and report their output.

I've created a program to read and write to separate files but i don't know how to store the numbers from the input file into an array and then store the new shifted array into an output file.  

****MY CODE*****

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.Scanner;

public class shiftedArray {

public static void main(String[] args) throws FileNotFoundException {

File input = new File("inputFile.txt");

// this is main file to read from

PrintWriter output = new PrintWriter("OutputFile.txt");

//printwriter writes to the new file outputFile.txt

Scanner sc = new Scanner(input); //scans input file

//while loop to loop all lines from main file

while(sc.hasNextLine()) {

output.println(sc.nextLine());

}

//close scanner of input file and close new file output

sc.close();

output.close();

// TODO Auto-generated method stub

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class shiftedArray {
    public static void main(String[] args) throws FileNotFoundException {
        /**
         * For reading file
         */
        File input = new File("inputFile.txt");
        /**
         * For writing file
         */
        PrintWriter output = new PrintWriter("outputFile.txt");
        /**
         * Scanner class for reading file and reading from user
         * sc -- for reading from file
         * scan -- for reading from user
         */
        Scanner sc = new Scanner(input); //scans input file
        Scanner scan = new Scanner(System.in);
        /**
         * Reading size of array from user
         */
        System.out.print("Enter size of array: ");
        int n = scan.nextInt();
        /**
         * creating array of size n to read n integers from file
         */
        int[] arr = new int[n];
        int i = 0; // index in array
        /**
         * Reading n integers from file
         */
        while(i<n && sc.hasNextInt()) {
            int val = sc.nextInt();
            arr[i] = val; // storing in array at index i
            i++; // increase index by 1
        }
        /**
         * reading value of m which denotes the right shift count
         */
        System.out.print("Enter value of m: ");
        int m = scan.nextInt();
        /**
         * Rotating m right shift of array
         */
        
        
        /**
         * Creating a temp array of size m to store the last m integers of array 
         */
        int[] temp = new int[m];
        int j = n - 1;
        for(i = m-1;i>=0;i--,j--) {
            temp[i] = arr[j];
        }
        /**
         * shifting first (n-m) integers to m index right
         */
        for(i=n-m-1;i>=0;i--) {
            arr[i+m] = arr[i];
        }
        /**
         * Put last m integers in the starting of array to complete the process of rotating of array
         */
        for(i=0;i<m;i++) {
            arr[i] = temp[i];
        }
        /**
         * Writing the array integers in file after right shifting
         */
        for(i=0;i<n;i++)
            output.print(arr[i] + " ");
        /**
         * closing the files
         */
        sc.close();
        output.close();
    }
}

Input file content (inputFile.txt):

5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 105 110 115

Sample input 1:
Enter size of array: 10 Enter value of m: 3

Sample output 1:

40 45 50 5 10 15 20 25 30 35 

Sample input 2:
Enter size of array: 5 Enter value of m: 4

Sample output 2:

10 15 20 25 5 

Sample input 3:
Enter size of array: 15 Enter value of m: 7

Sample output 3:

45 50 55 60 65 70 75 5 10 15 20 25 30 35 40 

Screenshot of code:
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class

for(i=0;i<m;i++) { arr[i] = temp[i]; for(i=0;i<n;i++) output.print(arr[i] + ); sc.close(); output.close(); 36 37 } }

If the answer helped please upvote, it means a lot and for any query please comment.

Add a comment
Know the answer?
Add Answer to:
Write a Java method that will take an array of integers of size n and shift...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a program to create a file named integerFile.txt if it does not exist. Write 100...

    Write a program to create a file named integerFile.txt if it does not exist. Write 100 integers created randomly into the file using text I/O. The random integers should be in the range 0 to 100 (including 0 and 100). Integers should be separated by spaces in the file. Read the data back from the file and display the data in increasing order This is what I have so far: import java.io.File; import java.util.Scanner; import java.io.PrintWriter; public class integerFile {...

  • **Java** Assume that indata1 and indata2 are two files containing at least two integers, separated by...

    **Java** Assume that indata1 and indata2 are two files containing at least two integers, separated by white space. Write a program named Add2 that writes the sum of the first integers of these two files to a file named outdata1. It writes the sum of the first integers of these two files to a file named outdata2. Each sum is written on a line by itself. So, if the contents of indata1 were "37 6 90" and the contents of...

  • In Java, Implement a class MyArray as defined below, to store an array of integers (int)....

    In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion. Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another...

  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • JAVA Which of these statements does not match by using exception action in Java? 1. Exception...

    JAVA Which of these statements does not match by using exception action in Java? 1. Exception action makes it possible for the calling method to handle errors in called methods.    2. Exception action simplifies programming since incorrect reporting and handling can be located in catch blocks separately from the rest of the code.    3. Exception action increases the performance of programs. 4. Java separates exception action from common processes. Why create instances of File Class? - several alternatives...

  • Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File;...

    Get doubles from input file. Output the biggest. Answer the comments throughout the code. import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Lab8Num1 { public static void main(String[] args) { //Declaring variable to be used for storing and for output double biggest,temp; //Creating file to read numbers File inFile = new File("lab8.txt"); //Stream to read data from file Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { //Logger.getLogger(Lab10.class.getName()).log(Level.SEVERE, null, ex); } //get first number...

  • Computer Science - Java Explain the code step by step (in detailed order). Also explain what...

    Computer Science - Java Explain the code step by step (in detailed order). Also explain what the program required. Thanks 7 import java.io.File; 8 import java.util.Scanner; 9 import java.util.Arrays; 10 import java.io.FileNotFoundException; 12 public class insertionSort 13 14 public static void insertionSort (double array]) 15 int n -array.length; for (int j-1; j < n; j++) 17 18 19 20 21 double key - array[j]; int i-_1 while ( (i > -1) && ( array [i] > key array [i+1] -...

  • Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class...

    Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class Car {    private int year; private String model; private String make; int speed; public Car(int year, String model, String make, int speed) { this.year = year; this.model = model; this.make = make; this.speed = speed; } public Car() { } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getModel() { return model; }...

  • I have this program that works but not for the correct input file. I need the...

    I have this program that works but not for the correct input file. I need the program to detect the commas Input looks like: first_name,last_name,grade1,grade2,grade3,grade4,grade5 Dylan,Kelly,97,99,95,88,94 Tom,Brady,100,90,54,91,77 Adam,Sandler,90,87,78,66,55 Michael,Jordan,80,95,100,89,79 Elon,Musk,80,58,76,100,95 output needs to look like: Tom Brady -------------------------- Assignment 1: A Assignment 2: A Assignment 3: E Assignment 4: A Assignment 5: C Final Grade: 82.4 = B The current program: import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class main {    public static void main(String[]...

  • Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this...

    Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this file, include your assignment documentation code block. After the documentation block, you will need several import statements. import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; Next, declare the Lab12 class and define the main function. public class Lab12 { public static void main (String [] args) { Step 2: Declaring Variables For this section of the lab, you will need to declare...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT