Debugging using console Input - java

How one would be able to debug the Java program using ecllipse IDE which takes the input using scanner. I have search this on google but doesn't find any appropriate solution. The problem is that I was stuck into an null pointer exception while reading the input , so I want to debug my program.
This is my program...
package p;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
int[][] ar = new int[T][];
for(int i=0;i<T;i++){
int n;
{
n = in.nextInt();
}
for(int j=0;j<n;j++)
{
ar[i][j]=in.nextInt(); /*null pointer exception occurs here*/
}
}
for(int i=0;i<T;i++)
{ int count=0,i1,k;
for(int j=1;j<ar[i].length;j++)
{
k=ar[i][j];
for(i1=j-1; i1>=0 && k<ar[i][i1]; i--)
ar[i][i1+1]=ar[i][i1];
ar[i][i1+1]=k;
count++;
}
System.out.println(count);
}
}
}

You never say(by initializing) how many cols will ar[i][j] will have (so accessing those uninitialized memory block surely gives NullPointerException
do this for all i rows
ar[i] = new int[colSize]
check this link as well

Check out a tutorial on debugging using eclipse.
You need to enter debugging mode after setting some break points. Break points are spots in your code you want the debugger to stop so you can view what's currently stored in various variables, etc.

Check the javadoc for Scanner and use the hasNext() methods to make sure it has the input you expect

Just put a break point where you want, then run it with Debug .It does not matter programme step contains Scanner or not. Even if you come across scanner statemenet, you just type a line on concole input, then enter. Programme will continue.

Related

How to solve NoSuchElement in java?

It works well on Intellij.
However, NoSuchElement appears on the algorithmic solution site.
I know that NoSuchElement is a problem caused by trying to receive it even though there is no value entered.
But I wrote it so that the problem of NoSuchElement doesn't occur.
Because given str, the for statement executes. Given "END", the if statement is executed. And because it ends with "break;".
I don't know what the problem is.
Algorithm problem: Arrange the reverse sentence correctly.
My code for algorithmic problems
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
Output
!edoc doog a tahW
erafraw enirambus detcirtsernu yraurbeF fo tsrif eht no nigeb ot dnetni eW
END
Expected
What a good code!
We intend to begin on the first of February unrestricted submarine warfare
This happens when there is no input at all, for example when you hit Ctrl + d or run your code like echo "" | java Main.java.
To avoid this, check that the Scanner actually has input before trying to grab the next line. Pull scan out of the loop, there is no point to create a new Scanner for each line anyway. Then use hasNext to see if there is input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String str = scan.nextLine();
if(str.equals("END")){
break;
}
for (int i = str.length()-1; i >=0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}

Why does my evenOdd code produce an output?

I'm a first year university student starting my computer science major so sorry for any rookie mistakes. We've just gotten to if/else statements and practice mostly on this website called "Practice-It!", a coding practice website for Java, C++, and Python although I'm currently learning Java. Now, I recently got to this problem called "evenOdd" in which we need to read an integer from the user and print "even" if its an even number or print "odd" if it's an odd number. The exact problem goes as follows:
Write Java code to read an integer from the user, then print even if that number is an even number or odd otherwise. You may assume that the user types a valid integer. The input/output should match the following example:
Type a number: 14
even
I'm pretty sure I know how to do this, but when I enter in my bare code, it produces no output. I'm unsure of why. My code goes as follows:
int number;
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
number = console.nextInt();
if (number % 2 == 0) {
    System.out.println("even");
} else  if (number % 2 != 0) {
    System.out.println("odd");
}
I should mention I'm supposed to put in bare code, meaning no class or methods.
I'm not sure if it's just me or maybe the website's slightly faulty. Any help is much appreciated.
Your code is sound, but if that is all the code you submit to the compiler then it won't work. You need to import the Scanner class from java.util.Scanner and you need to run your code inside a function and a class, unlike python which can run free in an IDE or console. Here is the code that worked for me.
import java.util.Scanner;
public class temp{
public static void main(String [] args){
int number;
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
number = console.nextInt();
if (number % 2 == 0) {
System.out.println("even");
} else if (number % 2 != 0) {
System.out.println("odd");
}
}
}
Hope that helps.
I would suggest you use some IDE like Eclipse or NetBeans. These IDEs will help you in writing and debugging your code. They will also mark errors in your code and also provide description and quick fix which will help you code.
package abc.xyz.test;
import java.util.Scanner;
public class EvenOdd
{
public static void main(String... args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
if (input.nextInt() % 2 == 0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}
input.close();
}
}
You can download eclipse from https://www.eclipse.org/downloads/ and NetBeans from https://netbeans.org/downloads/. Both of them are free, you don't have to pay anything for using them.
You need to import the scanner from java.util package. In every java program there must be a main method. try the following code. Look at my code i am creating an instance of Scanner named userInput and at the end of my code i am calling the close() method to prevent resource leak. you will not get any error for not closing but it is part of good practice.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int number = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Type a number");
number = userInput.nextInt();
if( number % 2 == 0 ) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
userInput.close();
}
}

Trying to make a balanced delimiter checker in java using stacks while getting input from the user

As talked about above I am trying to create a balanced delimiter checker in java. I have seen several examples of how to make one all of which were well done, but I have not found any that deal with having to get input from the user with the stack. I have looked into it, but I have not been able to find much with it. Below is what I have so far. I have been working on it but I have done more to confuse myself than anything else. Am I looking at this the right way? Or is there a better route to go about this?
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthensies
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
String line = input.nextLine();
Stack<Character> S = new Stack<Character>();
while(input.hasNext())
{
System.out.println("Enter: ");
Character z= input.nextLine();//this line is not working
S.push(z);
}
for (int i=0; i<line.length(); i++)
{
char c = line.charAt(i);
// do something with c
}
}
}

Getting Objects From A Text File

I have a text file like this;
7-Georgia
1-Andrew
6-John
8-Luke
9-Erica
3-Kim
2-Jude
5-Phil
4-Leo
The first column is id and second is name. How can I get these id's and names? So far I wrote this;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
#SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
#SuppressWarnings("unused")
Scanner fromFile = new Scanner(new File("id_name.txt"));
fromFile.useDelimiter("-");
while(fromFile.hasNext()){
String temp = fromFile.next();
System.out.println(temp);
}
while(fromFile.hasNext()){
String temp= fromFile.next();
int[] fileID;
fileID= new int[9];
for(int i=0; i<9; i++){
fileID[i]= Integer.parseInt(temp);
}
System.out.println(fileID);
}
}
}
But this doesn't get the id's. I'm not sure how to fix this, I'd be grateful if you help me.
You have two while loops in your code. Typically one while loop will go through every item until the condition is no longer true. I think you need to rework this to have a better "flow of control" which might mean using only one while loop (with sections to grab the number and then the name.
I imagine that you are looking for results from the second while loop, but by the time you get to it, the first while loop will have exhausted all of your data.
Finally, printing an array will print out the array reference identifier. If you want to actually print the contents of the array, you need a loop over the elements within the array, and you need to print out each array element explicitly.
As an alternative to the array printing technique above (which you should master), you can also use the Arrays.toString(<insert array here>) method call. However, in many cases it will give you a format that is not desired. That's why you need to know the above technique too.
Also, you have one hidden issue. You (in the second while loop) make the assumption that there are only nine inputs. Pay close attention to what you are writing. Every time you have to reach for a number, consider whether it is a "magic" number. Magic numbers are numbers that are in your code with no explanation or reason why they exist. They are indicators of errors in the code made by assumptions that probably won't last the test of time.
For example, you are using the number 9 because you have seen the input file. The next input file will probably not have nine entries in it, and your program will probably not work right if you gave it an input with eight entries, or an input with ten entries. Perhaps you should rewrite the loop to remove the magic number, by making the logic process while there is still (some) input.
Try this on for size
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
Scanner fromFile = new Scanner(new File("id_name.txt"));
} catch (FileNotFoundException e) {
System.err.println("File not found");
}
String[] arr = new String[9];
String[] oth = new String[9];
int i = 0;
while(fromFile.hasNextLine()) {
String temp = fromFile.nextLine();
oth[i] = temp.substring(0,1);
arr[i] = temp.substring(2);
i++;
}
int[] fileID;
fileID = new int[9];
for(int j = 0; j < 9; j++) {
fileID[j] = Integer.parseInt(oth[j]);
}
}
}
this should go through and retrieve the numbers(.substring(0,1)) and then the names(.substring(2)), and then converting the numbers to int values.
Try the following:
File file=new File("id_name.txt");
int[] fileID;
fileID= new int[9];
String[] result = file.nextLine().split("-");
for (int x = 0; x < result.length; x++){
if (Character.isDigit(result[x])) { // use the isDigit method to get the ids
System.out.println("this is an id");
fileID[i]= Integer.parseInt(result[x]);
}
Actually my friend, there are several mistakes here.
1) When the first while loop completes, it leaves fromfile.hasNext() as false Hence the second loop never starts.
>> To fix this, You need to put it all in one while loop.
2) fileID is an array. You cannot print it using System.out.println(fileID).
>> You have to tell what kind of output you want. The code will depend on that. For simply printing all the values, you need to make a for loop that prints each value separartely. You should use fileID.length for the no. of times you need to loop it.
3) Basically, fromfile.next() is not the way to do it.
>> You need to use fromfile.nextLine().

Infinite loop with integer text file reading in Java

Hi I have a fairly simple program but I am having trouble understanding why I have an inifite loop when I am running it. The file I am reading from has 10 integers in it. I am using Eclipse Juno and the output in the console is counting by 1 starting at 281363 infinitely. How can I fix this? Thanks in advance.
import java.util.*;
import java.io.*;
public class TestScoreAnalyzer
{
public static void main(String[] args) throws FileNotFoundException
{
int arraySize = 0;
File file = new File("C:\\Users\\Quinn\\workspace\\CPS121\\src\\
additionalAssignments\\scoresSample.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNextInt())
{
arraySize++;
System.out.println(arraySize);
}
inputFile.close();
}
}
You're never calling inputFile.nextInt() - you're only calling hasNextInt(), which doesn't actually advance the location in the file. You probably want:
while (inputFile.hasNextInt())
{
arraySize++;
System.out.println(arraySize);
int value = inputFile.nextInt();
// Do something with the value?
}
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt()
Scanner isnt moving on - its just saying the next one is an int (looks at the same one each time)

Categories