Make Array From Temporary Arrays - java

I have a file in where rows of random integers are divided by "::".
For example "1 2 3::4 5:: 6 7 8 9::10 11 12::13"
What I want to make is an array where the rows are combined as follows: take the second row and place at the back of the first row, then take the third row place it in front of the first row, take the fourth row and place it at the back etc.
At the moment I can fill a temporary array with one row and place it in the totalArray but this will get overwritten by with the next row.
I can not use ArrayList or multi dimensional arrays.
The code to make it more clear:
class1() {
in = new Scanner(System.in);
out = new PrintStream(System.out);
}
public void lineToArray (Scanner intScanner) {
int i = 0;
int[] tempArray = new int[100];
while (intScanner.hasNext()) {
tempArray[i] = intScanner.nextInt();
i++;
}
}
public void readFile() {
while (in.hasNext()) {
in.useDelimiter("::");
String line = in.next();
Scanner lineScanner = new Scanner(line);
lineToArray(lineScanner);
}
}
void start() {
readFile();
}
and
public class Class2 {
int[] totalArray = new int[1000];
Class2() {
}
public void addToFront(int[] tempArray, int i) {
//totalArray = tempArray + totalArray
}
public void addToBack(int[] tempArray, int i) {
//totalArray = totalArray + tempArray
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Bear in mind that I'm a beginner

public static void main(String args[]) throws IOException
{
Scanner in = new Scanner(System.in);
PrintWriter w = new PrintWriter(System.out);
String inp = in.nextLine();
String s[] = inp.split("::");
StringBuilder ans = new StringBuilder();
for(int i = 0; i < s.length; i++){
if(i == 0){
ans.append(s[i]);
}
else if(i%2 == 0){
ans.append("::"+s[i]);
} else{
ans.reverse();
StringBuilder add = new StringBuilder(s[i]);
add.reverse();
ans.append("::"+add);
ans.reverse();
}
}
w.println(ans);
w.close();
}
Output:
1 2 3::4 5:: 6 7 8 9::10 11 12::13
10 11 12::4 5::1 2 3:: 6 7 8 9::13

Related

Set elements of passing to true whenever the parallel value of scores is a certain number or above?

The method (public static void processPass(boolean[] passing, double[] scores, int
length) should accept passing, scores, and length as parameters and it must set the elements of passing to true when the parallel value of
scores is 60 or more than 60.
I just started Programming II and everything got very complicated. I have the first part of the lab (which I didn't mention) but I have no clue what I did in the last method.
This website is always really helpful, I appreciate that.
public static void main(String[] args) throws IOException {
boolean[] isPassing = new boolean[100];
double[] scores = new double[100];
getData(scores);
}
public static int getData(double scores[]) throws FileNotFoundException {
File fileIn = new File("lab1data.txt");
int length = 0;
Scanner infile = new Scanner(fileIn);
while(infile.hasNext()) {
scores[length] = infile.nextDouble();
length +=1;
}
for(int i = 0; i < length; i++) {
System.out.println(scores[i] + "\n");
}
System.out.println("Length: " + length);
infile.close();
return length;
}
//this is what I am struggling with
public static void processPass(boolean[] passing, double[] scores, int length) {
if(length <= 60) {
passing[length] = true;
}
System.out.println(passing[length]);
}
}

Printing an Array as a String with 10 elements per line

// 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

Possible to create two different sized arrays/matrices from a file?

Basically, I'm trying to create two different sized 2D arrays from a text file that looks like this:
2
add
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
subtract
2 2
2 12
10 0
4 6
9 1
The 2 is the number of problems (add and subtract), the 3 and 4 are the number of rows and columns, and the numbers below it are the two separate matrices being filled into the 2D arrays. If I just stop there, this program works correctly:
class Matrices {
private Scanner fileReader;
private int rows;
private int columns;
int problems;
String method;
public Matrices(String file) throws FileNotFoundException {
this.fileReader = new Scanner(new FileInputStream(file));
problems = fileReader.nextInt();
method = fileReader.next();
if(method.equals("add")) {
rows = fileReader.nextInt();
columns = fileReader.nextInt();
}
}
public int[][] readMatrix() throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public int[][] add(int[][] a, int[][] b) {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public void printMatrix(int[][] matrix) {
for ( int[] anArray : matrix ) {
for ( int anInt : anArray ) {
System.out.print(anInt+ " ");
}
System.out.println();
}
}
}
With this driver:
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
Matrices matrixReader = new Matrices(filename);
int[][] a = matrixReader.readMatrix();
int[][] b = matrixReader.readMatrix();
System.out.println("Matrix 1: ");
matrixReader.printMatrix(a);
System.out.println();
System.out.println("Matrix 2: ");
matrixReader.printMatrix(b);
System.out.println();
System.out.println("Addition: ");
int[][] addition = matrixReader.add(a,b);
matrixReader.printMatrix(addition);
}
}
It creates and prints the matrices just fine, with no problems. However, whenever I try to create and print the next two matrices (the 2x2 arrays below subtract in the text file), it returns the following error:
Enter name of file:
data/Matrices.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at baker.Matrices.readMatrix(Matrices.java:27)
at baker.MatricesDriver.main(MatricesDriver.java:15
My question is, what adjustments should I make so that the program recognizes that two of the 2D arrays are to be 3x4, and the two following are to be 2x2?
I would recommend decomposing your implementation into the following parts:
class Matrix - holds the values of one matrix from problem definition
class Problem - holds the operation and the two matrices from problem definition
The Matrix class could look like:
class Matrix {
private int[][] values;
public Matrix(int[][] values) {
this.values = values;
}
public int[][] getValues() {
return values;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Matrix [values=\n");
for (int i = 0; i < values.length; i++) {
sb.append("\t" + Arrays.toString(values[i]) + "\n");
}
sb.append("]");
return sb.toString();
}
}
The Problem class could be:
class Problem {
private String operation;
private Matrix first;
private Matrix second;
public Problem(String operation, Matrix firstMatrix, Matrix secondMatrix) {
this.operation = operation;
first = firstMatrix;
second = secondMatrix;
}
public String getOperation() {
return operation;
}
public Matrix getFirst() {
return first;
}
public Matrix getSecond() {
return second;
}
#Override
public String toString() {
return "Problem [\noperation=" + operation + ", \nfirst=" + first + ", \nsecond=" + second + "\n]";
}
}
Based on this, your "driver" class does the following:
Get the filename from user input
Read from file the number of problems and construct a list with this initial size
For the number of problems (i.e. 2) get the operation, rows, and colums and construct a new Problem object containing these information and put the Problem into the list ...
Here is one simple solution - still room for improvement here :-)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
List<Problem> problems = readProblems(filename);
System.out.println(problems);
keyboard.close();
}
private static List<Problem> readProblems(final String filename) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(filename));
int numberOfProblems = fileReader.nextInt();
List<Problem> problems = new ArrayList<>(numberOfProblems);
for (int i = 1; i <= numberOfProblems; i++) {
problems.add(readProblem(fileReader));
}
fileReader.close();
return problems;
}
private static Problem readProblem(Scanner fileReader) throws FileNotFoundException {
fileReader.nextLine(); // go to next line
String operation = fileReader.nextLine(); // read problem operation
int rows = fileReader.nextInt(); // read number of rows
int columns = fileReader.nextInt(); // read number of columns
Matrix firstMatrix = readMatrix(rows, columns, fileReader);
Matrix secondMatrix = readMatrix(rows, columns, fileReader);
return new Problem(operation, firstMatrix, secondMatrix);
}
private static Matrix readMatrix(final int rows, final int columns, final Scanner fileReader) throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return new Matrix(result);
}
}
Tested with your input file.
HTH
You tried to structure your data?
you can use that:
properties-file
For create array or vector without a fixed size use arrayList, you can make a arrayList from a arrayList

Java Fibonacci series

What would be the next step in order to ask the user which of the numbers in this series of 30 he wants to see and prompts for an integer input - a number between 1 and 30 (inclusive)?
So if the user wants to see the fifth (5th) number of the Fibonacci series the user would input the integer 5 in response to the prompt.
public class MyFibonacci {
public static void main(String a[]) {
int febCount = 30;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++) {
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++) {
System.out.print(feb[i] + " ");
}
}
}
Use a Scanner, or some InputStreamReader to read the input from the console. Scanner would be used in this way:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt())
int someInt = scanner.nextInt();
Another option would be to use some reader like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
and parse the required data from the output of the reader. Using Scanner will be simpler in most cases though.
public class Fibonacci_series // upto less than a given number
{
public static void main(long n)
{
long a=0, b=1, c=0;
while (c<n)
{
a=b;
b=c;
System.out.print(c+", ");
c=a+b;
}
System.out.print("....");
}
}
Here you go :
public class TestProgram {
public static void main(String a[]) {
Scanner reader = new Scanner(System.in);
printFibonacciSeries();
System.out.println("");
System.out.println("Fibonacci Series, Enter the number in the series of 30 you want to see");
int num = reader.nextInt();
int febCount = 30;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
if (i == num) {
System.out.print(feb[i] + " ");
}
}
}
public static void printFibonacciSeries() {
int febCount = 31;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
System.out.print(feb[i] + " ");
}
}
}
You could use a command line argument and read it from the main method args:
public class MyFibonacci {
public static void main(String a[]) throws NumberFormatException {
int febCount = Integer.parseInt(a[0]);
then call it with
java MyFibonacci 30
Or pass it in the 'VM options' input in an IntelliJ run configuration

I am trying to create a method that calculates the averages of numbers in two arrays

import java.io.*;
import java.util.*;
public class Marks {
public static void main(String[] args) {
Marks r = new Marks();
double[] finalArray = r.openFile();
double[] finalArray2 = r.openFile2();
}
//ID's and first set of grades
private Scanner a;
public double[] openFile() {
ArrayList<String> list1 = new ArrayList<String>(7);
try {
a = new Scanner(new File("IR101.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (a.hasNextLine()) {
list1.add(a.nextLine());
}
String[] arrayOne = list1.toArray(new String[list1.size()]);
Arrays.sort(arrayOne);
//System.out.println(Arrays.toString(arrayOne));
int size = arrayOne.length;
double[] finalArray = new double[size];
for (int j = 0; j < size; j++) {
String word = arrayOne[j];
String newWord = word.substring(6, 10);
double grade = Double.parseDouble(newWord);
finalArray[j] = grade;
}return finalArray;
}
//ID's and second set of grades
private Scanner b;
public double[] openFile2() {
ArrayList<String> list2 = new ArrayList<String>(7);
try {
b = new Scanner(new File("IR102.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (b.hasNextLine()) {
list2.add(b.nextLine());
}
String[] arrayTwo = list2.toArray(new String[list2.size()]);
Arrays.sort(arrayTwo);
//System.out.println(Arrays.toString(arrayTwo));
int size = arrayTwo.length;
double[] finalArray2 = new double[size];
for (int j = 0; j < size; j++) {
String word = arrayTwo[j];
String newWord = word.substring(6, 10);
double grade2 = Double.parseDouble(newWord);
finalArray2[j] = grade2;
}return finalArray2;
}
// ID's and names
private Scanner c;
public void openFile3() {
ArrayList<String> list3 = new ArrayList<String>(7);
try {
c = new Scanner(new File("IRStudents.txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (c.hasNextLine()) {
list3.add(c.nextLine());
}
String[] arrayThree = list3.toArray(new String[list3.size()]);
Arrays.sort(arrayThree);
//System.out.println(Arrays.toString(arrayThree));
int size = arrayThree.length;
String[] names = new String[size];
for (int j = 0; j < size; j++) {
names[j] = arrayThree[j].substring(6);
}
String[] IDs = new String[size];
for (int x = 0; x < size; x++){
IDs[x] = arrayThree[x].substring(0,5);
}
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(IDs));
}
public void calculateAvg() {
}
}
I am trying to access the numbers in finalArray and finalArray2 but I am not sure how to do this when I try to call on the two arrays it does not work I think it is to do with the scope of the arrays.So how do I make the two array accessible to the whole program.
If you want to make the two arrays accessible to the whole program, declare them as static variables outside of the main method and initialize inside like seen here:
public class Marks {
static double[] finalArray;
static double[] finalArray2;
public static void main(String[] args) {
Marks r = new Marks();
finalArray = r.openFile();
finalArray2 = r.openFile2();
While you could make the arrays visible to the whole class, it probably makes more sense to pass them to the method which should access them. So do something like this:
public void calculateAvg(double[] array1, double[] array2) {
// ...
}
You can then call it like this:
public static void main(String[] args) {
Marks r = new Marks();
double[] finalArray = r.openFile();
double[] finalArray2 = r.openFile2();
r.calculateAvg(finalArray, finalArray2);
}

Categories

Resources