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");
Related
Here are the instructions:
Exercise 2
Write a program in a single file that:
Main:
Creates 10 random doubles, all between 1 and 11,
Calls a method that writes 10 random doubles to a text file, one number per line.
Calls a method that reads the text file and displays all the doubles and their sum accurate to two decimal places.
SAMPLE OUTPUT
10.6269119604172
2.737790338909455
5.427925738865128
1.3742058065472509
1.1858700262498836
4.180391276485228
4.910969998930675
5.710858234343958
7.790857007373052
3.1806714736219543
The total is 47.13
I have it all written but nothing is coming out on the txt file. I need help with the second method because I think I need to change something but I'm not sure what.
public class Program2 {
public static void main(String[] args) {
double[] nums = new double[10];
for (int i = 0; i < nums.length; i++) {
nums[i] = 1 + Math.random() * 11;
}
printNum(nums);
sumNum(nums);
}
public static void printNum(double[] values) {
try {
java.io.File randomNums = new java.io.File("Project1.txt");
randomNums.createNewFile();
java.io.PrintWriter output = new java.io.PrintWriter(randomNums);
for (int i = 0; i < values.length; i++) {
output.println(i);
}
}
catch (Exception ex) {
System.out.print("EX");
}
}
public static void sumNum(double[] ints) {
Scanner input = new Scanner("Project1.txt");
double sum = 0;
for (int i = 0; i < ints.length; i++) {
sum = sum + i;
}
System.out.printf("\n%-.2f", "The total is ", sum);
input.close();
}
}
Method printNum
There are two reasons why you may see no output in the file: Some error occurred or the file is not flushed/closed by the time you read from it.
Be sure to flush and close the PrintWriter before leaving the method:
output.flush();
output.close();
In case some error occurs, you just print EX, hiding what is actually going on. So use this catch block:
catch (Exception ex) {
System.out.print("EX");
ex.printStackTrace(System.out);
}
Read what the program is trying to tell you.
And last but not least: You are not printing the random numbers but the loop count. Use this:
for (int i = 0; i < values.length; i++) {
output.println(values[i]);
}
Method sumNum
You need to open the file for reading. Your line does not do it:
Scanner input = new Scanner("Project1.txt");
Use this instead:
Scanner input = new Scanner(new File("Project1.txt"));
Next, you are not reading from the scanner. Inside your loop use
sum = sum + input.nextDouble();
input.nextLine();
Finally you need to print the result, as mentioned by OldProgrammer:
System.out.printf("The total is %f", sum);
Main method
The random numbers you generate are not in the defined range. You can figure this out.
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.
I'm trying to build a N x N matrix that will print with 0's and 1's. It shows no errors in the code, but when I run my code I get
Exception in thread "main" java.lang.NumberFormatException: null
I have no idea how to fix it.
public class LargestRowColumn {
public static void printMatrix (int n){
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
System.out.println((int)(Math.random() * 2)+ " ");
}
System.out.println("\n");
}
}
public static void main(String[] args) {
System.out.println("Enter a number");
String Matrix = null;
int n = Integer.parseInt(Matrix);
System.out.print(n);
}
}
It means you are trying to parse null as an int :
String Matrix = null;
int n = Integer.parseInt(Matrix);
You probably want to get some input from the user.
you are trying to convert null to integer
String Matrix = null;
Integer.parseInt(Matrix); // here is exception
if you want input from user then do like this:
int matrix=new Scanner(System.in).nextInt();
printMatrix(matrix); // print matrix
If you want to get input from the user, Scanner Class is the best way. To use it, write code like:
import java.util.Scanner; //since JAVA SE 7
public class AnyClass{
public static void main(String[] a){
Scanner scan = new Scanner(System.in);
//telling Scanner Class to proceed with input Stream
System.out.println("Enter a number");
int n = scan.nextInt(); //getting a number from the user
}
}
And for writing good code, try to use try and catch blocks for catching Exception(s).
You can enclose your code present in main() method in this example in try block followed by one or more catch block for catching the Exception and to deal with it.
This is a homework assignment.
I am prompting the user to input any amount of numbers, followed by a word. Because I do not know the amount of numbers that will be input, I am storing them in a String[], then moving them to an ArrayList.
I am storing the input correctly into the String[] by splitting the scanner input at white spaces.
Now I am attempting to add the contents of a String[] into an ArrayList with the following:
int i = 0;
for ( i = 0; i < inputToStringArray.length; i++) {
if(values.add(Double.parseDouble(inputToStringArray[i]))){ //if you can parse a double, parse a double
values.add(Double.parseDouble(inputToStringArray[i]));
}
}
Because I do not want the word at the end of the input, I am parsing the String[] for doubles.
Problem is, the ArrayList copies each number, storing it twice consecutively.
An input of 1, 2.2, 3.3 will store as 1.0, 1.0, 2.2, 2.2, 3.3, 3.3.
Why?
Basically, if List#add returns true, you're adding it again...
if(values.add(Double.parseDouble(inputToStringArray[i]))){ //if you can parse a double, parse a double
values.add(Double.parseDouble(inputToStringArray[i]));
}
Which basically says...
if add(value) {
add(value) // again...
}
Something like...
for ( i = 0; i < inputToStringArray.length; i++) {
try {
values.add(Double.parseDouble(inputToStringArray[i]));
} catch (NumberFormatException exp) {
System.err.println(inputToStringArray[i] + " is not a valid double");
}
}
May work better...
Because you are adding it twice! Your If statement is attempting to add it to values, then if it succeeds, you are adding it again.
Try something like this:
int i = 0;
for ( i = 0; i < inputToStringArray.length; i++) {
try {
values.add(Double.parseDouble(inputToStringArray[i]));
} catch (NumberFormatException e) {
// not a number!
e.printStackTrace();
}
}
a) In fact you call the method values.add() twice (you don't need it on the if clause).
b) You may encounter an exception if the string value is not a number, you should catch this
You should use something like this:
for ( int i = 0; i < inputToStringArray.length; i++) {
try {
values.add(Double.parseDouble(inputToStringArray[i]));
} catch (NumberFormatException e){}
}
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);
}