Mistake Integer customized value Java - java

How can I read-in an integer in this following program? It doesn't work. It doesn't compile at the moment.
/**
* Main class of the Java program.
*
*/
import java.util.Scanner;
//...
class Scanner{
Scanner in = new Scanner(System.in);
int num = in.nextInt();
}
public class Main {
public static void main(String[] args) {
// we print a heading and make it bigger using HTML formatting
System.out.println("<h4>-- Binaere Suche --</h4>");
int anzahl = 0; int zahl;
}
}

import java.util.Scanner;
// This will print what you want but will not make it look bigger as it
// will get printed in console
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
// we print a heading and make it bigger using HTML formatting
System.out.println("<h4>--"+num+" --</h4>");
}
}

Related

Converting String Array into Integer Array by accessing each indexes using loop

I have my example code below. I'm trying to convert the gradeString into gradeInt and I can't seem to do it properly. When I print the value of gradeInt at the end using toString.
It says a blank array which is like this one: [ ]
Thanks for the help!
import java.util.*;
class testing{
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr = new String[studSize];
public static int [] gradeInt = new int[gradeArr.length];
public static void initialize(){
System.out.print("Please enter student size: ");
String studString = console.nextLine();
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeArr));
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
}
Add this line just before your call to convert for the "quick fix":
gradeInt = new int[gradeArr.length];
Try this. The problem is that you are assigning sizes of arrays etc before any data is entered. Actually the usuage of studSize is not needed at all - see comments in code
public static Scanner console = new Scanner(System.in);
public static int studSize;
public static String [] gradeArr;
public static int [] gradeInt;
public static void initialize(){
// not needed -
System.out.print("Please enter student size: ");
String studString = console.nextLine();
// not needed
studSize = Integer.parseInt(studString);
enterData();
}
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
convert();
}
public static void convert(){
// set here as the size is know
gradeInt = new int[gradeArr.length];
for(int i=0; i<gradeArr.length; i++){
// should be carefull of NumberFormatException
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
print();
}
public static void print(){
System.out.print(Arrays.toString(gradeInt));
}
public static void main(String [] args){
initialize();
//Main and Class Closing Braces
}
I ran your code and it works
Output:
[95, 85, 75]
Process finished with exit code 0
I suspect there may be an error in other parts of your code if you're getting a empty array.
What's the context you're running the code in? If you paste the rest of the code it might help finding the real source of the error.
SOLUTION:
Like Andy mentioned. The root error is contained here:
public static int [] gradeInt = new int[gradeArr.length];
You're defining this variable at runtime and assigning it the same length as gradeArr which is 0 at the time.
This results in a logic error that happens in the convert() method.
for(int i=0; i<gradeInt.length; i++){
gradeInt[i] = Integer.parseInt(gradeArr[i]);
}
You are telling the code to loop if i was smaller than gradeInt which has a length of 0. Basically it never loops. It just skips the loop entirely.
The quickest way to fix this is to modify the code like this:
Don't assign a length to the gradeInt variable at runtime. Modify the line to this:
public static int [] gradeInt;
And then modify your enterData() method to this:
public static void enterData(){
System.out.println("Enter student grades separated with dash(-)");
System.out.print("Enter student grade/s: ");
String gradeString = console.nextLine();
gradeArr = gradeString.split("-");
gradeInt = new int[gradeArr.length];
convert();
}

Java Calculator with classes

OK so i have been working on a calculator with classes(To play with classes but a function) and when ever I run it all i get back is zero no matter what I type in or say to use for the operator. Here is my code:
Main class:
import java.util.Scanner;
//numof = number of numbers in array
// numarrays = the array for user input
// finial = finial number aka the answer
public class Calculator {
public static double finial;
/**
* #return the finial
*/
public static double getFinial() {
return finial;
}
/**
* #param numof the finial to set
*/
public static void setFinial(double finial) {
finial = numof;
}
public static int numof;
/**
* #return the numof
*/
public static int getNumof() {
return numof;
}
/**
* #param numof the numof to set
*/
public static void setNumof(int numof) {
numof = numof;
}
public static double[] numarrays;
/**
* #return the numarrays
*/
public static double[] getNumarrays() {
return numarrays;
}
/**
* #param numarrays the numarrays to set
*/
public static void setNumarrays(double[] numarrays) {
numarrays = numarrays;
}
#SuppressWarnings("resource")
public static void main (String[] args) {
System.out.println("Hello and welcome to my calculator, in this calculator you can add, subtract or multiply");
System.out.println("For the next step I need to know how many numbers you would like to input? ");
int numof;
Scanner numofnums= new Scanner(System.in);
numof = numofnums.nextInt();
Calculator.setNumof(numof);
System.out.println("So next you are going to input the numbers");
double[] numarrays = new double[numof];
for (int k=0; k < numof; k++){
System.out.println("Please enter number");
Scanner input = new Scanner(System.in);
numarrays[k] = input.nextDouble();
}
Calculator.setNumarrays(numarrays);
System.out.println("Please enter what you would like to do with these numbers add,subtract,avg,multiply");
Scanner OP = new Scanner(System.in);
String OPerator= OP.next();
if (OPerator.equals ("add")){
Add.adding();
}
else if (OPerator.equals ("subtract")){
subtract.subtracting();
}
else if (OPerator.equals ("multiply")){
multiply.multiplying();
}
else if (OPerator.equals ("avg")){
avg.avging();
}
System.out.println("The answer is " + Calculator.getFinial());
}
}
here is the add class:
public class Add extends Calculator {
public static void adding() {
double finial = 0;
for (int h = 0; h < Calculator.getNumof(); h++){
finial = finial + Calculator.getNumarrays()[h];
}
Calculator.setFinial(finial);
}
}
I do have three more classes but it is just operator classes let me know if you need them
Just a quick look shows some significant basic issues. For example, in a basic setter, like:
public static void setFinial(double finial) {
finial = numof;
}
from your code, what you most likely intended was
public static void setFinial(double paramFinial) {
finial = paramFinial;
}
If your static variable and your parameter have the same name, you can't access both. The compiler will think you're talking about the parameter. Also, be careful that your setter is using the parameter paramFinial instead of the probably unintentional reference to numof.
It would be a lot easier to read the rest of your code if you would comment what finial, numof, and your other variables represent.

I have an error with a math operation Java?

I created a code that is meant to accept a user-input then add 5 to it, this is the code. When I enter any number, It returns 0. EDIT: I moved the reCalculate down under main, nothing changes
package files;
import java.util.*;
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
static int numberReCalculated;
public static int reCalculate(int a){
int numberReCalculated = a + 5;
return numberReCalculated;
}
public static void main(String[] args){
int bobson;
System.out.print("Enter a number, I will do the rest : ");
bobson = userFirstNumber.nextInt();
reCalculate(bobson);
System.out.println(numberReCalculated);
}
}
Your declaration of int numberReCalculated = a + 5; shadows the field declaration static int numberReCalculated;. Either change int numberReCalculated = a + 5; to numberReCalculated = a + 5;, or rewrite the entire code to be idiomatic and organized:
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
public static int reCalculate(int a){
return a + 5;
}
public static void main(String[] args){
int input;
System.out.print("Enter a number, I will do the rest : ");
input = userFirstNumber.nextInt();
int result = reCalculate(bobson);
System.out.println(result);
}
}
I have no idea how "bobson" is a descriptive and self-documenting variable name.

Write a class named Calculator with a method int sum(String s)

String s contains a set of integers separated by white space (blanks, tabs, or newlines). Return the sum of the integers.
You can use a Scanner object to solve this problem. Create a new Scanner(s) and store it in a variable, say in. Then, use in.hasNextInt() to control a while loop. Each iteration of the while loop uses in.nextInt() to get the next integer from the String s. Accumulate this integer into a variable and return that variable when the loop exits.
You may use a main method to test your method by creating an instance of the Calculator class and calling sum(…) with several combinations of values using that instance.
For example, sum(“3 4 5 27 3”) is 42.
I have written this so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
}
public int sum(String s){
int i = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}
To call the method from main and display the results make the sum method static and then call it and print the result:
public static void main(String[] args) {
System.out.println(sum("1 2 3"));
}
import java.util.Scanner;
public class Calculator{
public static void main(String[] args){
System.out.println(sum("1 2 3"));
}
public static int sum(String s){
int i = 0;
int sum = 0;
Scanner in = new Scanner(s);
while (in.hasNextInt()) {
sum = sum + in.nextInt();
}
return sum;
}
}

Exception in thread main error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I'm hoping this is just a simple error here, I've looked up numerous other instantces of people getting the same error message but none of their solutions really seem to apply for me. I was just wondering if you guys could help me find the error in my code. I'm not even sure if it's functional because I can't get it to run, so I suppose it could be a logic error.
When I try to run the following cold I am met with fatal exception error occured. Program will exit.
Eclipse also gives me:
java.lang.NoSuchMethodError: main
Exception in thread "main"
Thank you very much for any assistance you can offer!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static Integer main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
return soldiersList.get(0);
} //end main
}//end class
We know that to execute any java Program we should have a main function. because this is a self callable by JVM.
And the signature of the function must be..
public static void main(String[] args){
}
but in your code it's seem like this...
public static Integer main(String[] args){
}
so its consider as a different function , so change your main return type..
The signature for main method is
public static void main(String[] args).
When you run your program the JVM will look for this method to execute. You need to have this method in your code
Your program does not contain the main method, change it to
public static void main(String[] args)
If you want to return an Integer object, then define a custom mehod and call that method inside the main method and handle that returned value.
Java main() function doesn't have a return-statement. This line
public static Integer main(String[] args)
should be
public static void main(String [] args)
Also since it has no return value, you should delete the return statement.
Java's main method should have below signature.
public static void main(String[] args){
..
..
}
Try to run this code and tell if it works.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JoPuzzle
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of soliders");
int soldiers = input.nextInt();
System.out.println("Please enter the how many soldiers are skipped before the next death");
int count = input.nextInt();
List<Integer> soldiersList = new ArrayList<Integer>(soldiers);
for (int i = 1; i <= count; i++) {
soldiersList.add(i);
}
int currentIndex = 0;
while(soldiersList.size() > 1) {
currentIndex = (currentIndex - 1 + count) % soldiersList.size();
soldiersList.remove(currentIndex);
}
// return soldiersList.get(0);
System.out.println(soldiersList.get(0));
} //end main
}//end class

Categories

Resources