Java Scanner .nextInt() skipping inputs - java

Java novice here, trying to scan through the input in the form below:
3
3 3
101
000
101
1 2
11
5 5
10001
00000
00000
00000
10001
(The first digit is the number of test cases, followed by row and column, and 0s and 1s is the state of the world, and so on. Basically, like any typical BFS questions)
Below is a part of my Java code where I'm trying to get the input from the console. The comments are the values I see in the watch section while debugging:
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // t: 3, in.nextInt(): 3 as expected
for (int i = 1; i <= t; i++) { // i: 1, t: 3, in.nextInt(): 3 (not sure which "3")
int row = in.nextInt();
// after this line in.nextInt(): 101 and row: 0 which are all WEIRD
int column = in.nextInt();
// now here it's in.nextInt(): 2 and column: 2
int world[][] = new int[row][column];
// in.nextInt(): 11 now and as we see it changed its value when I didn't even call it
TreeMap<Integer, ArrayList<int[]>> distancesRandAcc = new TreeMap<Integer, ArrayList<int[]>>();
distancesRandAcc.put(0, new ArrayList<int[]>());
for (int j = 0; j < row; j++) {
int temp = in.nextInt();
char[] s = Integer.toString(temp).toCharArray();
for (int k = 0; k < column; k++){
world[j][k] = Character.getNumericValue(s[k]);
}
}
int result = calculateDeliveryTime(world, row, column, distancesRandAcc);
System.out.println("Case #" + i + ": " + result);
}
}
This does something weird that goes beyond 'common sense'. I was debugging line by line after putting all the inputs in the IntelliJ console and it seemed like in.nextInt() can't stop getting a random number of tokens at random lines regardless of whether I even called it or not.
When I tried to put the inputs line by line as well while debugging line by line and it seemed like one call of .nextInt is asking for two int values. (I typed in a number and entered but it still waited for another input while staying in the same line where .nextInt() is just called just once)
At this point, I'm getting the feeling that my debugging process is wrong or at least it's some external problems rather than the code itself. I might be wrong as I still consider myself a novice...
Please, could somebody more experienced teach me how to get around this problem? I found a few questions having similar-looking problems with .nextLine() and .nextInt() but not exactly this. I apologise in advance if it's really a duplicate, though...
(I'll add more info if needed)

You are calling nextInt(), so input 000 is parsed as the number 0 and the int return value is therefore 0. Integer.toString() will therefore return the string "0". Why are you surprised about that?
Since you don't actually care about the input as a number, just use next:
for (int j = 0; j < row; j++) {
String s = in.next();
for (int k = 0; k < column; k++) {
world[j][k] = Character.getNumericValue(s.charAt(k));
}
}
UPDATE
That is the only problem with the question code for reading the input. Whether there is a problem in the calculateDeliveryTime is unknown.
See IDEONE for proof. The calculateDeliveryTime method simply prints the 2D array, so it can be seen that the input has been handle ok.

Related

Why is the last line not being scanned

I want to scan some lines of number. The lines with single number num represent how many rows there will be for the 2d array, and the next num lines will consist of 2 numbers and they should be recorded in the array called townCord.
An example input looks like this:
4
1 2
2 1
1 1
2 2
3
3 1
2 2
1 3
The last line, 1 3, is not in the 2d array though. I think the reason is because I split by the pattern " ". I wonder how I can fix this bug and record all of them in the array? Thanks in advance
public static boolean checkWin(int x1,int y1, int x2, int y2){
if(y1==y2){
return false;
} else{
if(Math.toDegrees(Math.atan((Math.abs((double)(y1-y2)))/(Math.abs((double)(x1-x2)))))==45){
return true;
}else{
return false;
}
}
}
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
int num = Integer.parseInt(sc.nextLine());
int townCord[][] = new int[num][2];
for (int i = 0; i < townCord.length; i++) {
if(sc.hasNext()){
String[] line = sc.nextLine().trim().split(" ");
for (int j = 0; j < line.length; j++) {
townCord[i][j] = Integer.parseInt(line[j]);
}
}else{
break;
}
}
double overallCount = 0;
double winCount = 0;
for (int i = 0; i<num;i++){
for(int j = 0;j<num;j++){
overallCount++;
if(checkWin(townCord[i][0],townCord[i][1],townCord[j][0],townCord[j][1])){
winCount++;
}
}
}
System.out.println(winCount/overallCount);
}
sc.close();
}
EDIT: I think this is not working properly, because unless I hit enter after entering these numbers, I do not get the correct result.
output should be 2 numbers, yet it only prints one. I think by hitting enter, I add an extra line after the last 1 3 input, which makes the code working. Without doing that I only get 0.25, one number.
The input must be fixed and I cannot add anything to it. If you try to directly copy&paste the whole input thingy, it probably won't work.
EDIT 2: I posted full code and hopefully I did not make any stupid mistakes on the part that's not relevant to the scanner

split the numbers and add them together code is not working properly, What is it am doing wrong?

I wrote the below code to split the numbers and add them together, it is working fine if my number is not starting with 1 eg, 123456 -- not working, 234567 -- working, can anyone tell me what I am doing wrong here?
public class Basic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sum =0;
for (int i = 0; i <input; i++) {
int A = input%10;
System.out.println("test1 " +A);
input = input/10;
System.out.println("test " +input);
sum = sum + A;
}
System.out.println(sum);
}
It's the loop:
for (int i = 0; i <input; i++) {
You are dividing the int input into its digits. So the loop should run until all digits are eaten up:
while (input > 0) {
That should fix it
In every iteration, you're updating input, so for example, step by step:
input = 123
i = 0
sum = 0
input = 12
i = 1
sum = 3
input = 1
i = 2
sum = 5
Then check the condition i < input it's 2 < 1, it's not, so it's skipping the last digit, the same happens for 234 it returns 7 rather than 9, because of the same thing.
You could change your for-loop for a do-while:
do {
//Your code here
} while (input > 0);
The problem is in i < input; i++ in your loop. It's not problem with only numbers starting with 1, for example 23445352 isn't work correctly too. I see 26 instead of 28.
Check the next steps in the loop, for 123 input, after two steps, you have sum = 5, input = 1 and... i = 2. So the condition for exiting the loop returns true without considering the last digit.

Add asterisk when number is in range

this is my first time using this site so sorry if I do something wrong,
Here's an example output of the program I'm working on, basically what's supposed to happening
1-10 |**
11-20 |****
21-30 |***
31-40 |
41-50 |******
It goes on like that till the range of 91-100. This is my code so far, I've had a couple of different ideas so the code is incomplete in some parts but I really don't know which direction to go.
import java.util.Scanner;
public class HowMany
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
int range1 = 0;
int range2 = 0;
int range3 = 0;
int range4 = 0;
int range5 = 0;
int range6 = 0;
int range7 = 0;
int range8 = 0;
int range9 = 0;
int range10 = 0;
System.out.println("Enter integers between 1 and 100 (inclusive).");
System.out.println("Enter an integer out of the range to stop.");
//Assigning the user input a variable
int userNum = input.nextInt();
while(userNum >= 1 || userNum <= 100)
{
for (int i = 0; i < value; i++)
System.out.print("*");
if(userNum >= 1 && userNum <= 10)
}
}
}
Any help will be appreciated and if I haven't mentioned anything that I should specify let me know
Thanks
I don't think it would be beneficial for you if I just write you the program because this looks like exercise or homework, so let's work this out together. The program should run like this:
USER INPUT
If: 1..100 => PUT in the correct range and do 1)
Quit
The first observation is that
int userNum = input.nextInt();
needs to happen inside a loop, called the event loop. The structure is one big loop, that does the steps as stated above.
Now there is a better way to keep track of the ranges. Whenever you see yourself writing variables like var1, var2... you are better off with an array of values. The best would be to use an array of integers, where each index represents one range, something like this:
[0] 1-10
[1] 11-20
[2] 21-30 ...
and then you can just increment the correct index.
For instance, the user types in 34, you work out with the modulo operator where it goes and insert it.
Then I am sure you can find a smart way to print the final string. The best would be to create a separate print function for the array, something like:
printCounts(int[] count) { ... }
Hope those help, feel free to ask follow-up questions :)

Count of random numbers from a string java

This is a homework problem with a rule that we cant use arrays.
I have to make a program that will generate ten random numbers , append it to a string with a comma after each number.
I then have to give a count of each random number and remove the highest frequency number from the string.
The only issue i cannot solve is how to give a count of each number.
Lets say the string is "1,1,2,4,5,6,6,2,1,1" or "1124566211" with the commas removed.
How can I go about an output something like
1 = 4
2 = 2
4 = 1
5 = 1
6 = 2
Removing all numbers of max frequency
245662
Where the left side is the number and the right is the count.
EDIT: Range is 1 between 10, exclusing 10. It is testing the frequency of each digit i.e. how many times does 1 appear, how many times does 2 appear etc. Also its due tonight and my prof doesnt answer that fast :/
I would use a HashMap. A string representation of the num will be used as the key and you will have an Integer value representing the frequency it occurs.
Loop through the string of nums and put them to the HashMap, if the num already exists in the map, update the value to be the (current value + 1).
Then you can iterate through this map and keep track of the current max, at the end of this process you can find out which nums appear most frequently.
Note: HashMap uses Arrays under the covers, so clarify with your teacher if this is acceptable...
Start with an empty string and append as you go, check frequency with regex. IDK what else to tell you. But yeah, considering that a string is pretty much just an array of characters it's kinda dumb.
You can first say that the most common integer is 0, then compare it with the others one by one, replacing the oldest one with the newest one if it written more times, finally you just rewritte the string without the most written number.
Not the most efficient and clean method, but it works as an example!
String Text = "1124566211"; // Here you define the string to check
int maxNumber = 0;
int maxNumberQuantity = 0; // You define the counters for the digit and the amount of times repeated
//You define the loop and check for every integer from 0 to 9
int textLength = Text.length();
for(int i = 0; i < 10; i ++) {
int localQuantity = 0; //You define the amount of times the current digit is written
for(int ii = 0; ii < textLength; ii ++) {
if(Text.substring(ii, ii+1).equals(String.valueOf(i)))
localQuantity ++;
}
//If it is bigger than the previous one you replace it
//Note that if there are two or more digits with the same amount it will just take the smallest one
if(localQuantity > maxNumberQuantity) {
maxNumber = i;
maxNumberQuantity = localQuantity;
}
}
//Then you create the new text without the most written character
String NewText = "";
for(int i = 0; i < textLength; i ++) {
if(!Text.substring(i,i+1).equals(String.valueOf(maxNumber))) {
NewText += Text.charAt(i);
}
}
//You print it
System.out.println(NewText);
This should help to give you a count for each char. I typed it quickly off the top of my head, but hopefully it at least conveys the concept. Keep in mind that, at this point, it is loosely typed and definately not OO. In fact, it is little more than pseudo. This was done intentionally. As you convert to proper Java, I am hoping that you will be able to get a grasp of what is happening. Otherwise, there is no point in the assignment.
function findFrequencyOfChars(str){
for (i=0; i<str; i++){
// Start by looping through each char. On each pass a different char is
// assigned to lettetA
letterA = str.charAt(i);
freq = -1;
for (j=0; j<str; j++){
// For each iteration of outer loop, this loops through each char,
// assigns it to letterB, and compares it to current value of
// letterA.
letterB = str.charAt(j);
if(letterA === letterB){
freq++
}
}
System.Out.PrintLn("the letter " + letterA + " occurs " + freq +" times in your string.")
}
}

Plus Multiply | December Long Challenge Division 2

The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one integer ― the desired number of pairs.
Example Input
2
3
2 4 2
3
0 2 3
Example Output
1
0
My solution looks like:
class Codechef {
public static void main (String[] args) throws java.lang.Exception {
ArrayList<Integer> resultList = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
int T;
T = scanner.nextInt();
for(int i = 0; i < T; i++) {
int N;
N = scanner.nextInt();
int A[] = new int[N];
for(int j = 0; j < N; j++) {
A[j] = scanner.nextInt();
}
quick_sort(A, 0, N-1);
int pos = 0, pairs = 0;
while(pos < A.length - 1) {
if(A[pos] == A[pos + 1]) {
pos += 2;
pairs += 1;
} else {
++pos;
}
}
resultList.add(pairs);
}
for(int pairCount : resultList) {
System.out.println(pairCount);
}
scanner.close();
}
}
It successfully runs the example test cases but fails on submission, My question is, if the input is something like 1 1 2 2 1, then what should be the answer, 3? as there are 2 pairs of 1, and 1 of 2's.
Also, what will be the suggested data structure to be used for this purpose, Java with primitive data types is taking too much longer to execute it with 40,000 input values. What's wrong with my solution
To answer your first question, I'd say yes that each pair of 1's would count separately so you'd get 3.
I think your code is failing since you're only counting touching pairs after you sort.
For example,
1 1 1, you find the first pair at index 0/1, but then advance pos += 2.This means you're missing the two other pairs of 1's.
Your solution seems to be O(nlogn) because of sorting but I can think of a O(n) solution.
int[] backing = new int [10];
for (int j = 0; j < N; j++) {
int x = scanner.nextInt();
backing[x]++;
}
//At this point, you have a backing array with the frequency of each integer
You'll want something similar to this to calculate the number of pairs. It's the frequency of each integer choose 2, since you want to choose each occurrence of a pair.
So for example if you know you have 5 1's, then you'll compute:
5!/(2!*3!) = 10

Categories

Resources