Scanner nextInt() inside a for loop - java

Class code
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList<ArrayList<Integer>> rows = new ArrayList<>();
for (int i = 0; i < n; i++) {
int d = in.nextInt();
ArrayList<Integer> row = new ArrayList<>();
for (int j = 0; j < d; j++) {
row.add(in.nextInt());
}
rows.add(row);
}
int q = in.nextInt();
for (int i = 0; i < q; i++) {
System.out.println("test");
int x = in.nextInt();
System.out.printf("test2");
int y = in.nextInt();
System.out.println("I dont get it");
try {
System.out.println(rows.get(x - 1).get(y - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("ERROR!");
}
}
}
}
with this imput
5
5 41 77 74 22 44
1 12
4 37 34 36 52
0
3 20 22 33
5
1 3
3 4
3 1
4 3
5 5
Result
74
52
37
ERROR!
ERROR!
I don't understand how nextInt() works in the last loop. Why do the lines "I dont get it", "test", "test2" never get printed?
Why is the try block executed at the end of the loop and not during the loop?
How could the stdout print 4 results at once?
Please help.

I can see below output with your input.
test
test2I dont get it
74
test
test2I dont get it
52
test
test2I dont get it
37
test
test2I dont get it
ERROR!
test
test2I dont get it
ERROR!
Just remove your .class and compile again and check.

Based on your Input
Output array --> rows=[[41, 77, 74, 22, 44], [12], [37, 34, 36, 52], [], [20, 22, 33]]
In the first three iterations its printing
rows[0][2]=74
rows[2][3]=52
rows[2][0]=37
rows[3][2]=Error
-->because in your output array third index is an empty array [] ,there is nothing in the second position

Related

My output seems to have extra spacing after each line is printed

Edit: I figured out what was wrong, when count hits 5, it stays at 5 until the first condition is hit then count changes. This results in the extra empty lines.
So my goal is for the output to be one line after the other but its not doing that.
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
}
if (count%5==0)
System.out.println();
}
}
}
This code is suppose to take integer values of n, m, a and b and displays all the numbers from n to m that are divisible by a but not divisible by b, and prints the results 5 numbers per line. So far I have got printing the numbers 5 times per line down but every time it out puts the next line, instead of immediately printing to the next line it skips some.
Here is what its suppose to do when n=10, m=50, a=2 and b=3:
10 14 16 20 22
26 28 32 34 38
40 44 46 50
Instead its printing this:
10 14 16 20 22
26 28 32 34 38
40 44 46 50
What am I doing wrong?
When count reaches a number that's divisible by 5, you continue iterating over i. In some of these iterations, count is not incremented, so it remains divis5 and you continue adding new lines.
Moving the second if statement inside the for loop should solve this:
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
if (count % 5 == 0) // Here!
System.out.println();
}
}
You forgot to consider that the count variable will not increase as long as you dont satisfy the first if block. The better way is to check if its equal to 5
print new line the set count = 0
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
}
if (count==5){
System.out.println();
count = 0;
}
}
}
}
When the count is 5 and the code is not entered to the first "if" the new line will be printed because the count will not be increased.
Please try:
public class Main {
public static void main(String[] args) {
int n=10,m=50,a=2,b=3;
int count = 0;
boolean is_new_line = false;
for (int i=n;i<=m;i++){
if(i%a==0&&i%b!=0) {
System.out.print(i + " ");
count++;
is_new_line = false;
}
if ((count%5==0) && (is_new_line==false)) {
System.out.println();
is_new_line = true;
}
}
}
}

Putting values from file separated by space into multi dimension array

I'm newbie and I don't know how to merge my parts of knowledge.
I have to make Algorithm looking for the longest rising sequence of numbers.
My file has 50 columns, every column has some random numbers separated with space.
I'm still trying to put them in Matrix or other multi dimension arrays but I don't know how.
This is my code:
import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;
public class reading {
public static void main(String[] args) {
double[][] numbers = new double[101][101];
int column = 0, row = 0;
try {
System.out.print("Enter the file name with extension : ");
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
for (int columns = 0; columns < 101; columns++) {
String input2 = input.nextLine();
StringTokenizer strToken = new StringTokenizer(input2);
int count = strToken.countTokens();
for (int rows = 0; rows < count; rows++) {
numbers[columns][rows] = Integer.parseInt((String) strToken.nextElement());// writing values to arrays
System.out.println(numbers[columns][rows]);// test
}
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// here someday will be algorithm
}
}
**Sorry guys for my poor english i'm trying to tell what i want but it's a little bit hard for me. :( I got file whit a lot of numbers and i have to found longest series of numbers from smaller to most bigger without replacing numbers **
little example from file "
45 -31 -21 -34 30 -2 12 21 -39 -46 -48 8 15 30 8 -48 29 12 11 -28 40 27 28 -45 2 50 8 28 14 47 -22 -20 27 16 43 -7 35 13 7 15 40 -42 23 -7 7 18
22 13 28 -33 -15 -46 12 -22 31 -33 39 34 -11 45 -25 -25 -50 48 31 -20 -25 -5 5
18 -36 -24 -17 10 24 21 -35 6 19 38 6 44 20 30 -49 -33 -44 9
37 -36 -18 2 -2 35 -2 45 -36 40 26 -42 -17 45 40 -31 -21 33 -4 -50 40 13 -50 11 12 37 -26 38 -31 7 30 4 32 -50 -7 -40 -12 27
17 -5 -11 41 -1 46 16 16 48 38 -49 10 1 25 39 26 -14 -50"
If you're trying to read whitespace-separated values, the easiest solution is probably just to use Scanner.next or one of the other next... functions (other than nextLine, like Scanner.nextInt, or Scanner.nextDouble in your case).
These functions use whitespace as a delimiter, so each subsequent call will return the next piece of text that's between some whitespace, and also convert it to the appropriate type, if applicable.
input = new Scanner(file);
for (int rows = 0; rows < numbers.length; rows++){
for (int columns = 0; columns < numbers[rows].length; columns++){
numbers[rows][columns] = input.nextDouble();
}
}
If you want each line in the file to be a row, the rows loop should be on the outside (consider that you want to start with row 0 and go through each column in the same way you'd start from line 0 and go through each value in that line).
This is not particularly robust (if there's something wrong with your data, it might still work or it might be hard to find where the problem is).
If you're looking for something more robust, I might recommend something more like:
for (int rows = 0; rows < numbers.length; rows++){
String[] split = input.nextLine().split("\\s+"); // \\s+ is 1 or more whitespace characters
if (split.length != numbers.length) {
throw new IllegalArgumentException("Line " + rows + " has " + split.length + " columns, but needs " + numbers.length);
}
for (int columns = 0; columns < numbers[rows].length; columns++){
numbers[rows][columns] = Double.parseDouble(split[columns]);
}
}
In Java 8 we can achieve the same result like this:
final int DESIRED_ROW_LENGTH = 101;
for (int rows = 0; rows < numbers.length; rows++){
numbers[rows] = Arrays.stream(input.nextLine().split("\\s+"))
.mapToDouble(Double::parseDouble).toArray();
if (numbers[rows].length != DESIRED_ROW_LENGTH) {
throw new IllegalArgumentException("Line " + rows + " has " + numbers[rows].length + " columns, but needs " + DESIRED_ROW_LENGTH);
}
}
I'll provide an alternative* to #Dukeling answer on the premise that you are actually looking for some sort of algorithm for the longest rising sequence of numbers:
Basically, do it directly while reading the file, and just check each position of ((column + 1) - (column) == 1) and update a field if so.
File file = new File("\\\\share\\file\\path\\file.txt");
Scanner sc = new Scanner(file);
int totalCount = 0;
int tempCount = 0;
int tempLineNumber = 1;
int totalLineNumber = 0;
while (sc.hasNextLine()) {
String[] array = sc.nextLine().split("\\s+");
for (int i = 0; i < array.length - 1; i++) {
if (Integer.parseInt(array[i + 1]) - Integer.parseInt(array[i]) == 1) {
tempCount++;
}
}
if (totalCount < tempCount) {
totalCount = tempCount;
totalLineNumber = tempLineNumber;
}
tempCount = 0;
tempLineNumber++;
}
System.out.println("The max longest rising sequence of numbers is: "
+ totalCount + " at line " + totalLineNumber);
* I just threw this example together quickly, and most likely has an issue or two, such as missing edge cases etc
The actual algorithm happens on a one-dimensional array of integers.
So this could be done per line read from the file.
Path path = Paths.get(input.nextLine());
for (String line : Files.readAllLines(path, Charset.defaultCharset())) {
// Convert line into numbers:
String[] words = line.split(" ");
int[] numbers = new int[words.length];
for (int i = 0; i < numbers.length; ++i) {
numbers[i] = Integer.parseInt(words[i]);
}
// Find longest sequence in numbers array:
...
}
As other code here uses File and Scanner, I have given Path (newer alternative for File), and Files a utility class that has such nice methods like readAllLines.
Though you need no matrix, in general one does not use the typical math ordering, but line-by-line (by rows):
for (int row = 0; row < count; rows++) {
... read a line
for (int column = 0; column < 101; column++) {
numbers[row][column] = ...
System.out.print(numbers[row][column] + " ");
}
System.println();
}

sorted array in java using swap methods

My problem is when I sort a list it will get the last element of the array wrong, ending up with it at the beginning of the array. In my example it fails to sort the last element which is 9, ending up printed first ahead of small numbers such as 0 and 1. Here is my code:
public class ty {
public static void main(String[]argus){
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
int j;
for( int i=0;i<numbers.length;i+=1){
int first=0;
for(j=0;j<=i;j+=1){
if(numbers[j]>=first){
first=numbers[j];
numbers[j]=numbers[i];
numbers[i]=first;}
}//inner loop
}//first loop
for(int i=0;i<numbers.length;i+=1){
System.out.print(numbers[i]+" ");}
}
}
//the output is 9 0 1 4 23 23 34 45 56 66 545
As you see, they are in order except for the 9 at the start which is out of place.
You have the wrong output as a result of a logical error. You have mistakes in the Selection sort technique. Here's how to do it:
int []numbers={45,23,34,545,56,23,4,1,66,0,9};
for(int i=0; i<numbers.length-1; i+=1){
int m = i;
for(int j=i+1; j<numbers.length; j+=1){
if(numbers[m]>numbers[j])
m = j;
}
int temp = numbers[m];
numbers[m] = numbers[i];
numbers[i] = temp;
}
for(int i=0; i<numbers.length; i+=1)
System.out.print(numbers[i]+"\t");
This will work correctly and give the output:
0 1 4 9 23 23 34 45 56 66 545

For each loop won't print correctly

I'm not sure why this won't print out anything
for (int number : humidity)
{
if (sum < 12)
{
System.out.printf("%6d",humidity[sum]);
sum++;
}
}
Humidity is taken in from a file
Scanner inFileHumid = new Scanner(fileNameHumid);
int [] humidity = new int[length];
Then is set to the array
while (inFileHumid.hasNextInt())
{
humidity[n] = inFileHumid.nextInt( );
n++;
}
and the numbers from the file are 69 67 66 64 66 69 67 67 70 69 69 70 which are the ones I'm trying to get to be printed in my for each loop
You are iterating each number in humidity, but then you ignore those values and test some unrelated sum. I think you want
for (int number : humidity)
{
System.out.printf("%6d", number);
}
Or equivalently,
for (int sum = 0; sum < humidity.length; sum++)
{
System.out.printf("%6d", humidity[sum]);
}
I think you just have a problem indexing into humidity. So this should work.
for (int number : humidity){
if (number < 12) // Look at the value
{
System.out.printf("%6d", number); // Print what is in the array
}
}
Assuming sum is zero before the loop is entered, that code works.
int[] humidity = {1,2,3,4,5,6,7,8,9,0,1,2};
int sum= 0;
for (int number : humidity) {
if (sum < 12) {
System.out.printf("%6d", humidity[sum]);
sum++;
}
}
producing:
1 2 3 4 5 6 7 8 9 0 1 2
So for the code to fail sum must be greater or equal to 12 before the loop is entered.

Two dimensional array bug (can't find it)

I am doing this homework project that produces the pascals triangle but I'm getting an error and I can't find it. I looked it over many times but to me it seems okay, Can someone help me find the bug?
public class PascalsTriangle {
public static void main(String[] args) {
int[][] triangle = new int[11][];
fillIn(triangle);
print(triangle);
}
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.size(); i++) {
triangle[i] = new int[i++];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
}
public static void print(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
for (int j = 0; j < triangle[i].length; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
I assume you have already changed your code to use length instead of size as the other answer mentions.
When you call this method:
public static void fillIn(int[][] triangle) {
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i++]; // this line
triangle[i][0] = 1;
The line pointed out above should be:
triangle[i] = new int[i + 1];
When you call i++ the int array will be initialized with length i and then i will be incremented. You are already incrementing i in the declaration of your for loop. So, we take away the ++.
But then we have another problem. You start the loop at i = 0. Then you initialize an array with length 0. Then you add an element to that array. Something doesn't make sense. What you meant to do was to initialize the array as int[i + 1].
Finally the program displays some lines from Pascal's Triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
not sure this method exist
triangle.size()
try
triangle.length
instead

Categories

Resources