I would like my print statement to be outside the loop so the statement doesn't print the same thing over and over. The for loop below simply checks a number from one array against another to find out how many matches have been found. Defining the variables above and printing the statements below results in a "variable not initialised error" which is understandable.
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
int lottMtch = count(chkNum, rndNum);
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
System.out.print(chkNum);
}
else {
System.out.print("no matches found");
}
}
Declare the variable before the loop and then do your stuff in the loops, like adding one to the variable if it is found, then print it out afterwards if it is more than 0. Something like this...
int var = 0;
for(...) {
if(found)
var++;
}
if(var > 0)
sysout(var);
Of course this code won't work but it is a start. For your learning experience I will let you implement this idea with your code.
this would not really make sense ..
if you want than Try this ...
int lottMtch[]=new int[myArray.length];
Arrays.fill(lottMtch, 0);
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
lottMtch[i] = count(chkNum, rndNum);
}
for (int i = 0; i < 6; i++)
{
if (lottMtch[i] > 0)
System.out.println(lottMtch[i] + " matches found "+ myArray[i]);
}
If you wan to found just how many match of rndNum in myArray Than try this
Here i assume rndNm is global
int lottMtch=0;
for (int i = 0; i < 6; i++)
{
lottMtch += count(myArray[i], rndNum);
}
if (lottMtch> 0)
System.out.println(lottMtch + " matches found "+ rndNum);
As per discussed in comment Try this ..
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < 6; i++)
{
Integer chkNum = myArray[i];
Integer cnt = (Integer)count(myArray[i], rndNum);
if(cnt>0)
{
if(map.get(chkNum)==null)
map.put(chkNum,1);
else
map.put(chkNum, map.get(chkNum)+1);
}
}
for (Object key : map.keySet())
System.out.println(map.get(key) + " matches found "+key.toString());
This is because if you only declare the variables above the loop and only initialize said variables in the loop, when you attempt to print them outside of the loop, there's no guarantee that they would have been initialized.
So, perhaps you want something like this:
int lottMtch = 0;
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
lottMtch += count(chkNum, rndNum);
//System.out.print(chkNum); this would not really make sense outside of the loop
}
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
}
else
{
System.out.print("no matches found");
}
You need to declare a variable outside the loop if you plan to access it after the loop exits.
You need to initialise variables outside the loop. Try this:
int chkNum = 0;
int lottMtch = 0;
for (int i = 0; i < 6; i++)
{
chkNum = myArray[i];
lottMtch = count(chkNum, rndNum);
}
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
System.out.print(chkNum);
}
else {
System.out.print("no matches found");
}
Related
Im using a while-loop to check if there is a matching number in an array. But when there is, it appears the loop becomes endless and doesnt stop running
Im very new to java, so I havent tried a lot of things because I dont know what will work and what will not.
I believe the problem lies within the fyllArray or sjekkArray.
NOTE: Im norwegian, so a lot of things I can name myself (variables?) are in norwegian, but I think anyone can understand it.
import java.text.DecimalFormat;
import static javax.swing.JOptionPane.*;
class UnikeTall{
java.text.DecimalFormat df = new DecimalFormat("0.0");
static int[] array;
boolean likt = false;
int min = 1000;
int max = 0;
private void setArray(int lengde){
array = new int[lengde];
}
private boolean sjekkArray(int tall){
for(int i = 0; i < array.length; i++){
if(tall == array[i]){
likt = true;
}
}
if(likt != true){
likt = false;
}
return likt;
}
private void fyllArray(){
int tall = 0;
boolean sjekk = false;
for(int i = 0; i < array.length; i++){
while(!sjekk){
tall = (int) (Math.random() * (900) + (100));
sjekkArray(tall);
if(likt == true){
continue;
}
if(likt == false) {
sjekk = true;
}
}
sjekk = false;
array[i] = tall;
}
}
private String sjekkMin(){
String lavest;
for(int i = 0; i < array.length; i++){
if(array[i] < min){
min = array[i];
}
}
lavest = "Minste tall er: " + min;
return lavest;
}
private String sjekkMax(){
String størst;
for(int i = 0; i < array.length; i++){
if(array[i] > max){
max = array[i];
}
}
størst = "Største tall er: " + max;
return størst;
}
private double gjennomsnitt(){
int sum = 0;
double snitt;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
snitt = sum / array.length;
return snitt;
}
public void kjorArray(){
String utskrift = "";
int antall = 0;
int lengde = Integer.parseInt(showInputDialog("Hvor langt skal arrayet være?"));
//The text in the input box translates to: "How long do you want the array to be?"
setArray(lengde);
fyllArray();
for(int i = 0; i < array.length; i++){
if(antall < 5){
utskrift += array[i] + " ";
antall++;
}
else if(antall == 5){
utskrift += "\n" + array[i] + " ";
antall = 1;
}
}
utskrift += "\n";
utskrift += sjekkMin();
utskrift += "\n";
utskrift += sjekkMax();
utskrift += "\n";
String gsnitt = df.format(gjennomsnitt());
utskrift += "Snittet er: " + gsnitt;
showMessageDialog(null, utskrift);
}
}
public class oppgaveOblig3{
public static void main(String[] args){
new UnikeTall().kjorArray();
}
I would expect all the numbers in the array to be different. And that happens sometimes, but I believe that only happens when it works on the first try. When there is a matching number in the array, it stops.
But stopping, I mean the loop goes endless and my code stops at that point. Not getting any error codes because my program is still running
The sjekkArray method is supposed to check whether the value is already in your array, I think. Your problem is because you are using a object variable called likt in sjekkArray to pass the result of that test to the calling function fyllArray. But you fail to set likt to false at the beginning of sjekkArray. Because it's an object variable, once it is set to true, it will always stay true.
Make likt a local variable in sjekkArray and use the return value of sjekkArray in fyllArray.
In general, there are a lot of unnecessary complex ways of doing things in your code. It would be good if you could ask an experience programmer for guidance.
I need the second for loop to pick up where it left off. Every time the if statement is true I need a slot to fill in the array used in the first for loop. But I don't want the same key value to keep getting added. I need the second for loop to move to the next key value. (In the code below, arrl is an ArrayList of objects that have a value)
int temp = 0;
int count = 0;
for(int i = 0; i < eeVal.length; i++)
{
count= 0;
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1 && count == 0)
{
eeVal[i] = arrl.get(j);
count++;
temp=j;
}
}
}
}
return eeVal;
You need another variable to track where the inside loop has gotten to. Something like the following:
int temp = 0;
for(int i = 0; i < eeVal.length; i++)
{
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1)
{
eeVal[i] = arrl.get(j);
}
temp=j;
}
}
}
return eeVal;
This way, once the outside loop runs the second time around, the inside loop will start from 'temp' until the end of the loop.
From your explanation, it sounds like you do not want the inner for loop. The traversal of arrl needs to be manually controlled using a variable, e.g.`cnt', which only gets incremented when your condition for incrementing it is satisfied.
What you probably are looking for is a List.
In your answer, you don't need the first loop. This one has issues though - index i can go out of bounds.
int i = 0;
for(int j = 0; j < arrl.size(); j++) {
if(arrl.get(j).getValue() == 1) {
eeVal[i++] = arrl.get(j);
}
}
return eeVal;
What you need is a dynamic collections such as List.
Using list (I am calling the type as MyType).
List<MyType> vals = new ArrayList<>();
for(MyType item : arrl) {
if(item.getValue() == 1) {
vals.add(arrl.get(j));
}
}
return vals.toArray(new MyType[vals.size()]);
The code was picking up where the last correct value was. I needed to add 1 to j when I wanted progress to know where I left off.
int count2 = 0;
int progress = 0;
for(int i = 0; i < retVal[h].length; i++)
{
count2 = 0;
for(int j = progress; j < arr.size(); j++)
{
if(arr.get(j).getLevel() == h && count2==0)
{
retVal[h][i] = arr.get(j);
count2++;
progress = j+1;
}
}
}
return retVal;
I am trying to write a program that:
1) asks for user input to create an array of 10 elements
2) checks to make sure the elements are distinct
3) identifies the highest value among the elements.
I think Im close but I keep receiving this error message:
error: variable i is already defined in method main(String[])
for (int i = 0; i < myList.length; i++) {
Here is my full code:
import java.util.Scanner;
public class max101 {
public static void main(String[] args) {
double[] myList = new double[10];
double max = myList[0];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " distinct numbers: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble ();
for(int i = 0; i <myList.length; i++) {
for(int j = i+1; j<myList.length; j++) {
if(myList[i] == (myList[j])); {
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if(myList[i] != (myList[j])); {
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
}
}
Try using different variable names in your loops
If you dont want to do the above dont reinitialize the variable with int just put i = 0
It might also be useful to look into how scope works.
My suspicion is you’re not ending your blocks properly — a block meaning from { to }. When I have my IDE indent your code, it is:
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
for (int i = 0; i < myList.length; i++) {
for (int j = i + 1; j < myList.length; j++) {
if (myList[i] == (myList[j]))
;
{
System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers");
}
if (myList[i] != (myList[j]))
;
{
for (int i = 0; i < myList.length; i++) {
if (myList[i] > max)
max = myList[i];
System.out.println("The maximum value is " + max);
}
}
}
}
I think you see now that i is declared inside a for loop that already declares i. Also once you’ve detected a duplicate I think you should break out of the two loops rather than checking for more duplicates, and not find a max until the user has entered 10 new numbers.
One more tip, don’t put a semicolon after your if ( … ), it breaks your logic.
for (int i = 0; i < 6; i++) {
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null,"");
if (lineOne[i] > 47 || lineOne[i] < 1)//Number also have to be inside these parameters
JOptionPane.showMessageDialog(null, "Please try again!!!");
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
}
}
Instead of using an array use a Set.
Example:
Set<Integer> numbers=new HashSet<>();
Then add the numbers to the set. It will not allow duplicates.
boolean b = true;
int[] lineOne = new int[6];
for (int i = 0; i < 6; i++) {
b = true;
int k = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
for (int j : lineOne) {
if (k == j) {
System.out.println("error");
b = false;
break;
}
}
if (b && k < 47 && k > 1) {
lineOne[i] = k;
} else {
JOptionPane.showInputDialog(null, "Duplicate value or value out of bounds.");
i--;
}
}
this is the best way i could think of. boolean determines whether or not the value already exists
The issue is with your if-statement. The way the code is written if the entered value is outside the 1-47 range, you asked for the value again. But if, again, an "incorrect" value is given, you keep it in the array and go back to the top of the for-loop.
Try this.
for (int i = 0; i < 6; i++) {
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null,"");
while (lineOne[i] > 47 || lineOne[i] < 1) { //Number also have to be inside these parameters
JOptionPane.showMessageDialog(null, "Please try again!!!");
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
}
}
I am having with my studies, I have problem where I am supposed to get an IP address from an user and then iterate it from right most number and if that number will be equal or more than 256 then I should iterate the number -1 place before this and this one set to 0.
I tried to solve it by simply making primitive code at first which would do it one time and only by user input and after that I would add more complexity like original more than one iteration, error checks and put code into propper .java files and classes.
I understand that this would be better with ArrayList but I intended to add ArrayList instead of simple Array later.
Could anyone please tell me why the loop with condition put outofarraybound exception when I am not trying to iterate "i"?
for (i = 3; i >= 0; i--) {
pomoc = zasobnikIPadresa[i];
if (pomoc > 255) {
zasobnikIPadresa[i] = 0;
zasobnikIPadresa[i-1] = pomoc + 1;
}
}
So far I was able to analyze that I dont have proper knowledge of Arrays and I think that solution to my issue would help me to finish my problem and to better understand them.
here is full code so far:
package com.ipadresa.classes;
import java.util.Scanner;
public class Hlavni {
public static void main(String[] args) {
int i = 0;
int[] zasobnikIPadresa = new int[4];
Scanner ctecka = new Scanner(System.in);
for (i = 0; i < zasobnikIPadresa.length; i++) {
zasobnikIPadresa[i] = ctecka.nextInt();
}
System.out.print("Original IP adress: ");
for (i = 0; i < zasobnikIPadresa.length; i++) {
if (i < zasobnikIPadresa.length - 1) {
System.out.print(zasobnikIPadresa[i] + ".");
} else {
System.out.print(zasobnikIPadresa[i]);
}
} System.out.println();
int pomoc = 0;
for (i = 3; i >= 0; i--) {
pomoc = zasobnikIPadresa[i];
if (pomoc > 255) {
zasobnikIPadresa[i] = 0;
zasobnikIPadresa[i-1] = pomoc + 1;
}
}
System.out.print("Final IP adress: ");
for (i = 0; i < zasobnikIPadresa.length; i++) {
if (i < zasobnikIPadresa.length - 1) {
System.out.print(zasobnikIPadresa[i] + ".");
} else {
System.out.print(zasobnikIPadresa[i]);
}
}
ctecka.close();
}
}
Since by this for loop condition, for (i = 3; i >= 0; i--) {, the variable i is allowed to == 0, then let's see what the array index is here when i is 0:
zasobnikIPadresa[i-1] = pomoc + 1;
it's -1. Ouch.
What if the condition
pomoc > 255
is true when
i==0.
Then you'll be accessing zasobnikIPadresa[-1] i.e. out of bound.