How to use previous parameter from array in for loop - java

I have been try to code this, to increment the user input by 33 if the input is "31" or more up to the input or "90", and I have hit a wall where I want to use the user input from the array but I cannot. Could anyone help? Thank you.
if (choice.equals("R")) {
System.out.println("You have selected to draw a Rectangle!");
System.out.println("Please enter the Height and Width of the rectangle that is within 30cm - 90cm: ");
int[] array = new int[2];
int[] array2 = new int[2];
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
String[] numbers1 = line1.split(" ");
for(int i=0;i<numbers1.length;i++){
array[i] = Integer.parseInt(numbers1[i]);
}
I am trying to make a method to be able to easily call upon it later on, but that's the problem as I cannot complete my calculation.
public static void timeTurn (int a, int b) {
for(int i = 1000; i < 3001; i+= 33) {
if(numbers1.equals(>=30)) {
}
}
}

int[] array2 = new int[2]; is useless here.
By the way, please do not name a variable "array" or "array2". It's hard to understand for others and for yourself in the future.
if you defined the "array"s length to 2, then this for loop for(int i=0;i<numbers1.length;i++){...} is meaningless cause you already defined that you can only have two integers in this array.
I do not know the meaning of "convert cm to milliseconds" since one is distance and the other is time...
I can not understand (int a, int b) what "a", "b" means.
by my understanding the second code should be:
public static void timeTurn (int[] length) {
int minMillsecond = 1000;
int maxMillsecond = 3001;
int gap = 33;
for(int len : length){
if (30 <= len <= 90){
len += minMillsecond;
while(len < 3000){ len+=gap;}
print len;
}
}
}

Related

Array is being changed when in for statement

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.

How to use create 2 Array with User input with Std.readAllInts()

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.

Adding Numbers and printing the sum vertically using arrays

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

Removing specific value from array (java)

i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}

Array not returning strings

This is assessed work so please don't give the answer, just advice!
I'm trying to get my program to return the strings pass, compensation pass or fail depending on the values inputted by the user. However, it's not returning the values and I'm receiving an error for 'weighting'. Earlier it was working, however not in a suitable way because it wouldn't always return the correct before results. I added the array because i think that's what is needed, but now I'm just getting an error. Cheers.
enter code here
public class MarkCalculator {
static int[] marks = new int[12];
static int[] weighing = new int[6];
// public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int weighting;
int coursework;
int exammark;
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter course work weighting");
weighting = kb.nextInt();
weighing[i] = weighting;
}
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter course work mark ");
coursework = kb.nextInt();
marks[i] = coursework;
}
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter exam mark ");
exammark = kb.nextInt();
marks[i + 6] = exammark;
}
System.out.println("Calculating Marks");
MarkCalculator mc = new MarkCalculator();
String[] results = mc.computeMarks(marks, weighing);
for (String result : results) {
System.out.println("Results are " + result);
}
}
public String[] computeMarks(int[] marks, int[] weighing) {
int[] formula = new int[12];
String[] results = new String[weighing.length];
for (int i = 0; i < weighing.length; i++) {
int exam = marks[i];
int cw = marks[i+weighing.length];
int weight = weighing[i];
formula [i]= ((cw + weight) + (exam * (100 - weight)) / 100);
if ((formula[i]<=39) && (formula[i] > 35)) {
results[i] = "COMPENSATION PASS";}
else if (formula[i] >= 40) {
results[i] = "PASS";
}
else {
results[i] = "FAIL";
}
}
return results;
}
public static void computeResult (int[] coursework, int[] exammark)
{
computeResult(coursework,exammark);
}
}
Was posted as comment:
You could separate the marks into two arrays which will be easier to debug? Also it seems like you might be going over the array index for weightings on this line
for (int i = 0; i < marks.length;i++)
{
int exam = marks[i];
int cw = marks[i];
int weight = weighing[i]; // Error is here
//...
}
Because "weighing" has a range 0-5 and you are cycling through to 0-11 (with the marks array)
weighting and marks are different length arrays, yet you are doing the loop
for (int i = 0; i < marks.length; i++)
which will go out of bounds for weighting when i > 5.
It looks like you need to do something like this:
for (int i = 0; i < weighting.length; i++) {
int cw = marks[i];
int exam = marks[i+weighting.length];
int weight = weighing[i];
But that will depend on how you are storing the marks for the cw and exam in the marks array. I would recommend creating separate arrays for cw and exam as these are different items and will make things a lot easier to read and debug for yourself.
As you've asked for tips to improve your program as well, without specific code, then I would consider doing the following:
1) Have separate arrays for exam and cw marks. You're making it hard for yourself to debug your program by concatenating them together and this is also the source of your error.
2) Assuming that you always have the same number of exams as you do cw elements then I would consider having a class variable in MarkCalculator that stores the number of tests. Something like this:
private static int NUM_TESTS.
This way you can initialise arrays like this:
private static int[] examMarks = new int[NUM_TESTS]
and you can do the looping in computeMarks like this:
for (int i = 0; i < NUM_TESTS; i++)
This way if you decide you want more tests you only have to update the code in one place. It would also be easy to change your program so that the user could define how many tests should be calculated.
3) Where you have:
weighting = kb.nextInt();
weightings[i] = weighting;
replace it with:
weightings[i] = kb.nextInt();
as the variable weighting only seem to be used in this place and is therefore unnecessary. This will result in fewer operations the program has to perform and reduces the amount of code on the screen. In practice the compiler will likely remove this redundant variable, but it is good practice to think about how many operations you are performing and which of them aren't necessary.
4) It's better practice to explicitly set access modifiers on fields in a class. So you should have:
'private static int[] weightings = new int[NUM_TESTS];`
If you want to access it from another class you would then typically specify a getter method like so:
public int[] getWeightings() { return weightings; }
5) This is less important, but I would move main to the bottom of the class. In Java it's more typical to see the classes fields first, then the constructor, then public methods, then private methods and have the main at the bottom. In large projects it helps keeping to good style as it makes the code easier to read and understand.
These reference might help you learn more:
Java Coding Style Guide
Oracle Tutorial on access-modifiers
You will encounter an error as "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6"
This is because in method computeMarks. The length of marks (int[]) is 12.
and you just declare a variable with length 6 to handle:
int[] formula = new int[6];
when variable i in for loop reaches 6. The following code will throw out an error.
formula [i]= ((cw + weight) + (exam * (100 - weight)) / 100);
Have a try to declare it with length of 12.
int[] formula = new int[12];
Just paste code for method computeMarks.
public String[] computeMarks(int[] marks, int[] weighing) {
int[] formula = new int[12];
String[] results = new String[weighing.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < weighing.length; i++) {
sb.setLength(0);
int exam = marks[i];
int cw = marks[i + weighing.length];
int weight = weighing[i];
formula[i] = ((cw + weight) + (exam * (100 - weight)) / 100);
if ((formula[i] <= 39) && (formula[i] > 35)) {
sb.append("COMPENSATION PASS");
} else if (formula[i] >= 40) {
sb.append("PASS");
} else {
sb.append("FAIL");
}
sb.append(" cw mark is ").append(cw).append(" and exam mark is ")
.append(exam);
results[i] = sb.toString();
}
return results;
}

Categories