I have this piece of code :
import java.util.*;
class HelloWorld {
public static void main(String args[]) {
Scanner ob = new Scanner(System.in);
int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not
int a = 0, c = 0;
for (int j = 0; j < t; j++)
{
a = 0; c = 0;
String str = ob.nextLine();
String [] spstr = str.split("\\s+");
try
{
for (int i=0 ; i<spstr.length ; i++)
{
if(spstr[i].equals("")) {i--;}
else {
c = c + Integer.parseInt(spstr[i]);
}
}
System.out.println(c);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
}
What this code do is add any no.s of integers in a single line. Before doing this, I have a Test Case int t. This decides how many inputs must be taken. But this results to an infinite loop even when I am entering integer value.
I have seen this post:
How to handle infinite loop caused by invalid input using Scanner which have many answers on how to get rid of this. I have followed the answers, but I have not yet solved this issue.
Note: When I use int t=5;, it works fine. But in this case too, if exception is caught twice, same thing happens.
Please tell me how to solve this infinite loop error ?
Thanks in Advance :)
Simply use ob.nextLine() to ignore it. I fixed the code for you and it works as it should. Your code had several issues which I have mentioned.
import java.util.*;
class HelloWorld {
public static void main(String args[]) {
Scanner ob = new Scanner(System.in);
int t = ob.nextInt();
ob.nextLine();
int a = 0, c = 0;
for (int j = 0; j < t; j++)
{
a = 0; c = 0;
String str = ob.nextLine();
if(str.trim().length()>0){
String [] spstr = str.trim().split("\\s+");
try
{
for (int i=0 ; i<spstr.length ; i++)
{
c = c + Integer.parseInt(spstr[i]);
}
System.out.println(c);
} catch (NumberFormatException e) {
System.out.println("Invalid Input");
}
}
}
}
}
if(spstr[i].equals("")) {i--;} is pointless and wrong logic in fact which will throw your program into an infinite loop. Simply trim the String and check if it is empty as I have done.
Do not simply catch Exception superclass. This is bad for debugging. The Exception raised here is NumberFormatException which you should catch.
To begin with, proper indentation helps make code easier to read.
class HelloWorld {
public static void main(String args[]) {
Scanner ob = new Scanner(System.in);
int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not
int a = 0, c = 0;
for (int j = 0; j < t; j++) {
a = 0;
c = 0;
String str = ob.nextLine();
String[] spstr = str.split("\\s+");
try {
for (int i = 0; i < spstr.length; i++) {
if (spstr[i].equals("")) {
i--;
} else {
c = c + Integer.parseInt(spstr[i]);
}
}
System.out.println(c);
} catch (Exception e) {
System.out.println("Invalid Input");
}
}
}
}
There's several problems.
int t = ob.nextInt(); //no. of Test Cases
ob.next(); // for next input whether exception occurs or not
I don't know what you're hoping to accomplish here. That is not what the linked answer has as a solution. The linked answer is referring to cases where the input is invalid and specifically references catching the exception like so:
try {
int x = ob.nextInt();
} catch (InputMismatchException e) {
ob.next();
}
Which I seriously doubt has anything to do with your problem unless you're intentionally entering bad data.
Then there's this, the most likely culprit considering it's a potential infinite loop at first blush.
for (int i = 0; i < spstr.length; i++) {
if (spstr[i].equals("")) {
i--;
} else {
c = c + Integer.parseInt(spstr[i]);
}
}
If i is 5 and spstr[i].equals("") returns true then i becomes 4, the else is skipped and i is incremented back to 5 ad infinitum.
Related
So I made this to print primes between two numbers of my choice; however, it prints out a comma after the last number and I don't know how to take it off.
Example
in: 0 10
out: 2, 3, 5, 7,
I want 2,3,5,7
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
for (int i = a; i <= b; i++){
int j;
for (j = 2; j<i; j++){
int p = i%j;
if(p==0){break;}
}
if(i == j){System.out.printf("%d,", i);}
}
}
Use a boolean to keep track of whether you've printed anything yet. Then your format string could be something like
anythingPrinted ? ",%d" : "%d"
That is, only include the comma in the format string if there's something printed.
Use a StringBuilder and write to the console at the end of your program.
StringBuilder sb = new StringBuilder();
for (int i = a; i <= b; i++){
int j;
for (j = 2; j<i; j++){
int p = i%j;
if(p==0){break;}
}
if(i == j){
// If the length of the StringBuilder is 0, no need for a comma
if(sb.length() != 0) {
sb.append(",");
}
sb.append(i);
}
}
System.out.println(sb);
This might seem like overkill, and for many cases it might be, but I have been writing a source code transcoder and I find this situation coming up a lot. Where I need commas in between values, or a prefix value which is only printed once. So I found it handy to create a class which simplifies things.
Again, you wouldn't probably want to use this if you code had one or two print loops in it, but maybe if you had more than a few. Perhaps you would remove in "on first" part if you were never going to use it.
public class FirstPrintOptions {
private PrintStream printStream;
private String onFirst;
private String remaining;
private boolean trip = false;
public FirstPrintOptions(PrintStream printStream, String onFirst, String remaining) {
this.printStream = printStream;
this.onFirst = onFirst;
this.remaining = remaining;
}
public void print() {
if (!trip) {
if (onFirst != null) {
printStream.print(onFirst);
}
trip = true;
} else {
if (remaining != null) {
printStream.print(remaining);
}
}
}
}
Then use it like this..
FirstPrintOptions firstPrintOptions = new FirstPrintOptions(System.out, null, ",");
for (int x=0;x<10;x++) {
firstPrintOptions.print();
System.out.print(x);
}
The results are..
0,1,2,3,4,5,6,7,8,9
I was testing and I came up with this. I was using compilejava.net so scanner doesn't work. I bypassed that part and just set a and b manually. Basically, it builds a string with the numbers and ends in a comma. Then it prints a substring including everything except the last comma.
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
//Scanner s = new Scanner(System.in);
int a = 2;
int b = 18;
String c = "Output = ";
for (int i = a; i <= b; i++){
int j;
for (j = 2; j<i; j++){
int p = i%j;
if(p==0){break;}
}
if(i == j){c=c+ Integer.toString(i) + ",";}
}
System.out.print(c.subSequence(0, c.length()-1));
}
}
this program for finding factors of a number
for(i=1;i<=number;i++)
{
if(number%i==0)
{
system.out.print(i);
if(i!=0)
{system.out.print(",");}
}
}
so i get the output for 10 as
1,2,5,10
I'm having difficulties with the output from the main method. If a used enters a bunch of random Strings, my program should get only integers and group them as a pair. For example, if a user enters 3 2 54 -5, the output should be:
(3,2)
(54,-5)
Or, another example: if the input is 1 2 3, the program should output only
(1,2)
because there would not be any other pair found for number 3. The main point of the program is to gather numbers into pairs. Exception is thrown if the program cannot convert a String into int. Could smb please help me out?
public static void main(String [] args) throws Exception
{
int [] number = new int [args.length];
try
{
for (int i = 0; i < args.length; i++)
{
number[i] = Integer.parseInt(args[i]);
System.out.println("("+i+","));
}
}
catch (NumberFormatException e)
{
System.out.println(e.getMessage());
}
}
I think what you can do is use the split method from the String class if you already know that the user will use that format, you cannot parse them because the user entered some spaces. If the data the user entered comes in the String array you can use something like:
public static void main(String [] args) throws Exception
{
int[] numbers = new int[args.length];
try
{
for (int i = 1; i < args.length; i+=2)
{
number[i-1] = Integer.parseInt(args[i-1].split(" ")[0];
number[i] = Integer.parseInt(args[i].split(" ")[0];
System.out.println("("+number[i-1]+","+number[i]+")");
}
}
catch (NumberFormatException e)
{
System.out.println(e.getMessage());
}
}
Also if you use the i+=2, as you can see in the for, then you start in 1 and it goes up 2 by 2. Then it works with itself and the previous number, guaranteeing that there will only be pairs
This'll work for you,
int[] number = new int[args.length];
try {
for (int i = 0; i < args.length; i++) {
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(args[i]);
if (m.find()) {
number[i] = Integer.parseInt(m.group());
System.out.print(number[i] + ",");
}
}
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
First of all, in order to loop through all of the inputs and not leave the loop the first time that a non-integer is hit, the try/catch block has to be inside of the for loop. Then, in order to take care of the fact that you want pairs of ints, you do not want to print out every time that you go through with an int, you want to print out only when a counter that starts at zero is odd. The counter is only incremented if an integer is found (when no exception is thrown). Finally, I believe that what you are saying is that you want to throw an exception only if no int pair is found, so this would be the case that the counter never passed one. So all of this can be handled as follows:
int count = 0;
for (int i = 0; i < args.length; i++)
{
try
{
number[count] = Integer.parseInt(args[i]);
if(count%2==1)
System.out.println("("+number[count-1]+","+number[count]+")");
count++;
}
catch (NumberFormatException e)
{
//if you're intention is to throw an exception if something other than an int is entered.
throw new Exception(e.getMessage());
}
}
if(count <= 1) throw new Exception("No int pair found");
I'm writing a method that checks to see if the text file being passed into the constructor of my instantiable class contains non-numeric data. Specifically, it matters if the data cannot be represented as a double. That is, chars are not okay, and integers are.
What I have so far is:
private boolean nonNumeric(double[][] grid) throws Exception {
boolean isNonNumeric = false;
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] != ) {
isNonNumeric = true;
throw new ParseException(null, 0);
} else {
isNonNumeric = false;
}
}
return isNonNumeric;
}
I cannot seem to find what I should be checking the current index of grid[i][j] against. As I understand it, typeOf only works on objects.
Any thoughts? Thank you.
Edit: Here is the code used to create the double[][] grid:
// Create a 2D array with the numbers found from first line of text
// file.
grid = new double[(int) row][(int) col]; // Casting to integers since
// the dimensions of the
// grid must be whole
// numbers.
// Use nested for loops to populate the 2D array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
if (scan.hasNext()) {
grid[i][j] = scan.nextDouble();
count++;
}
}
// Check and see if the rows and columns multiply to total values
if (row * col != count) {
throw new DataFormatException();
}
I come up with this sample for you, hope it helps.
It helps you to narrow down your entries types to any type that you are looking for.
My entry.txt include :
. ... 1.7 i am book 1.1 2.21 2 3222 2.9999 yellow 1-1 izak. izak, izak? .. -1.9
My code:
public class ReadingJustDouble {
public static void main(String[] args) {
File f = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects"
+ "\\ReadingJustString\\src\\readingjuststring\\entry.txt");
try (Scanner input = new Scanner(f);) {
while (input.hasNext()) {
String s = input.next();
if (isDouble(s) && s.contains(".")) {
System.out.println(Double.parseDouble(s));
} else {
}
}
} catch (Exception e) {
}
}
public static boolean isDouble(String str) {
double d = 0.0;
try {
d = Double.parseDouble(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
}
Output:
1.7
1.1
2.21
2.9999
-1.9
Note: my sources are as follows
1.http://www.tutorialspoint.com/java/lang/string_contains.htm
2.How to check if a String is numeric in Java
I'm trying to run this code but I keep getting an out of bounds error. This is just the sub class for the super class "Simpler." The user enters in a string then the string is broken down into a char array. The array should not be smaller than the string yet I am getting this error. Can you tell me what I'm doing wrong? Thanks!
import java.util.*;
public class Encrypt extends Simpler
{
public void encryption()
{
boolean loop = true;
while(loop==true)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the phrase you'd like to encrypt: ");
String inPhrase = scan.nextLine();
char[] chars = inPhrase.toCharArray();
char tempArray[] = new char[chars.length+1];
tempArray = chars;
chars = new char[tempArray.length];
for (int i = inPhrase.length(); i<inPhrase.length(); i--)
{
if(chars[i]=='a')
{
chars[i]='1';
}
else if(chars[i]=='b')
{
chars[i]='2';
}
else if(chars[i]=='c')
{
chars[i]='3';
}
else if(chars[i]=='d')
{
chars[i]='4';
}
else if(chars[i]=='z')//I skipped some lines here for convienence
{
chars[i]='{';
}
else if(chars[i]==' ')
{
chars[i]='}';
}
}
String outPhrase = new String(chars);
System.out.println(outPhrase);
}
}
}
I think your for loop statement should look like this:
for (int i = 0; i < inPhrase.length(); i++)
if you're counting up, and like this:
for (int i = inPhrase.length() - 1; i >= 0; i--)
if you're counting down.
update
On looking back over it, I think there is more to it than that though.
I think your code needs to be rewritten:
String inPhrase = scan.nextLine();
char[] chars = inPhrase.toCharArray();
char tempArray[] = new char[chars.length()];
for (int i = 0; i < chars.length(); i++)
{
if(chars[i]=='a')
{
tempArray[i]='1';
}
.
.
.
.
}
String outPhrase = new String(tempArray);
No stop condition in the for loop, in this line:
for (int i = inPhrase.length(); i<inPhrase.length(); i--)
i gets 1, 0, -1, ... and wouldn't stop if -1 wouldn't throw an out of bounds exception
In for loop just changing the condition from i < inPhrase.length() to i >= 0 will do the job.
First thing:
for (int i = inPhrase.length(); i<inPhrase.length(); i--)
you never enter your loop because you assign i = n & entry condition is i < n.
it should be
for (int i = inPhrase.length()-1; i>=0; i--)
Now, this also removes your arrayoutofbound exception because earlier, you tried to access chars[n] which is actually the n+1 th character of that array.
I have a 2-D int array in file 'array.txt'. I am trying to read all the elements in the file in a two dimensional array. I am having problem in copying. It shows all the elements having value '0' after copying instead their original value. Please help me.
My code is :
import java.util.*;
import java.lang.*;
import java.io.*;
public class appMainNineSix {
/**
* #param args
*/
public static void main(String[] args)
throws java.io.FileNotFoundException{
// TODO Auto-generated method stub
Scanner input = new Scanner (new File("src/array.txt"));
int m = 3;
int n = 5;
int[][] a = new int [m][n];
while (input.next()!=null){
for (int i=0;i<m;i++){
for (int j=0;j<n;j++)
a[i][j]= input.nextInt();
}
}
//print the input matrix
System.out.println("The input sorted matrix is : ");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
System.out.println(a[i][j]);
}
}
}
while (input.next()!=null)
This will consume something from the scanner input stream. Instead, try using while (input.hasNextInt())
Depending on how robust you want your code to be, you should also check inside the for loop that something is available to be read.
Scanner input = new Scanner (new File("src/array.txt"));
// pre-read in the number of rows/columns
int rows = 0;
int columns = 0;
while(input.hasNextLine())
{
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt())
{
++columns;
}
}
int[][] a = new int[rows][columns];
input.close();
// read in the data
input = new Scanner(new File("src/array.txt"));
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < columns; ++j)
{
if(input.hasNextInt())
{
a[i][j] = input.nextInt();
}
}
}
An alternative using ArrayLists (no pre-reading required):
// read in the data
ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
Scanner input = new Scanner(new File("src/array.txt"));
while(input.hasNextLine())
{
Scanner colReader = new Scanner(input.nextLine());
ArrayList col = new ArrayList();
while(colReader.hasNextInt())
{
col.add(colReader.nextInt());
}
a.add(col);
}
The problem is when u reach the end of the file it throughs an exception that no usch element exist.
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner input = new Scanner(new File("array.txt"));
int m = 3;
int n = 5;
int[][] a = new int[m][n];
while (input.hasNextLine()) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
try{// System.out.println("number is ");
a[i][j] = input.nextInt();
System.out.println("number is "+ a[i][j]);
}
catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
System.out.println("The input sorted matrix is : ");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println(a[i][j]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I knew that making catch without processing the exception but it temporary works.
Please be aware I put the file outside the source folder.
Well the problem may be that you've got that pair of nested loops to read the numbers stuck inside that while loop. Why would you want to re-read the array values after you've read them once? And note that if there's anything in the file after the last number, then you'll fill the array in with whatever .nextInt() returns after end-of-file has been reached!
edit — well .nextInt() should throw an exception I guess when input runs out, so that may not be the problem.
Start simple...
change:
for (int j=0;j<n;j++)
a[i][j]= input.nextInt();
to:
for (int j=0;j<n;j++)
{
int value;
value = input.nextInt();
a[i][j] = value;
System.out.println("value[" + i + "][" + j + " = " + value);
}
And make sure that the values are read in.
Also, you should not call next without first calling (and checking) hasNext (or nextInt/hasNextInt).
You can try Using Guava ,
public class MatrixFile {
private final int[][] matrix;
public MatrixFile(String filepath) {
// since we don't know how many rows there is going to be, we will
// create a list to hold dynamic arrays instead
List<int[]> dynamicMatrix = Lists.newArrayList();
try {
// use Guava to read file from resources folder
String content = Resources.toString(
Resources.getResource(filepath),
Charsets.UTF_8
);
Arrays.stream(content.split("\n"))
.forEach(line -> {
dynamicMatrix.add(
Arrays.stream(line.split(" "))
.mapToInt(Integer::parseInt)
.toArray()
);
});
} catch (IOException e) {
// in case of error, always log error!
System.err.println("MatrixFile has trouble reading file");
e.printStackTrace();
}
matrix = dynamicMatrix.stream().toArray(int[][]::new);
}