Java длинная ошибка

Why do I get an int number is too large where the long is assigned to min and max?

/*
long: The long data type is a 64-bit signed two's complement integer.
It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of         9,223,372,036,854,775,807 (inclusive).
Use this data type when you need a range of values wider than those provided by int.
*/
package Literals;

public class Literal_Long {
     public static void main(String[] args) {
        long a = 1;
        long b = 2;
        long min = -9223372036854775808;
        long max = 9223372036854775807;//Inclusive

        System.out.println(a);
        System.out.println(b);
        System.out.println(a + b);
        System.out.println(min);
        System.out.println(max);
    }
}

Andrew Thompson's user avatar

asked Jan 19, 2012 at 10:59

Aaron's user avatar

1

All literal numbers in java are by default ints, which has range -2147483648 to 2147483647 inclusive.

Your literals are outside this range, so to make this compile you need to indicate they’re long literals (ie suffix with L):

long min = -9223372036854775808L;
long max = 9223372036854775807L;

Note that java supports both uppercase L and lowercase l, but I recommend not using lowercase l because it looks like a 1:

long min = -9223372036854775808l; // confusing: looks like the last digit is a 1
long max = 9223372036854775807l; // confusing: looks like the last digit is a 1

Java Language Specification for the same

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

Suresh Atta's user avatar

Suresh Atta

121k37 gold badges198 silver badges307 bronze badges

answered Jan 19, 2012 at 11:01

Bohemian's user avatar

BohemianBohemian

413k94 gold badges575 silver badges724 bronze badges

3

You must use L to say to the compiler that it is a long literal.

long min = -9223372036854775808L;
long max = 9223372036854775807L;//Inclusive

answered Jan 19, 2012 at 11:01

Petar Minchev's user avatar

Petar MinchevPetar Minchev

46.9k11 gold badges103 silver badges119 bronze badges

\$\begingroup\$

This is my first time working with Java exceptions. I have made a program that works to specifications, but I am wondering if there is anything I’ve done which is unconventional or not recommended. The application program does specify that there be line breaks between each message.

My driver is:

import java.util.Scanner;
public class ReadStrings {

    public static void main(String[] args) throws StringTooLongException{
        String str1;
        final int MAX_STRING_LENGTH = 20;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter strings, enter DONE when finished:\n");
        str1 = input.nextLine();
        if(str1.equalsIgnoreCase("done"))
            System.exit(0); //exit on first prompt
        do{
            try
            {
                if(str1.length()>MAX_STRING_LENGTH)
                    throw new StringTooLongException();
                System.out.println("\nEnter a string, enter DONE when finished:\n");
                str1 = input.nextLine();            
            }
                catch(StringTooLongException e)
            {
                    System.out.println(e.getMessage());
                    str1 = input.nextLine();
            }
        }while(!str1.equalsIgnoreCase("done"));
        input.close();
    }
}

And my custom exception class is:

public class StringTooLongException extends Exception {
    public StringTooLongException()
    {
        super("\nString has too many characters\n\nPlease try again:\n");       
    }
}

Thanks for taking a look. Any advice is appreciated.

200_success's user avatar

200_success

144k22 gold badges186 silver badges470 bronze badges

asked Nov 24, 2016 at 20:20

RandomKaryotype's user avatar

\$\endgroup\$

1

\$\begingroup\$

if(str1.equalsIgnoreCase("done"))
        System.exit(0); //exit on first startup

Do not use System.exit() (somewhere else then in a catch block in main) It terminates the JVM immediately. This is usually not intended.
just write a return instead.

         if(str1.length()>MAX_STRING_LENGTH)
                throw new StringTooLongException();
            System.out.println("\nEnter a string, enter DONE when finished:\n");
            str1 = input.nextLine();         

This will result in an endless loop when the user enters a long string. The check is done (and the exception thrown) before she gets a chance to enter a new one.

You should move the if behind the input request and delete the initial input request (along wit the if there) before the loop.


Since you do nothing else in the loop the checking the string and requesting new one some may argue that you use the Exception as flow control for which exceptions are not supposed to be used.
I’d agree to that argument in this particular case as long as the «happy path» also repeats the loop…

answered Nov 24, 2016 at 20:39

Timothy Truckle's user avatar

\$\endgroup\$

1

\$\begingroup\$

        String str1;

Delete that and change

        str1 = input.nextLine();

to

        String str1 = input.nextLine();

instead.

        if(str1.equalsIgnoreCase("done"))
            System.exit(0); //exit on first prompt
        do{
            try
            {
                if(str1.length()>MAX_STRING_LENGTH)
                    throw new StringTooLongException();
                System.out.println("\nEnter a string, enter DONE when finished:\n");
                str1 = input.nextLine();            
            }
                catch(StringTooLongException e)
            {
                    System.out.println(e.getMessage());
                    str1 = input.nextLine();
            }
        }while(!str1.equalsIgnoreCase("done"));

This seems the long way around. Why not

        while (!str1.equalsIgnoreCase("done")) {
            if (str1.length() > MAX_STRING_LENGTH)
            {
                System.out.println("\nString has too many characters\n\nPlease try again:");
            }

            System.out.println("\nEnter a string, enter DONE when finished:\n");
            str1 = input.nextLine();
        }

It’s uncommon to throw an exception in a try block that you catch immediately. And it’s totally unnecessary in this case. The only thing that you do differently is to print a message.

While not unknown, it is uncommon to put a try/catch in a loop. It’s extra overhead that you don’t need in this case.

It’s unclear why you exit before the loop. You can just use a regular while loop and exit normally. You also close input in that case.

answered Nov 24, 2016 at 21:10

mdfst13's user avatar

mdfst13mdfst13

21.4k6 gold badges32 silver badges67 bronze badges

\$\endgroup\$

1

\$\begingroup\$

You could make StringTooLongException a subclass of RuntimeException instead of Exception to make it an unchecked exception, in the spirit similar to the unchecked IndexOutOfBoundsException and ArithmeticException. However, this depends on the API you are willing to present to your users, and whether you think that this exception must be handled specially over others.

answered Nov 24, 2016 at 21:55

Tamoghna Chowdhury's user avatar

\$\endgroup\$

i have 9 classes which all compile in bluej but when i run it and after i log in all this messages come up but i dont know where its coming from.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.DecimalFormat;
import java.sql.*;
import java.util.Date;
import java.text.SimpleDateFormat;


public class LController implements ActionListener
{
DecimalFormat df = new DecimalFormat("###.00");
private LibraryGUI libg;
private String user;
private ChPwGUI cpwg;
private NewBookGUI nbg ;
private TakeOutLoanGUI tol;
private QueryFetcher qF;
private Store Storage;
private int selectedId = -1;
String bookname;
String authorf;
String authors;




    public LController(String LLoginName, int level)
    {
        // initialise instance variables
        user = LLoginName;
        nbg= new NewBookGUI(user);
        tol = new TakeOutLoanGUI(user);
        libg = new LibraryGUI(level, user);
        libg.addLibraryGUIActionListeners(this);//register controller as listener to bank GUI
        WindowQuitter wquit = new WindowQuitter();      // create quit object using inner class to close window
        libg.addLibraryWindowListener(wquit);
        if (level < 8) libg.jmiChangeLogin.setEnabled(false);
        if (level < 8) libg.jmiTakeLoan.setEnabled(false);
        libg.jmiViewAllBooks.doClick();
        libg.setVisible(true);


    }
    public void openLogin()
    {
        Login log = new Login(); 
        log.setLocation(100,100);
        log.setSize(350,250);
        log.setVisible(true);  
        System.out.println("New login window.");
    }//end openLogin
    public void openChPwGUI()
    {
        cpwg = new ChPwGUI(user);
        cpwg.addChangePasswordActionListeners(this);
        cpwg.setLocation(30,30);
        cpwg.setSize(350,250);
        cpwg.setVisible(true);  
        System.out.println("New change password window for user: " + user);
    }
    public void openNewBookGUI()
    {
        nbg = new NewBookGUI(user);
        nbg.addNewBookActionListeners(this);
        nbg.setLocation(30,30);
        nbg.setSize(480,220);
        nbg.setVisible(true); 
    }
    public void openTakeOutLoanGUI()
    {
        tol = new TakeOutLoanGUI(user);
        tol.addTakeOutLoanActionListeners(this);
        tol.setLocation(50,50);
        tol.setSize(480,220);
        tol.setVisible(true);
    }


    /**
     *methods
     */



    public void actionPerformed(ActionEvent ae) 
    {
        Object source = ae.getSource();
        //Filters from the "Tool Bar"       
        if (source == libg.jmiViewAllBooks)
        { 
            System.out.println("View All Books");
            String sql="Select * from tblBook";
            getData(sql,"All Books");
            System.out.println(sql);
        }

        if (source == libg.jmiFilterByFAuthor)
        { 
            System.out.println("filter By Author Firstname");
            String Firstname = JOptionPane.showInputDialog(libg,"Firstname: ","Library - Filter by Firstname");
            String sql="SELECT * FROM QryBooks WHERE Firstname LIKE '%" + Firstname + "%'"; 
            System.out.println("Firstname = " + Firstname);
            getData(sql,"All Books matching Firstname containing " + Firstname);     
            System.out.println(sql);
        }

        if (source == libg.jmiFilterBySAuthor)
        { 
            System.out.println("filter By Author Surname");
            String Surname = JOptionPane.showInputDialog(libg,"Surname: ","Library - Filter by surname");
            String sql="SELECT * FROM QryBooks WHERE Surname LIKE '%" + Surname + "%'"; 
            System.out.println("Surname = " + Surname);
            getData(sql,"All books matching Surname containing " + Surname);
        }

        if (source == libg.jmiFilterBySeries)
        { 
            System.out.println("filter By Series Name");
            String SeriesName = JOptionPane.showInputDialog(libg,"Series: ","Library - Filter by Series");
            String sql="SELECT * FROM QryBooks WHERE SeriesName LIKE '%" + SeriesName + "%'"; 
            System.out.println("Series = " + SeriesName);
            getData(sql,"All Series containing " + SeriesName);
        }

        if (source == libg.jmiFilterByTakenOut)
        { 
            System.out.println("filter By Taken Out (1)");
            int TakenOut = 1;
            String sql="SELECT * FROM QryBooks WHERE TakenOut =" + TakenOut; 
            System.out.println("Loans = " + TakenOut);
            getData(sql,"All loans containing " + TakenOut);
        }
//          if(source == libg.jmiFilterByNOL)
//         {
//            System.out.println("filter By Number of Loans");
//            int NOLcompare = 0;
//            String sql ="SELECT * FROM QryBooks WHERE NOL >" + NOLcompare;
//            getData(sql,"All loans >" + NOLcompare);
//         }
        if (source == libg.jmiChangeLogin)
        {
            System.out.println("Edit login button clicked");
            openChPwGUI();           
        }

        if (source == libg.jmiExit)
        { 
            System.out.println("password Quit button clicked");
            System.out.println("logging out. Closing Library.");
            openLogin();     
            libg.dispose();
        }

        if (source == libg.jbtPrint)
        { 
            System.out.println("print button clicked");
            try
            {
                libg.lTable.print();
            }
            catch (java.awt.print.PrinterException pl)
            { //if there is a run-time printing error, print message and trace
                pl.printStackTrace();
                System.out.print("Jtable print FAILED :- error - " + pl.getMessage() );
            }//end of catch block
        }



        if (source == libg.jmiNewBook)
        { 
            System.out.println("New Book Button pressed");
            openNewBookGUI();           
        }

        if (source == libg.jmiTakeLoan)
        {
            System.out.println("Take Out Loan");
            openTakeOutLoanGUI();
        }
        if (source == libg.jmiQuit)
        {
            System.out.println("logging out. Library closed.");
            openLogin();     
            libg.dispose();
        }

        else if (source == tol.jbTakeOut)
       {    bookname = tol.jtfBookName.getText();
           authorf = tol.jtfAuthorFName.getText();
           authors = tol.jtfAuthorSName.getText();
           Store.changeLoanStatus(bookname, authorf, authors);
           Storage.closeConnection();
        }

        else if (cpwg !=null && source == cpwg.jbSubmit)
        {
            System.out.println("cpwg = " + cpwg);
            System.out.println("password GUI submit button clicked");

            tryNewPassword();
        }
        else if (cpwg !=null && source == cpwg.jbCancel)
        {
            System.out.println("cpwg = " + cpwg);
            System.out.println("password GUI cancel button clicked");
            cpwg.jpfOPassword.setText("");
            cpwg.jpfN1Password.setText("");
            cpwg.jpfN2Password.setText("");
            cpwg.jpfOPassword.requestFocus();
        }
       else if (cpwg !=null && source ==cpwg.jbQuit)
        {
            System.out.println("cpwg = " + cpwg);
            System.out.println("password Quit button clicked");     
            cpwg.dispose();
        }
        else if (cpwg !=null && source ==cpwg.jpfOPassword)
        {
            System.out.println("cpwg = " + cpwg);
            System.out.println("old password text field <enter>");
            cpwg.jpfN1Password.requestFocus();
        }
        else if (cpwg !=null && source ==cpwg.jpfN1Password)
        {
            System.out.println("cpwg = " + cpwg);
            System.out.println("new password 1 text field <enter>");
            cpwg.jpfN2Password.requestFocus();
        }
        else if (cpwg !=null && source ==cpwg.jpfN2Password)
        {
            System.out.println("cpwg = " + cpwg);
            System.out.println("new password 2 text field <enter>");
            tryNewPassword();
        }
        else if (source == nbg.jbSubmit && (nbg.bookname.equals("") || nbg.authorf.equals("") || nbg.authors.equals("") || nbg.series.equals("")))
        {
            JOptionPane.showMessageDialog(null,  " Error, Fields have been left Empty! "," ERROR! ", JOptionPane.ERROR_MESSAGE); 
        }



        else if (nbg !=null && source ==nbg.jbSubmit)
        {
            System.out.println("Submit Button Clicked.");
            String bookName = NewBookGUI.jtfBookName.getText();
            String authorFName = NewBookGUI.jtfAuthorFName.getText();
            String authorSName = NewBookGUI.jtfAuthorSName.getText();
            int SeriesNo = Integer.parseInt(NewBookGUI.jtfSeriesNumber.getText());
            String SeriesNa = NewBookGUI.jtfSeriesName.getText();
            Store storage = new Store();
            Store.newBook (bookName, authorFName, authorSName, SeriesNo, SeriesNa);
            storage.closeConnection();
            nbg.dispose();
            System.out.println("View All Books");
            String sql="Select * from tblBook";
            getData(sql,"All Books");
            System.out.println(sql);
        }
        else if (source == nbg.jbCancel)
        {
            nbg.dispose();
        }

    }



    public void getData(String sql, String message) //uses queryfetcher
    {
        int noOfColumns = 0;
        QueryFetcher allBooks = new QueryFetcher("Library.mdb");
        String allValues[] [], colNames[], colTypes[];
        allValues = allBooks.getFilteredBooks(sql); 
        System.out.println("datavalues = " + allValues);
        colNames = allBooks.getLibraryColumnNames(sql);
        colTypes  = allBooks.getLibraryColumnTypes(sql);
        System.out.println("colNames = " + colNames + "colTypes = " + colTypes);
        showBooks(allValues, colNames, colTypes, message);

        }


    public void showBooks(String data[] [] , String cols[], String types[], String title) 
    {
        //takes arrays with data, column headings and data types and displays in JTable
        int c=cols.length;      //c = no of fields = length of colls array
        System.out.println("c = " + c);
        int r = data.length;    //r = no of rows
        System.out.println("r = " + r);
        int[] w = new int[c];   //width of each column
        System.out.println("w = " + w);
        int tw = 0;//total width of cols
        System.out.println("tw = " + tw);
        for  (int col=0;col<c;col++)    //loop through cols
                {
            w[col] = 5;
            for (int row=0;row<r;row++)
                    {   
                //add in £ symbol to currency values
                if (types[col].equals("CURRENCY")&& data[row][col]!=null )
                {
                    double d = Double.parseDouble(data[row][col]);     
                    if (d >=0)data[row][col] = "  £" + df.format(d);
                    else data[row][col] = "- £" + df.format(-d); 
                        }//end if
                //find maximum number of characters in each column of data
                if (data[row][col]!=null && w[col]<data[row][col].length()) w[col] = data[row][col].length();
                    }//end inner row for loop
            System.out.println("w["+col+"] = " + w[col]);
                    tw = tw + w[col];       //add size of each column to get total width
                }//end outer column for loop

            if (libg.scrollPane != null)libg.jpAll.remove(libg.scrollPane);     //remove scroll pane if exists
            libg.lTable = new JTable( data, cols );//create new JTable
            Color colour = new Color(91,209,234);
            libg.lTable.setBackground(colour);
            libg.scrollPane = new JScrollPane( libg.lTable );                 //... scrollpane
            libg.lTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);        
            libg.lsm = libg.lTable.getSelectionModel();                       //... list selection model
            libg.jpAll.add( libg.scrollPane, BorderLayout.CENTER);
            libg.jpAll.setBackground(Color.BLACK); 
            //set preferred column widths of JTable to match data widths in array w (with minimum of about 10 'pixels')
            for(int i=0;i<c;i++)
            {
                libg.lTable.getColumnModel().getColumn(i).setPreferredWidth(w[i]*10+15);
            }
            if (tw*10+c*15 < 1250)libg.setPreferredSize(new Dimension(tw*10+c*15,320));
            else libg.setPreferredSize(new Dimension(1250,320)); 
            libg.pack();
        }




        private void tryNewPassword()
        {
            String fpw = Store.charArrayToString(cpwg.jpfN1Password.getPassword());
            String spw = Store.charArrayToString(cpwg.jpfN2Password.getPassword());
            String opw = Store.charArrayToString(cpwg.jpfOPassword.getPassword());
            System.out.println("fpw = " + fpw + "and spw = " + spw + " and opw = " + opw);
            if(verifyPassword(fpw,spw)) //check new passwords match
            {
                System.out.println("new password verified");
                Store st = new Store();                      // create connection object
                int level = st.SQLfindLogin(user, opw);     //-1 login failed otherwise returns security level
                System.out.println("verified password level = " + level);
                if (level >0)       //old password is valid
                {
                    System.out.println("old password correct - changing password ...");
                    st.changePassword(user, fpw);
                    cpwg.jtfFeedback.setText("password changed");
                    JOptionPane.showMessageDialog(cpwg,"Change successful. Close window.","Password change",JOptionPane.INFORMATION_MESSAGE);
                    cpwg.dispose();
                }
                else System.out.println("password error - no change made");
                st.closeConnection();                  // close connection
            }
            else 
            {
                System.out.println("password needs to match and be valid - change FAILED");   
                cpwg.jtfFeedback.setText("change FAILED - try again");
            }
        }   

        private boolean verifyPassword(String p1, String p2)
        {
            if (p1.length() > 2 && p1.equals(p2)) return true;
            else return false;
        }

        //inner class to open login window as this window closes
        class WindowQuitter extends WindowAdapter
        {
            public void windowClosing( WindowEvent we )
            {

                System.out.println("Logged out...");
                //create login screen
                openLogin();
                libg.dispose();           //and quit   
            }
        }//end WindowQuitter class

    }//end of class

thats my main class.

public class Three {
    public static void main(String[] args) {
        Three obj = new Three();
        obj.function(600851475143);
    }

    private Long function(long  i) {
        Stack<Long> stack = new Stack<Long>();

        for (long j = 2; j <= i; j++) {
            if (i % j == 0) {
                stack.push(j);
            }
        }
        return stack.pop();
    }
}

When the code above is run, it produces an error on the line obj.function(600851475143);. Why?

tobias_k's user avatar

tobias_k

81.4k12 gold badges120 silver badges179 bronze badges

asked Sep 21, 2010 at 6:18

user446654's user avatar

5

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an «L»: 600851475143L

answered Sep 21, 2010 at 6:20

Yuliy's user avatar

YuliyYuliy

17.4k6 gold badges41 silver badges47 bronze badges

Append suffix L: 23423429L.

By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.

answered Sep 21, 2010 at 6:20

Roman's user avatar

RomanRoman

64.4k92 gold badges238 silver badges332 bronze badges

1

You need to use a long literal:

obj.function(600851475143l);  // note the "l" at the end

But I would expect that function to run out of memory (or time) …

answered Sep 21, 2010 at 6:20

Thilo's user avatar

ThiloThilo

257k102 gold badges512 silver badges657 bronze badges

3

The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.

To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.

Since some Fonts make it hard to distinguish «1» and lower case «l» from each other you should always use the upper case «L».

answered Sep 21, 2010 at 6:29

josefx's user avatar

josefxjosefx

15.5k6 gold badges38 silver badges63 bronze badges

You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).

This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).

answered Sep 21, 2010 at 6:22

Andre Holzner's user avatar

Andre HolznerAndre Holzner

18.4k6 gold badges54 silver badges63 bronze badges

At compile time the number «600851475143» is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.

answered Sep 21, 2010 at 11:59

JVM's user avatar

JVMJVM

2291 silver badge2 bronze badges

Apart from all the other answers, what you can do is :

long l = Long.parseLong("600851475143");

for example :

obj.function(Long.parseLong("600851475143"));

answered Jan 22, 2017 at 13:33

Anand Undavia's user avatar

Anand UndaviaAnand Undavia

3,5035 gold badges19 silver badges33 bronze badges

1

Or, you can declare input number as long, and then let it do the code tango :D

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number");
    long n = in.nextLong();

    for (long i = 2; i <= n; i++) {
        while (n % i == 0) {
            System.out.print(", " + i);
            n /= i;
        }
    }
}

answered Jun 25, 2017 at 8:21

Milen.Jeremic's user avatar

In this short post, I will be sharing how to fix «integer number too large». This error is a compile-time error in Java. This error occurs when the java compiler tries to interpret the given number as a constant value of type int by default. As always, first, we will produce the «integer number too large» error before moving on to the solution.

Read Also: [Fixed] int cannot be converted to int[]

[Fixed]: Error: Integer number too large

Example 1: Producing the error by assigning an int to a long data type

We can easily produce this error by assigning an int to a variable whose data type is long as shown below:

public class IntegerNumberTooLarge {
    public static void main(String args[]) {
      

long x = 123456789101112;

System.out.println("variable x value is: " + x); } }

Output:
IntegerNumberTooLarge.java:3: error: integer number too large
           long x = 123456789101112;
                          ^
1 error

Explanation:

The cause of this error is by assigning an int to a variable whose data type is long. Integer literals are by default int in Java. This causes an error since 123456789101112 literal can not be represented with an int.

Solution:

The solution to this error is to append «l» or «L» after the number. Use «L» instead of «l» because lowercase «l» makes it hard to distinguish with «1», as a result, you should always use the uppercase «L». In Java, the compiler can interpret the long data type as long as the number to be interpreted contains ‘l’ or ‘L’ after it. It can be represented in the code as shown below:

public class IntegerNumberTooLarge {
    public static void main(String args[]) {
      

long x = 123456789101112L;

System.out.println("variable x value is: " + x); } }

Output:
variable x value is: 123456789101112

That’s all for today, please mention in the comments in case you are still facing the error java integer number too large.

Понравилась статья? Поделить с друзьями:
  • Java виды ошибок
  • Java деление на ноль какая ошибка
  • Java вызов ошибки
  • Java выдает ошибку 1603
  • Java virtual machine launcher ошибка как исправить майнкрафт