This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.
Related
I think that it supposed to be posted with entire codes in this time.
When I'm trying to get values from Scanner into array named "score",
the second for statement shows unexpected outcomes.
import java.util.Scanner;
public class B1546 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int[] score = new int[N];
Max scoreMax = new Max();
double sum = 0;
for (int i=0; i<N; i++) {
score[i] = input.nextInt();
}
for (int i=0; i<N; i++) {
System.out.println(score[i]); // this show the problems
sum = sum + ((double) score[i] / scoreMax.max(score) * 100);
}
System.out.println(sum / N);
}
}
class Max {
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
for( int i=0; i<score.length-1; i++) {
for( int j=i+1; j<score.length; j++) {
if (tmpArray[i]<tmpArray[j]) {
int tmp = tmpArray[i];
tmpArray[i] = tmpArray[j];
tmpArray[j] = tmp;
}
}
}
return tmpArray[0];
}
}
For example, when I type
3
10 20 30
then It comes
10
20
10
...
not
10
20
30
...
I don't know what is the problem.
Your Max.max method changes the array - the 3 lines starting with int tmp =.
Likely the source of your problems is not understanding reference types. tmpArray = score does not make a separate copy of the array score -- you just have two references to the same array. This concept is fundamental to Java programming.
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
}
score is a reference to the array object. Here you create a new reference to the existed array. To fix it, jut make a new array object:
int max(int[] score) {
int[] tmpArray = Arrays.copyOf(score, score.length);
}
int[] are objects and therefore are passed-by-reference in Java. When you do the following in your Max#max(int[]) method:
int[] tmpArray;
tmpArray = score;
Both tmpArray and score will hold the same reference, so when you swap values in the tmpArray, the score-array will be modified as well.
You'll have to create a new integer-array instead for the tmpArray, and copy the values. The simplest would be one of the following two:
int[] tmpArray = score.clone();
// or:
int[] tmpArray = Arrays.copyOf(score, score.length);
I would suggest the second, the .clone() is normally used for other purposes.
Try it online.
i'm working on a function which reads a file of strings with n lines.
Imagine each line in the file is numbered, starting from 0. i m trying to modify this function so it reads the whole file and then outputs the lines numbered 0, 3, 6,...
followed by the lines numbered 1, 4, 7,.... and finally followed by the lines numbered 2, 5, 8,....
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
String s;
List<String> tmp = new ArrayList<String>();
while((s = r.readLine())!=null){
tmp.add(s);
}
for (String text : s) {
w.println(text);
}
}
like for example:
0
1
2
3
4
5
6
7
8
9
should output
0
3
6
9
1
4
7
2
5
8
i'm sure i need to use the % sign. but i cant seem to figure out how. any help will be appreciated
You should use a List<Integer> if you store only int value (with Integer.parseInt(s) and catch the NumberFormatException).
Then you have to sort your List (with Collections.sort()) like this :
Collections.sort(tmp, new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
return new Integer(o1 % 3).compareTo(new Integer(o2 % 3));
}
});
You can use this loop to achieve what you want after you have created the list:
int gap = 3;
for (int i = 0; i < gap; i++) {
for (int j = i; j < tmp.size(); j+=gap) {
System.out.println(tmp.get(j));
}
}
If you want to jump more than 3, you just update the variable gap.
For this example will be taken into account that has all its lines in an array of strings, here I present a recursive function that iterates threes in the loop
static int cont=0;
public static int ReadLines(String[]array,int init)
{
if(cont>array.length-1)return 0;
else
{
for (int i = init; i < array.length; i+=3) {
System.out.println(array[i]);
cont++;
}
return ReadLines(array, init+1);
}
}
Call the function
String[] array = new String[]{"0","1","2","3","4","5","6","7","8","9"};
ReadLines(array,0);
Parse the file to 3 lists and then write one list after the other to the output:
final int num = 3;
ArrayList<String>[] lists = new ArrayList[num];
for (int i = 0; i < num; i++) {
lists[i] = new ArrayList<>();
}
String s;
for (int i = 0; (s = r.readLine())!=null; i++) {
lists[i % num].add(s);
}
for (int i = 0; i < num; i++) {
for (String line : lists[i]) {
w.println(line);
}
}
Add the lines to a array or list and you can get them by the index
I have to create a program which adds two integers and prints the sum vertically.
For example, I have.
a=323, b=322.
The output should be:
6
4
5
I've created the code for when the integers are up to two digits, but I want it to work for at least three digits.
Below is the best I could think of.
It may be completely wrong, but the only problem I'm facing is the declaration of array.
It says that the array might not be initialized.
If I set it to null then also it won't assign values to it later.
I know maybe I'm making a big mistake here, but I'll really appreciate if anyone could help me out.
Please keep in mind that I must not use any other functions for this code.
Hope I'm clear.
public class Vert
{
public static void main(String args[])
{
int n,i=0,j,a=323,b=322;
int s[];
n=a+b;
while(n>9)
{
s[i]=n%10;
i++;
s[i]=n/10;
if(s[i]>9)
{
n=s[i];
}
}
j=i;
for(j=i;j>=0;j--)
{
System.out.println(+s[j]);
}
}
}
String conversion seems like cheating, so here's a Stack.
int a = 323, b = 322;
java.util.Stack<Integer> stack = new java.util.Stack<>();
int n = a + b;
while (n > 0) {
stack.push(n % 10);
n = n / 10;
}
while (!stack.isEmpty())
System.out.println(stack.pop());
If an array is required, you need two passes over the sum
int a = 323, b = 322;
// Get the size of the array
int n = a + b;
int size = 0;
while (n > 0) {
size++;
n = n / 10;
}
// Build the output
int s[] = new int[size];
n = a + b;
for (int i = size - 1; n > 0; i--) {
s[i] = n % 10;
n = n / 10;
}
// Print
for (int x : s) {
System.out.println(x);
}
To initialize an array, you need to specify the size of your array as next:
int s[] = new int[mySize];
If you don't know the size of your array, you should consider using a List of Integer instead as next:
List<Integer> s = new ArrayList<Integer>();
Here is how it could be done:
// Convert the sum into a String
String result = String.valueOf(a + b);
for (int i=0; i <result.length();i++) {
// Print one character corresponding to a digit here per line
System.out.println(result.charAt(i));
}
I'd do it like this:
int a = 322;
int b = 322;
int sum = a + b;
String s = Integer.toString(sum);
for(int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
But your problem looks like an array is required.
The steps are same as in my solution:
Use int values
Sum the int values (operation)
Convert the int value in an array/string
Output the array/string
So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.
Ok, I am having a really beginner mistake here, but I can't think of what I need to do. I have an array permArray that I am recursively filling with possible permutations. I have a public method that gets the parameters ready, then I work on the array in the private method that calls itself to work on smaller and smaller parts.
The problem I am having, is how do I pass the finished array back to the public method. Would I return the array every time I am finished with the recursion (after I have placed the last element in each section, where the section size is 1).
Oh, and also, this is practice, not homework.
//todo:
//need to determine what is wrong with my array of linked lists
package wordchains;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.xml.soap.Node;
/**
*
* #author Samuel French
*/
public class WordChains {
public static void main(String[] args) {
//variables
int numWords = -1; //This will hold the number of words the user is inputting
String userInput; //holds the user input to be broken up into a string array
//Get the user's input, 0 is the quit value
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of words: ");
numWords = sc.nextInt();
System.out.println(">");
sc.nextLine();
userInput = sc.nextLine();
String[] inputWords = userInput.split("\\s+");
int numElements = inputWords.length;
int numOfPerms = numOfPerms(numElements);
//We will start by checking the last letter of the first word
char cTest;
int wordChecking = 0;
int[][] permArray = genPerms(numElements, numOfPerms);
for (int col = 0; col < numOfPerms; col++) {
System.out.println();
for (int row = 0; row < numElements; row++) {
System.out.print(permArray[col][row] + " ");
}
}
}
public static int numOfPerms(int numElements) {
int numOfPerms = numElements;
numElements--;
while (numElements > 0) {
numOfPerms = numOfPerms * numElements;
System.out.println(numOfPerms);
numElements--;
}
return numOfPerms;
}
public static int[][] genPerms(int numElements, int totPerms) {
int permArray[][] = new int[totPerms][numElements];
//either do it like this or create an array of head nodes
List<LinkedList<Integer>> elementsLeftList = new ArrayList<LinkedList<Integer>>();
LinkedList tempList = new LinkedList();
for (int x = 0; x < numElements; x++) {
tempList.addLast(x);
}
for (int x = 0; x < totPerms; x++) {
elementsLeftList.add((LinkedList<Integer>) tempList.clone());
}
return privateGenPerms(permArray,elementsLeftList,totPerms,0,0,totPerms);
}
private static void privateGenPerms(int[][] permArray, List<LinkedList<Integer>> elementsLeftList, int totalPermutations, int elementPlacing, int sectionBegin, int sectionSize) {
//variables-
//totalPermutations - the total number of permutations in the whole problem
//elementPlacing - the element currently being placed's position, corresponds to the rows of permArray
//elementPlacingIndex - the number of times the element currently being placed has been placed
//sectionSize - the size of the total working section. First time this is the # of permutations
//permCounter - this counter counts the permutation working with within the section
//sectionBegin - counts the beginning of the section working with
//2 Data structures:
//permArray - 2d the array of permutations
//elementsLeftList - list of lists of elements left, corresponds to each permutation
int totalNumberOfElements = permArray[0].length;
//
int numberOfElementsLeftToPlace = totalNumberOfElements - elementPlacing;
//
int permCounter = sectionBegin;
//Base case
if (numberOfElementsLeftToPlace == 1) {
for (int x = 0; x < totalPermutations; x++) {
permArray[x][totalNumberOfElements - 1] = (int) elementsLeftList.get(permCounter).remove(0); //may need to be a remove 1, not sure
}
return; //need to decide what I am going to do here
}
//
int elementPlacingIndex = 0;
int elementCurrentlyPlacing = 0; //could be a 1, don't remember
//
int numberOfTimesToPlaceWithinCol = (sectionSize / numberOfElementsLeftToPlace);
//
//
for (; permCounter < (sectionBegin + sectionSize); permCounter++) {
//when we need to switch to a different partition of the section
if (elementPlacingIndex == numberOfTimesToPlaceWithinCol) {
elementPlacingIndex = 0;
elementCurrentlyPlacing++;
}
permArray[permCounter][elementPlacing] = (int) elementsLeftList.get(permCounter).remove(elementCurrentlyPlacing);
elementPlacingIndex++;
}
for (int newSectionBegin = sectionBegin; newSectionBegin < (sectionBegin + sectionSize); newSectionBegin = newSectionBegin + numberOfTimesToPlaceWithinCol) {
privateGenPerms(permArray, elementsLeftList, totalPermutations, (elementPlacing + 1), newSectionBegin, (sectionSize / numberOfElementsLeftToPlace));
}
}
}
The array is passed-by-reference, so any changes you make in the private function will be permanent and you do not need to return the modified array again.
I have not looked at your logic to see if this is the correct way to do it in your case though.