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.
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.
This is my answer for half of half question in SPOJ( Question ID :12156) . I'm a beginner in JAVA. Please Help why am i getting an error. I'm able to get an expected answer while compiling in Ideone. Thanks
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan =new Scanner(System.in);
String[] name= new String[10];
int size,count;
String temp,news;
char[] chars= new char[20];
temp=scan.nextLine();
count=Integer.parseInt(temp);
for(int i=0;i<count;i++)
{
name[i]=scan.nextLine();
}
for(int j=0;j<count;j++)
{
news=name[j];
size=news.length();
chars=news.toCharArray();
for(int k=0;k<size/2;k=k+2)
{
System.out.print(chars[k]);
}
System.out.println();
}
}
}
Pay attention to the following points in the problem description:
In the first line of input your are given the positive integer t
(1 <= t <= 100) - the number of test cases.
In your code, you can handle 10 (and not 100) strings at maximum.
String[] name = new String[10];
In the each of the next t lines, you are given a sequence of 2*k
(1 <= k <= 100) characters.
In your code, you can handle 20 (and not 200) characters at maximum.
char[] chars = new char[20];
I did attempt same question half of half at SPOJ, my code is accepted.
I think array initialisation should be based on input.
import java.util.Scanner;
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
scan.nextLine();
String[] inputStringArray = new String[testCase];
for (int x = 0; x < testCase; x++) {
String input = scan.nextLine();
input = input.replaceAll("\\s+", "");
inputStringArray[x]=input;
System.out.println("#-"+x);
}
for(int y=0;y<testCase;y++){
String text = inputStringArray[y];
char[] inputArray = text.toCharArray();
int len = inputArray.length/2;
for(int z=0;z<len;z=z+2){
System.out.print(inputArray[z]);
}
System.out.println("");
}
}
}
I am making a program to a get a case input from the user and then store that case entry. However, I am getting an error during compilation,
demo576.java:44: error: incompatible types: String cannot be converted
to String [] h=z.Batman();
^ 1 error
the code is as follows:-
import java.util.Scanner;
class demo576
{
public static void main (String args[])
{
Scanner s=new Scanner (System.in);
fun z=new fun();
String x=z.Batman();
System.out.println(x);
int p=s.nextInt();
String h[]=new String[3];
int i;
for (i=0;i<3;i++)
{
h=z.Batman();
}
for(i=0;i<3;i++)
{
System.out.println(h);
}
}
}
I guess this should suffice:
for(int i=0; i<3; i++) {
h[i] = z.Batman();
}
Your print loop needs fixing:
for(int i=0;i<3;i++) {
System.out.println(h[i]);
}
P.S. Here is my motto for helping StackOverflow users:
System.out.println("He is not a hero. He is a silent guardian, a watchful protector; A DARK KNIGHT!");
You are trying to set an array equal to a string. Try this instead (first for loop)
for (i = 0; i < 3; i++)
h[i] = z.Batman();
Good luck!
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");
This is an exercise training for University. The program is about counting/reading the number of squares on a sheet (where the size is given by the user) the squares are represented by '#' and empty space is '.'.
public class Quadrado {
public static void main(String[] args){
int flag=0, l=0, c=0;
String bla;
Scanner in = new Scanner(System.in);
flag = in.nextInt();
l = in.nextInt();
c = in.nextInt();
char [][] folha = new char[l][c];
while(in.hasNext()==true){
for (int i=0; i<l; i++){
for (int x=0; x<c; x++){
bla = in.nextLine();
folha[i][x] = bla.charAt(x);
}
}
}
if(flag==1){
contador(folha,in);
}
}
public static void contador(char[][] folha, Scanner in){
int conta=0, l=0, c=0;
for (int i=0; i<l; i++){
for (int x=0; x<c; x++){
if (folha[i][x]=='#'){
conta++;
}
}
}
System.out.print(conta);
}
}
So eclipse was giving me errors on the folha[i][x] = bla.charAt(x), at first I had it like this: folha[i][x] = in.next().charAt(x), but it was giving an error that I don't recall, so my friend said to use the object like it is now, but it still goes wrong. When you execute it, it lets you insert the flag and the size of the sheet but as soon as you finish inserting the first line ex: ### it gives me:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Quadrado.main(Quadrado.java:21)
It was also giving me an error when calling the method and the suggested solution by eclipse was creating the same method.
Hope you guys can guide me here.
You will get StringIndexOutOfBoundsException when bla.length() will be less than the value of c.
because your this line is wrong
folha[i][x] = bla.charAt(x);
you should check x< bla.length() before this line.