How to break correctlly in the array? - java

I have a question about break the input, because my code is typing two times "-1" to stop the input, actually I want to type "-1" single time to stop the input and then to show the array output.
Below is my code:
import java.util.Scanner;
public class NewTMA {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt(sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line break, end by -1:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++) {
for (int j=0; j<column; j++) {
String line = sc.nextLine();
if ("-1".equals(line)) {
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Below is my output:
run:
enter row size
3
enter column size
2
Type float numbers two-dimensional array of similar type and size with line breaks. end by -1:
1.4
2.4
-1
-1
The result is:
1.4 2.4
0.0 0.0
0.0 0.0
BUILD SUCCESSFUL (total time: 13 seconds)
Actually I just want to type "-1" a single time to stop the input,but I don't know why the output is showing "-1" twice to stop it. Hope someone can help me find which part I am doing wrong. Thanks.

break breaks out of the inner-most loop, so the outer loop iterates again and hits the input read again.
To break out of the outer loop, use a label:
outerLoop: // label the outer for loop
for (int i=0; i<row; i++){
for (int j=0; j<column; j++) {
String line = sc.nextLine();
if ("-1".equals(line)) {
break outerLoop; // break from the outer for loop
}
...
}
You can use any java allowable name for the label (I just called it “outerLoop” for clarity)

Another approach would be putting a flag as an indication if the argument is met:
for (int i=0; i<row; i++){
/* this is the flag */
boolean isInputNegative = false;
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
isInputNegative = true;
break;
}
a[i][j]=Float.parseFloat(line);
}
/* here is the checking part */
if (isInputNegative) {
break;
}
}

Related

Why this error of sorting occuring only in cases of >5 table elements?

please see my code for BubbleSorting. When I choose 5 or more numbers for my table to be sorted I get an error:
at first.firstt.sorting_v2.sorting(sorting_v2.java:35).
Completely do not know why it occured, when I choose 2 or three element to sort it works perfect.
I know it can be made different way, this type of sorting but please show me what I did wrong as still learn and I'm very curious about the details of this error hmm.
Also see the image below:enter image description here
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Choose how much number you want to sort:");
int sizeOfTab = scanner.nextInt();
int[] numbers = new int[sizeOfTab];
for (int i = 0; i < sizeOfTab; i++) {
System.out.println("Choose number to collection: ");
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println(Arrays.toString(sorting(numbers)));
}
private static int[] sorting(int[] numbers) {
boolean notDone = false;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
int tmp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = tmp;
notDone = true;
}
}
}
return notDone ? sorting(numbers) : numbers;
}
}
Your logical error is that you are always restarting your second inner loop from j = 1 aka the second element in
for (int j = 1; j < numbers.length; j++) { ... }
You only ever want to compare numbers[i] > numbers[j] for cases where j is greater than i.
Lets say you have the array [1, 2, 3, 4]
Currently your loop will run and reach a point where it will check numbers[2] > numbers[1] and switch the second and third element despite the array already being sorted.
To fix this simply always have your second loop start from the current value of i with 1 added:
for (int j = i+1; j < numbers.length; j++) { ... }

How to check if certain numbers appear in an array?

I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored
somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing.
So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
break;
}
else
{
System.out.println(currentNum + " doesn't appear in the array");
break;
}
}
}
}
To resolve your problem you should simply remove the have used in the else part of the array.
Consider a case like this
ex. 2 1 4 3
when checking for i=1 it will first compare the value with 2 so it will come out of the loop.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
int flag=0;
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("currentNum+"Doesn't appear in array");
}
}
}
When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this:
found_match = no
for (... in ...) {
if (match) {
found_match = yes
break
}
}
if (found_match) {
do_found_match_stuff();
}

Printing number in an array backwards

I am new to java and I wondering how I could fix my program which has to take numbers from user input, then store them in an array, and then print those numbers forwards and then backwards. I have managed to get the program to print forward; however, when I try to print it backwards I get
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at arrays4Days.arrayS1.main(arrayS1.java:55)
import java.util.*;
public class arrayS1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many numbers will you enter? ");
int count = console.nextInt();
int myArray[]= new int [count];
for (int i =0; i < myArray.length ; i++) {
System.out.print("Type a number: ");
int number=console.nextInt();
myArray[i]=number;
}
System.out.println();
System.out.println("Your numbers in forward order:");
for (int i = 0 ; i < myArray.length ; i++) {
System.out.println(myArray[i]);
}
System.out.println();
System.out.println("Your numbers in backward order:");
for (int i = myArray.length ; i> 0 ; i--) {
System.out.println(myArray[i]);
}
}
}
Note that in your first loop, i starts at zero and goes up to - but not equals - the length of the array
for (int i = 0 ; i < myArray.length ; i++) {
so the second loop should also start at this position
for (int i = myArray.length - 1; i>= 0 ; i--) {
System.out.println(myArray[i]);
}
and should go down to zero

Java array reading loop never ends?

Hi I am new to programming and today i was writing a code for one Java array task and in the beginning i tried just to test what i have done and in the first for loop (the array reading ) the program does not stop to read a numbers even i already enter a number (n) for its length. Please help ?
import java.util.Scanner;
public class ReadTwoElementsForArrayAndSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Please enter N element:");
int n = in.nextInt();
System.out.print("Please enter K element, for k < N: ");
int k = in.nextInt();
int[] arrayN = new int[n];
System.out.print("Please enter N numbers for the array: ");
for(int i = 0; i < arrayN.length; i++) {
arrayN[i] = in.nextInt();
}
boolean changed = false;
do {
int temp = 0;
for( int i = 0; i < (arrayN.length-1); i++) {
if(arrayN[i] > arrayN[i+1]){
temp = arrayN[i];
arrayN[i] = arrayN[i+1];
arrayN[i+1] = temp;
changed = true;
}
}
} while (changed);
for(int i = 0; i < arrayN.length; i ++) {
System.out.printf("%d", arrayN[i]);
System.out.print(k);
}
in.close();
}
}
Loop is infinite because once the if condition inside for loop is executed then changed is set to true and its value never changed to false causing infinite loop by do while loop.
Instead you can use Arrays.sort(arrayN) or if you want to use loop only then try below code
int count = 0;
do {
int temp = 0;
count++;
for (int i = 0; i < (arrayN.length - 1); i++) {
if (arrayN[i] > arrayN[i + 1]) {
temp = arrayN[i];
arrayN[i] = arrayN[i + 1];
arrayN[i + 1] = temp;
}
}
} while (count < (arrayN.length));
Demo
in this loop :
do {
int temp = 0;
for( int i = 0; i < (arrayN.length-1); i++) {
if(arrayN[i] > arrayN[i+1]){
temp = arrayN[i];
arrayN[i] = arrayN[i+1];
arrayN[i+1] = temp;
changed = true;
}
}
} while (changed);
you once change the changed to true and never make it false. If you want to end your loop you must some how(it depends on your approach) make changed false so it can end the loop.
what you should be doing in a do-while loop is
boolean flag=true;
do{
(some condition){
flag=false;
}
}while(flag)
this causes correct execution of do-while loop

2D array trouble finding char element(s)

I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.

Categories