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

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();
}

Related

Why is array giving a wrong value when using two classes?

I have this code here.
public class ArrayChallenge {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of integers: ");
int num = kb.nextInt();
int [] returnedArray = readIntegers(num);
System.out.println("Ascending Order: " + printAsc(returnedArray));
}
public static int [] readIntegers(int count){
int [] values = new int[count];
for(int i=0; i<count; i++){
System.out.print("Enter number: ");
values[i] = kb.nextInt();
}
return values;
}
public static int [] printAsc(int [] theArray){
Arrays.sort(theArray);
return theArray;
}
The code above works perfectly fine. I have only one class but several static methods and during calling the method printAsc(returnedArray), the program will return a set of arrays in a format just like using .toString
I took this code to a next level using two classes and making the static methods to instance methods. However when i print the arrays. It prints these values [I#643b1d11
Here is my code below:
Main Class
public class Main {
public static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the number of elements: ");
int num = kb.nextInt();
int numArrays [] = new int[num];
Minimum minimum = new Minimum();
int [] returnedArrays = minimum.readIntegers(numArrays);
int returnedMin = minimum.findMin(returnedArrays);
System.out.println("Minimum Value: " + returnedMin);
System.out.println("Ascending Arrays: " + minimum.arrayAsc(returnedArrays));
}
}
Minimum Class
public class Minimum {
public int [] readIntegers(int [] numArrays){
System.out.println("Enter " + numArrays.length + " integers:");
for(int i=0; i< numArrays.length; i++){
numArrays[i]=Main.kb.nextInt();
}
return numArrays;
}
public int findMin(int [] numArrays){
int max = Integer.MAX_VALUE;
for(int i=0;i<numArrays.length;i++){
if(max>numArrays[i]){
max = numArrays[i];
}
}
return max;
}
public int [] arrayAsc(int [] numArrays){
Arrays.sort(numArrays);
return numArrays;
}
}
How did the result of my arrays became like that? Can someone explain the process to me? Much appreciate.
Also, i used the debug method because im using Intellij, It didnt really show anything.
The way you are using printAsc, you need to change its definition to return a String.
public static String printAsc(int [] theArray){
Arrays.sort(theArray);
return Arrays.toString(theArray);
}
If you do not want to change the definition of printAsc, you need to call it as follows:
System.out.println("Ascending Order: " + Arrays.toString(printAsc(returnedArray)));
You can't just print an Array and expect it to read out all the values. When printing, Java casts the value into a String. By default, when dealing with Objects, Java will simply print the name of the Object's class and its Hash value. This is what you see. You can read more about it here.
If you want to parse the Array into a String that hold all the members of the Array, you might want to take a look at the Arrays.toString method (and how to use it).

My bot program accepts user input and then instead of replying, does nothing

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.

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;
}
}

What is causing this exception? Is the constructor for loop unnecessary?

import java.util.*;
public class UserInput {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("How many students are in your class?");
Student.n= input.nextInt();
ArrayList<Student> manyStudents = new ArrayList<Student>();
for(int i=0; i<Student.n; i++){
manyStudents.add(new Student(null, null, null, null, 0));
}
}
}
This main method calls upon the public class Student to create a number of object instances that include the Student's first name last name HKID SID and exam grade and stores each object instance in another array deemed manyStudents. The question regards the compilation error received during run time shown in the latter part of the explanation.
import java.util.*;
public class Student {
public static String [] first;
public static String [] last;
public static String [] HKID;
public static String[] SID;
public static int []Exam;
public static int n;
public Student (String f, String l, String h, String s, int e){
Scanner kb= new Scanner(System.in);
for(int i=0;i<n;i++){
System.out.println("First name:");
first[i]=f= kb.next();
System.out.println("Last name:");
last[i]=l=kb.next();
System.out.println("HKID:");
HKID[i]=h=kb.next();
System.out.println("SID:");
SID[i]=s=kb.next();
System.out.println("Final exam score:");
Exam[i]=e=kb.nextInt();
}
}
public String[] getFirst(){return first;}
public String [] getLast(){return last;}
public String [] getHKID(){return HKID;}
public String [] getSID(){return SID;}
public int [] getExam(){return Exam;}
public void setFirst(String [] f){f=first;}
public void setLast(String [] l){l=last;}
public void setHKID(String [] h){h=HKID;}
public void setSID(String [] s){s= SID;}
public void setExam(int [] e){e=Exam;}
}
In run time I am receiving an error after it asks for the first name. The error reads:
Exception in thread "main" java.lang.NullPointerException
at Student.<init>(Student.java:15)
at UserInput.main(UserInput.java:9)
Is the "i" in the student constructor interfering with the allocation of the variables to each object instance. The code seems to make logical sense to me, so I am not sure the reason for error during run time. Perhaps the for loop in the constructor is unnecessary...I am not confident in any reason. Can someone please explain????
You need to instantiate your arrays, for example:
first = new String[n];
before you can use first[i]. Same for last & co.
Also you seem to expect that f = kb.next() is doing something but it's not doing anything in your current code.

Categories

Resources