The code below gets the failed indexes from a text file and prints it to a webpage and the lower loop does same but for the passes. I want to calculate the percentages and I have tried the code below but it returns 0.0%.
Please help as I am a novice programmer.
int i = 0;
while ((i = (secondLine.indexOf(failures, i) + 1)) > 0) {
System.out.println(i);
feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + resultString.length() + " tests.<br>";
}
int j = 0;
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
System.out.println(j);
feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";
}
totalScore = j * 100 / resultString.length();
System.out.println(totalScore);
feedbackString += "Your submission scored " + totalScore + "%.<br>";
You want to make your division a floating point division :
totalScore = (double)j * 100 / resultString.length();
That's assuming totalScore is a double.
Otherwise, j * 100 / resultString.length() would use int division, so if resultString.length() > 100, the result would be 0.
As Tom mentioned, the condition of the while loop :
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0)
ensures the it will end only once j <= 0. Therefore, it's no wonder (double)j * 100 / resultString.length() is 0.
If you want to count the number of passes you need a second counter :
int j = 0;
int passes = 0;
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
passes++;
System.out.println(j);
feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";
}
Then
totalScore = (double)passes * 100 / resultString.length();
The problem is that j is not the count of failures, it's an index to the failure. Since you indexOf returns -1 in case it didn't find the element and you use it to mark the end of search, it will always be -1. Add 1 and you always get j == 0.
You can do it that way:
String secondLine = "pfpffpfffp";
char failures = 'f';
char passed = 'p';
ArrayList<Integer> failuresList = new ArrayList<Integer>();
ArrayList<Integer> passedList = new ArrayList<Integer>();
String feedbackString = "";
for (int i = 0; i < secondLine.length(); i++) {
char o = secondLine.charAt(i);
if (o == failures) {
failuresList.add(i);
} else {
passedList.add(i);
}
}
int countFailures = failuresList.size();
int countPassed = passedList.size();
int countTotal = countFailures + countPassed;
for (int i = 0; i < failuresList.size(); i++) {
System.out.println(failuresList.get(i));
feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + countTotal + " tests.<br>";
}
for (int i = 0; i < passedList.size(); i++) {
System.out.println(passedList.get(i));
feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + i + "</strong> - Well done.</li>";
}
double totalScore = countPassed * 100.0 / countTotal;
System.out.println(totalScore);
feedbackString += "Your submission scored " + totalScore + "%.<br>";
System.out.println(feedbackString);
Related
public long process(long[][] theArray) {
long result = 0l;
int xDimension = 0;
int yDimension = 0;
for (int i = 0; i < theArray.length; i++) {
for (int j = 0; j < theArray[0].length; j++) {
if (((yDimension + 12) < theArray.length) && ((xDimension + 12) < theArray[0].length)) {
result = (theArray[yDimension][xDimension + 1]) + (theArray[yDimension][xDimension + 2])
+ (theArray[yDimension + 1][xDimension]) + (theArray[yDimension + 1][xDimension + 3])
+ (theArray[yDimension + 2][xDimension]) + (theArray[yDimension + 2][xDimension + 3])
+ (theArray[yDimension + 3][xDimension + 1]) + (theArray[yDimension + 3][xDimension + 2]);
}
xDimension++;
}
xDimension -= (theArray[0].length);
yDimension++;
}
return result;
}// method()
--> my console says : Index 5 out of bounds for length 5. But how is that possible together with my if-condition?
xDimension starts with 0 and will be negative after one iteration of the outer loop.
Here is my code. I think that there is much better way to fill matrix with integers from String lines. My output shows correct output, but it is too complicated. How to make it less complex?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int [][]matrix = new int [7777][7777];
int counter = 0;
int counter1 = 0;
for (int i = 0; i < 7777; i++) {
String s = scanner.nextLine();
if (!"end".equals(s)) {
counter++;
String s1[] = s.split(" ");
for (int j = 0; j < s1.length; j++) {
matrix[i][j] = Integer.parseInt(s1[j]);
counter1++;
}
} else {
break;
}
}
int v = counter;
int h = counter1/counter;
for (int i = 0; i < v; i++) {
for (int j = 0; j < h; j++) {
if (v == 1 || h == 1) {
System.out.print(matrix[i][j]*4 + " ");
} else if (i == 0){
if (j == 0){
System.out.print(matrix[v-1][j] + matrix[i+1][j] + matrix[i][h-1] + matrix[i][j+1] + " ");
} else if (j != h-1){
System.out.print(matrix[v-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][j+1] + " ");
} else {
System.out.print(matrix[v-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][0] + " ");
}
} else if (j == 0 && i != v-1){
System.out.print(matrix[i-1][j] + matrix[i+1][j] + matrix[i][h-1] + matrix[i][j+1] + " ");
} else if (j != 0 && j != h-1 && i != v-1) {
System.out.print(matrix[i-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][j+1] + " ");
} else if (j == h-1 && i != v-1){
System.out.print(matrix[i-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][0] + " ");
} else if (i == v-1) {
if (j == 0) {
System.out.print(matrix[i-1][j] + matrix[0][j] + matrix[i][h-1] + matrix[i][j+1] + " ");
} else if (j != h-1) {
System.out.print(matrix[i-1][j] + matrix[0][j] + matrix[i][j-1] + matrix[i][j+1] + " ");
} else {
System.out.print(matrix[i-1][j] + matrix[0][j] + matrix[i][j-1] + matrix[i][0] + " ");
}
}
}
System.out.println();
}
}
}
Here is the task assignment.
Write a program, which inputs the rectangular matrix from a sequence of lines, ending with a line, containing the only word "end" (without the quotation marks).
The program should output the matrix of the same size, where each elements in the position (i, j) is equal to the sum of the elements from the first matrix on the positions (i-1, j), (i+1, j), (i, j-1), (i, j+1). Boundary elements have neighbours on the opposite side of the matrix. In the case with one row or column, the element itself maybe its neighbour.
Sample Input:
9 5 3
0 7 -1
-5 2 9
end
Sample Output:
3 21 22
10 6 19
20 16 -1
Yes this code could be simplified.
Starting off, using array is not the best choice for containing the input because you don't know the input size. Using a List that can expand to fit the data will be easier. Further, using the Stream api, we can convert the input into a List<List<Integer>> fairly easily.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<List<Integer>> matrix = reader.lines()
.takeWhile(line -> !line.equals("end"))
.map(line -> Arrays.stream(line.split(" "))
.map(Integer::valueOf)
.collect(Collectors.toList()))
.collect(Collectors.toList());
Now that we have the data in our list we will compute the size of the width and height.
int height = matrix.size();
int width = matrix.get(0).size();
Computing the locations of (i-1, j), (i+1, j), (i, j-1), (i, j+1) without an IndexOutOfBoundsException is a little more tricky, however you can use this modulo formula. As long as the offset isn't negatively larger than the size this will work. You can also that the modulo of the offset if that is a concern
(size + index + offset) % size
// or
(size + index + (offset % size)) % size
To add the strings together with a space you can use a StringJoiner.
for (int i = 0; i < height; i++) {
StringJoiner joiner = new StringJoiner(" ");
for (int j = 0; j < width; j++) {
int value = matrix.get((height + i - 1) % height).get(j)
+ matrix.get((height + i + 1) % height).get(j)
+ matrix.get(i).get((width + j - 1) % width)
+ matrix.get(i).get((width + j + 1) % width);
joiner.add(String.valueOf(value));
}
System.out.println(joiner.toString());
}
I'm trying to reach this :
1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + 3 + ... + n)
I'm already getting this result:-
(1 + 2) + (2 + 3)
with this code :
int n = 8;
for (int i = 1; i < n; i++){
int j = i + 1;
System.out.print("(" + i + " + " + j + ")");
}
How can I achieve the top result ?
You need two loops like this :
int n = 8;
String del;
String del2 = "";
for (int i = 1; i <= n; i++) {
System.out.print(del2 + "(");
del = "";
for (int j = 1; j <= i; j++) {
System.out.print(del + j);
del = " + ";
}
System.out.print(")");
del2 = " + ";
}
code demo
Move the declaration of j before the loop and initialize it with 0, then just add the current i to j.
That would solve what? – AKSW
This would calculate the sum of the equation.
To print the equation you also need one loop only:
int n = 8;
StringBuilder equation = new StringBuilder("1");
StringBuilder equationGroup = new StringBuilder("1");
for (int i = 2; i < n; i++) {
equationGroup.append(" + ");
equationGroup.append(i);
equation.append(" + (");
equation.append(equationGroup.toString());
equation.append(")");
}
System.out.println(equation.toString());
Well, thanks #YCF_L for your answer it's the correct one, but this complete one after edit, i posted it in case some one need the complete solution:
int n = 8;
String del;
String delPlus = "";
String rightPract = "", leftPract = "";
for (int i = 2; i < n; i++) {
System.out.print(delPlus + rightPract);
del = "";
for (int j = 1; j < i; j++) {
System.out.print(del + j);
del = " + ";
}
System.out.print(leftPract);
delPlus = " + ";
rightPract = "(";
leftPract = ")";
}
Now the result is :-
1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4 + 5) + (1 + 2 + 3 + 4 + 5 + 6)
If you take the recursion approach you have to think of it as a recursion inside another recursion. add(i,n) generates 1 and (1+2) and (1+2+3) up to (1+2+3...n). then the sum(i,n) recursively sum them together
public static int add(int i, int n){
if(i == n){
return n;
}
return i + add(i+1,n);
}
public static int sum(int i, int n){
if(i == n){
return add(0,n);
}
return add(0, i) + sum(i+1,n);
}
public static void main(String[] args){
int n = 8;
System.out.print(sum(0, n));
}
I am new to Java and there's this one question that makes me wonder. How to make the for inner loop more efficient in this code?
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j < i; j++) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
I was just trying to get the factors of numbers from 2 to 100 but how can i make the inner loop more efficient?
It's a little bit number theory involved here but if you do this it would be efficient specially when the 100 is replaced with something much bigger:
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j <= (int) Math.sqrt(i); j++) {
if (i % j == 0) System.out.print(j + " " + i / j + " ");
}
System.out.println();
}
You could use the fact that for every divisor a of i there is a number b such that a * b = i.
Find all divisors a <= sqrt(i) and save b = i/a and print these values later.
final int num = 100;
int[] divisors = new int[(int) Math.sqrt(num)];
for (int i = 2; i <= num; i++) {
System.out.print("Factors of " + i + " is: ");
int j = 2;
int index = 0;
for (; j * j < i; j++) {
if (i % j == 0) {
System.out.print(j + " ");
divisors[index++] = i / j;
}
}
if (j * j == i) {
// print sqrt(i) only once, if it's integral
System.out.print(j + " ");
}
while (--index >= 0) {
System.out.print(divisors[index] + " ");
}
System.out.println();
}
This way your inner loop needs only O(sqrt(i)) instead of O(i) operations.
This code time complexity is O(N2).
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = i/2; j > 1; j--) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
}
Try this,as your code output will be displayed as follows (ascending order)
Factors of 24 is: 2 3 4 6 8 12
please be noticed, but this given code will be displayed output as follows (descending order )
Factors of 24 is: 12 8 6 4 3 2
"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.
Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}
Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}
I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));
Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .