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.
Related
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();
}
I created a bot and used a snippet of code I invented called "simplify" to dramatically shorten java commands.
Only problem is, the bot program I made with it doesn't work. It's supposed to search the user input for keywords and reply accordingly, but all it really does is accept user input and then turn off. What did I do wrong?
import java.util.*;
public class bot{
//"simplify" and "bot" created by #genisome, All rights reserved.
System.out.println(in);
}
public static void print(String in){
System.out.println(in);
}
public static void print(double in){
System.out.println(in);
}
public static void print(long in){
System.out.println(in);
}
public static void print(boolean in){
System.out.println(in);
}
public static void print(float in){
System.out.println(in);
}
//scan below
public static void scan(int dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextInt();
}
public static void scan(String dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.next();
}
public static void scan(double dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextDouble();
}
public static void scan(float dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextFloat();
}
public static void scan(boolean dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.nextBoolean();
}
public static void random(int min, int max, int dumpinto){
Random x = new Random();
dumpinto = x.nextInt(max) + min;
}
public static void main (String[] x){
int score;
String[] badcomputerresponse = {"that sucks, sorry", "sorry about that", "bummer", "shit", "aw, damn"};
String[] goodcomputerresponse = {"awesome.", "me too", "great", "cool", "I'm not bad myself"};
String[] goodwords = {"good", "fine", "dandy", "awesome", "cool", "swell", "great", "amazing", "ok", "okay", "well", "happy", "thrilled"};
String[] badwords = {"shitty", "terrible", "sad", "bad", "crappy", "terrible", "sucky", "up shit creek", "pathetic", "miserable", "badly", "terribly", "miserably"};
String input = "";
print("Hey there, how are you doing?");
scan(input);
for (int counter = 0; counter < goodwords.length; counter++){
if (input.contains(goodwords[counter])){
if (input.contains("not")){
sadanswer(badcomputerresponse);
}
else{
happyanswer(goodcomputerresponse);
}
}
}
for (int count2 = 0; count2 < badwords.length; count2++){
if (input.contains(badwords[count2])){
if (input.contains("not")){
happyanswer(goodcomputerresponse);
}
else{
sadanswer(badcomputerresponse);
}
}
}
}
public static void sadanswer(String[] badcomputerresponse){
int randomanswer = 0;
random(0, badcomputerresponse.length, randomanswer);
print(badcomputerresponse[randomanswer]);
}
public static void happyanswer(String[] goodcomputerresponse){
int randomanswer = 0;
random(0, goodcomputerresponse.length, randomanswer);
print(goodcomputerresponse[randomanswer]);
}
}
edit: thank you people who gave me help instead of downvoting me.
To the people who downvoted me, you stink!
First you define a bunch of scan methods like this:
public static void scan(String dumpinto){
Scanner x = new Scanner(System.in);
dumpinto = x.next();
}
Then you call it like this:
String input = "";
print("Hey there, how are you doing?");
scan(input);
That function does not do what it looks like it does. String dumpinto is an input parameter to the method. You can't write output to it. Once the method is done executing, the value that you typed in is lost. After you call scan(input);, the input variable still contains "". (Print it out or use a debugger to verify.)
Your scan method needs to return a value. Better yet, get rid of those methods altogether and just use one Scanner object to get input from the user.
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>");
}
}
The numThrows Variable is inciting an error of variable not found when used in the main method. even though i declare it in one of the methods.
I use the declare the variable in the void prompt method. This program is designed to calculate Pi using random coordinates then uses a formula to estimate pie over a user given amount of tries.
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts
public static void prompt()
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
}
public static double[] randomX( int numThrows)
{
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts <= numThrows)
{
cordX[i] = Math.random();
i++;
}
return cordX;
}
public static double[]randomY(int numThrows)
{
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts <= numThrows)
{
cordY[i] = Math.random();
i++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY)
{
int ii = 0;
int i = 0;
double hits = 0;
double misses = 0;
for(i = 0; i <= numThrows; i++)
{
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1)
{
hits++;
ii++;
}
else{
misses++;
}
}
}
public static double calcPi(int misses, int hits)
{
int total = hits + misses;
double pi = 4 * (hits / total);
}
// public static void print(double pi, int numThrows)
// {
// System.out.printf(" %-7s %3.1f %7s\n", "Trial[//numtrial]: pi = "
// }
public static void main(String[] args)throws IOException
{
prompt();
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
gethits();
double pi = calcPi(misses, hits);
}
}
If numThrows is declared within another function, then its scope does not extend to the main method.
Instead, if you want to use it in both the main method and the other one, make it a class instance.
For example:
class SomeClass {
public static int numThrows = 2;
public static void test() {
numThrows = 4; // it works!
}
public static void main(String[] args) {
System.out.println(numThrows); // it works!
}
}
Therefore, its scope will be extended to all the members of the class, not just the method.
numThrows is an instance variable to your prompt method. If you want to do what I think you want to do, make numThrows a static variable outside any methods.
It will look like this:
public class Darts {
public static int numThrows
public static int numTrials
These variables can be referenced from any method. This should fix it.
Try to remove the method prompt() it's unused, and put his block in the main method.
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
double[] cordX = randomX(numThrows);
...
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;
}
}