In the code below I try to get the grade of all my subjects. I get the input via a for loop. But I'm supposed to store the grade ("C" for example) in the grade array but I get a NullPointerException. I don't understand what's wrong with my code since I thought it was good to go.
Also, ignore the names of the subjects since they are in Swedish.
public class Defan{
Scanner sc = new Scanner(System.in);
String grade[];
String gradeName[] = {"Svenska1", "Svenska2", "Svenska3", "Engelska5", "Engelska 6",
"Mattematik 1c", "Mattematik 2c", "Mattematik 3c", "Mattematik 4", "Idrott", "Samhälle", "Religion",
"Historia", "Biologi1", "Biologi2", "Fysik1", "Fysik2", "Kemi1", "Kemi2", "Franska3", "Franska4", "Körsång1", "Körsång2"
, "Gymnasiearbete"};
public void getInput(){
for(int i = 0; i <= gradeName.length; i++){
System.out.println("Enter grade for " + gradeName[i] + ": ");
grade[i] = sc.nextLine();
}
}
It is very obvious, you have to allocate grade array first!
In your constructor:
final int SIZE = 1024;
grade = new String[SIZE];
Actually i prefer to use an ArrayList instead of array in your case.
You are trying to use grade[] array before initializing it. Try
String grade[] = new String[gradeName.length] <br>
And in in your for loop for(int i = 0; i <= gradeName.length; i++)
In condition use only '<' instead of '<=' like this
for(int i = 0; i < gradeName.length; i++)
because 0 is the first index and size-1 is last index.
Related
How do I print the selected name in the array? I want to print the names i entered in the array and print it alone but when I try to run the code it says:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:17)
here is my code:
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
//Getting the names using for loop.
for(int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
for(int i = 0; i <numOfLoop; i++) {
if(name[i] == name[num]) {
System.out.println(name[i]);
}
}
Input:
6 //How many loop and size of array I want.
john
mark
kevin
tesia
arthur
cody
5 //what ever is in array[5] will be printed.
Expected output: cody
I also encountered this problem before, it seems that when you change from nextInt() the scanner instance did not read the \n character before it goes forward to nextLine().
Just adding in.nextLine(); before the For-loop should fix the problem.
Your error comes from the fact that the first entry in the array gets set as an empty string and the last name you put in gets read where you normally would put the second number, thus the nextInt() throws an error since it gets a String and not an int.
There are several typical flaws in the code snippet to be addressed:
InputMismatchException - because not all new lines are consumed properly after calling to nextInt
name[i] == name[num] -- invalid String comparison, should be name[i].equals(name[num])
Missing check num < numOfLoop -- without that, ArrayOutOfBoundsException is possible
The fixed code would look as follows:
Scanner in = new Scanner(System.in);
System.out.println("Input the number of names: ");
int numOfLoop = in.nextInt(); //number of loops I want.
in.nextLine(); // skip remaining line
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
System.out.println("Input the names, one per line: ");
//Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
System.out.println("Input the index of the name to print: ");
int num = in.nextInt(); //The name I want to print depend on what number I enter here.
//Reading the array one by one to print the name I want.
if (num >= 0 && num < numOfLoop) {
System.out.println("Looking for name: " + name[num]);
for (int i = 0; i <numOfLoop; i++) {
if(name[i].equals(name[num])) {
System.out.println(name[i] + " at index=" + i);
}
}
} else {
System.out.println("Invalid index, cannot be greater or equal to " + numOfLoop);
}
Sample output:
Input the number of names:
5
Input the names, one per line:
john
jeff
joan
john
jake
Input the index of the name to print:
0
Looking for name: john
john at index=0
john at index=3
You do not need the second loop.
All you need to do is to check if (num >= 0 && num < numOfLoop) and display the value of name[num] or an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numOfLoop = Integer.parseInt(in.nextLine()); // number of loops I want.
String[] name = new String[numOfLoop]; // size of the array is depend on how many loop I want.
// Getting the names using for loop.
for (int i = 0; i < numOfLoop; i++) {
name[i] = in.nextLine();
}
int num = Integer.parseInt(in.nextLine()); // The name I want to print depend on what number I enter here.
if (num >= 0 && num < numOfLoop) {
System.out.println(name[num]);
} else {
System.out.println("Invalid index.");
}
}
}
Also, use Integer.parseInt(in.nextLine()) instead of in.nextInt() for the reason mentioned at Scanner is skipping nextLine() after using next() or nextFoo()?
A sample run:
5
Johny
Arvind
Kumar
Avinash
Stackoverflow
3
Avinash
Scanner in = new Scanner(System.in);
int numOfLoop = in.nextInt(); //number of loops I want.
String[] name = new String[numOfLoop]; //size of the array is depend on how many loop I want.
for (int i=0; i<name.length; i++){
String names = in.next();
name[i] = names;
}
System.out.println("The names array: " + Arrays.toString(name));
for(int index=0;index<name.length;index++) {
System.out.print("Enter an index you want to print: ");
index = in.nextInt();
System.out.println("index " + index + " is: " + name[index-1]);
}
I am new to java and I am taking a college course right now. I was just curious what I am missing to give myself an output because right now the console is blank.
public static void main(String[] args) throws IOException {
double avgScore;
int highestScore, count = 0;
String highScoringStudent;
String names[] = null;
int scores[] = null;
File myFile = new File("Student_Data.txt");
Scanner inFile = new Scanner(myFile);
inFile.nextLine();
while(inFile.hasNext()) {
for(int i = 0; i > 0; i++) {
names[i] = inFile.next();
scores[i] = inFile.nextInt();
count++;
}
}
System.out.print("Name Score");
System.out.print(names[count] + " " + scores[count]);
}
First of all, I really wouldn't suggest to place a for inside a while loop, especially in this case (because it doesn't work). Here are the problems:
1) Your for loop starts with i = 0, and finishes right away, because !(i > 0) (i is not > 0) - so you are right, no data will be stored in the array!
2) Inside your for loop, you are reading a string, then an int one by one. After you have read them, you should move to the next string and integer to store in the next position of names and score.
3) You are not increasing i: so (if the for was working), you would just keep assigning different values to the array, at the same position (basically resetting the value of a variable every time).
This would be the best code that would work for your case:
int i = 0;
while(inFile.hasNext()) {
names[i] = inFile.next();
scores[i] = inFile.nextInt();
count++;
i++;
}
Hope this helped! :)
How can i put a value into each slot of the array. Meaning i have:
String name[] = new name[50];
for (int i=0; int<=name; int++;){
name[1] = "name 1";
name[2] = 'name 2";
}
This is what i have so far but i know that it is not right. I could make 50 different array and give name i could do name[1] = new name["kevin"]; and so on and keeping that for all 50 people.But that so many lines of code.
so how do i give all 50 a name. and i need to do in one loop or something like that.
or can i do this:
people[] people = new people[50];
If you want to assign a name to all of them according to the pattern name index you do it like this
for (int i = 0; i < name.length; i++) {
name[i] = "name " + (i + 1);
}
and by the way, initialize your array like this
String name[] = new String[50];
open Scanner for input, Take name as input and then loop over 50 times
// open Scanner for input
Scanner keyboard = new Scanner(System.in);
String name[] = new String[50];
for (int i=0; i< name.length; i++){
//take input
System.out.println("Input");
String input = keyboard.nextLine();
name[i] = input;
}
I'm a beginner programmer Java:
I want to get 10 values from user and put if statement, if some one enters grade value above 100, it may get "Enter right value < 100"
But i don't want to use any array etc.
When i use the following code, it shows the error message but for 1 wrong value, it calculates other 09 values and don't repeat the wrong value, given if statement skips the wrong
int i, number, total=0;
Scanner sc = new Scanner(System.in);
for (i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100);;
{total = total + number;}
}
int number, total=0;
int i = 1;
Scanner sc = new Scanner(System.in);
while (i<=10)
{
System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
i++;
}else{
System.out.println("invalid value");
}
}
This will work, using a while loop
You just had few typo errors in your code also , to make the for loop more simple you don't need to define i at top just define the i when you need to use the for loop . And its avoid overwrite outside of the for loop .
To make using for loop more professional also considering that maybe sometimes you need to use it for arrays its better to always start the loop with i=0 thats the better practice.
After if(condition) don't need to put any ;
int number, total=0;
Scanner sc = new Scanner(System.in);
for (int i=1; i<=10; i++)
{ System.out.print("Enter Grade "+i+" : \n");
number = sc.nextInt();
if (number < 100){
total = total + number;
}
}
I'm trying to make a basic program that allows the use to input and remove up to 10 contacts (a [10][4] array supposed to be filled with First Name, Last Name, Phone #, and age). However when I try to input the 5th contact eclipse gives me an error message. I'd like to know why I'm receiving an error message. (I assume it's something to do with the columns since it's whenever i'm inputting something >4, but i'm not sure what exactly.)
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args){
new Lab2 ();
}
// This will act as our program switchboard
public Lab2 (){
Scanner input = new Scanner(System.in);
String[][] personalInfo = new String[10][4];
System.out.println("Welcome to the contacts database.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("0: Exit the database.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContact(personalInfo);
break;
case 2:
removeContact(personalInfo);
break;
case 0:
System.out.println("Thank you for using the contact database.");
System.exit(0);
}
}
}
private void addContact(String personalInfo[][])
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println( " Hello user, please enter your contact info. (I.E. First and Last Names, Phone #, and Age. Max 10 Contacts)");
String addedContact = input.nextLine();
int j;
for(int i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j] == null)
{
personalInfo[i][j] = addedContact;
break;
}
}
}
}
private void removeContact(String personalInfo[][]) {
Scanner input = new Scanner(System.in);
System.out.print( " Please enter an existing contact that you would like to remove. ");
String deleteContact = input.nextLine();
int i , j;
for(i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j].equals(deleteContact))
{
personalInfo[i][j] = null;
break;
}
}
}
}
}
Try like this for(j = 0; j < personalInfo[i].length; j++){
First things first:
String[][] personalInfo = new String[10][4];
This statement creates a 2dimensional array of Strings, thus creating an array that is capable of holding an array that is capable of holding strings. (in this case 10 arrays that keep 4 strings each)
Now the error:
String addedContact = input.nextLine();
This line puts the entire line you added in a single string.
Now the loops:
1. The outer loop loops correctly through the 10 arrays of strings.
2. The inner loop does not loop through the '2nd dimension', that is the actual array which will hold your contact. This loop should be as #Kannan Thangadurai described:
for(j = 0; j < personalInfo[i].length; j++){
(add relevant code here)
}
The last error you made is more of a bug, and is in the way you read out the user input. You actually only ever put a string in the first array and so your four contacts that you saved will all be under personalinfo[1] then you try to add another contact in the fifth place of the array that does not exist, thus raising your error.
You're working with jagged array (or array of arrays)
String[][] personalInfo = new String[10][4];
so in order to itterate it you should use different lengths for dimensions (in general case the
required length is personalInfo[i].length):
for (int i = 0; i < personalInfo.length; ++i) // <- outer array
for (int j = 0; j < personalInfo[i].length; ++j) // <- inner length depends on i
if (personalInfo[i][j] == null) {
personalInfo[i][j] = addedContact;
break;
}