Object Array in JAVA giving InputMismatchException - java

Code and Snap of the Exception are attached. Pls Help me out with InputMismatchException. I believe there is something wrong while entering the value at runtime
import java.util.Scanner;
class ObjectArray
{
public static void main(String args[])
{
Scanner key=new Scanner(System.in);
Two[] obj=new Two[3];
for(int i=0;i<3;i++)
{
obj[i] = new Two();
obj[i].name=key.nextLine();
obj[i].grade=key.nextLine();
obj[i].roll=key.nextInt();
}
for(int i=0;i<3;i++)
{
System.out.println(obj[i].name);
}
}
}
class Two
{
int roll;
String name,grade;
}

Instead of :
obj[i].roll=key.nextInt();
Use:
obj[i].roll=Integer.parseInt(key.nextLine());
This ensures the newline after the integer is properly picked up and processed.

use Integer.parseInt(key.nextLine());
public class ObjectArray{
public static void main(String args[]) {
Scanner key = new Scanner(System.in);
Two[] obj = new Two[3];
for (int i = 0 ; i < 3 ; i++) {
obj[i] = new Two();
obj[i].name = key.nextLine();
obj[i].grade = key.nextLine();
obj[i].roll = Integer.parseInt(key.nextLine());
}
for (int i = 0 ; i < 3 ; i++) {
System.out.println("Name = " + obj[i].name + " Grade = " + obj[i].grade + " Roll = " + obj[i].roll);
}
}
}
class Two {
int roll;
String name, grade;
}
output
a
a
1
b
b
2
c
c
3
Name = a Grade = a Roll = 1
Name = b Grade = b Roll = 2
Name = c Grade = c Roll = 3

Related

Java: Both if and else statements run

I am trying to refector a 2D array project to include a search method to clean up the code in my main method. However, when I enter a valid name it can find the first row of data but will also print the else statement. If I enter a valid name for second row it will sometimes return it after printing the else statement.
I've tried rewriting the code, creating a return variable for the method, using a nested loop, modifying the return array value.
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("==== Family Affair ====");
System.out.println("How many members will you add?");
int number = scan.nextInt(); scan.nextLine();//scan.nextLine() ad hoc scan fix
//2D Array number of rows by scan/number input
String[][] familyData = new String[number][2];
//for loop captures input column data for each row
//nested loop created duplicate output
for (int i = 0; i < familyData.length; i++) {
System.out.print("\tName: ");
familyData[i][0] = scan.nextLine();
System.out.print("\tState: ");
familyData[i][1] = scan.nextLine();
System.out.println(" ");
}
System.out.println(" ");//extra space
printData(familyData);//call printData() method
findData(familyData);//call findData() method
}
public static void printData(String[][] data) {
for (int i = 0; i < data.length; i++) {
System.out.print("\tName: " + data[i][0] + " ");
System.out.print("\tState: " + data[i][1] + " ");
System.out.println(" ");
}
}
public static String[] findData(String[][] data) {
System.out.println("SEARCH...");
System.out.println("First Name: ");
String name = scan.nextLine();
String[] resultData = new String[0];
for (int i = 0; i < data.length; i++) {
if (name.equals(data[i][0])) {
System.out.println("--- Search Results ---");
System.out.println("\tName: " + data[i][0]);
System.out.println("\tState: " + data[i][1]);
}else {
System.out.println("Nothing found. Try Again");
System.out.println("First Name: ");
name = scan.nextLine();
}
}
return resultData; //returned as String[] results = findData(param);
}
Let me suggest the use of List<>
import java.util.ArrayList;
import java.util.List;
private static List<String[]> findData(String[][] source, String search)
{
final List<String[]> data = new ArrayList<>();
for (String[] array : source)
{
if (search.equals(array[0]))
{
data.add(array);
}
}
return data;
}
And here is an example of use
public static void main(String args[])
{
String[][] familyData = new String[2][2];
familyData[0][0] = "Sulabha";
familyData[0][1] = "Married";
familyData[1][0] = "Bertram";
familyData[1][1] = "Single";
List<String[]> data = findData(familyData, "Sulabha");
if (data.size() == 0)
{
System.out.println("Nothing found.");
}
else
{
for (String[] item : data)
{
System.out.println("--- Search Results ---");
System.out.println("\tName: " + item[0]);
System.out.println("\tState: " + item[1]);
}
}
}

Bubble sort and input

I have to enter 3 jumpers who will jump 2 times.
Here is an illustration via my console for the first jump. (it's step is ok)
Then, for the second jump. I have to sort the first jump from the smallest to the biggest.
So, I have to retrieve the jumper Emilie and not Olivia.
I don't understand how to do this ?
I think my problem is my sortBublle() method ?
import java.util.*;
class Main {
public static void main(String[] args) {
String[] arrayJumper = new String[3];
int[] arrayJump = new int[3];
encoding_jump_1(arrayJumper, arrayJump);
sortBublle(arrayJump);
encoding_jump_2(arrayJumper, arrayJump);
}
public static void encoding_jump_1(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJumper = 0;
int iJump = 0;
System.out.println("Jump 1 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter jumper " + (i+1) + " : ");
String jumper = input.next();
arrayJumper[iJumper++] = jumper;
System.out.print("Enter for the jumper " + arrayJumper[i] + " the first jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
public static void sortBublle(int[] arrayJump){
int size = arrayJump.length;
int tempo = 0;
for(int i=0; i<size; i++){
for(int j=1; j < (size - i) ; j++){
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
}
}
}
}
public static void encoding_jump_2(String[] arrayJumper, int[] arrayJump){
Scanner input = new Scanner(System.in);
int iJump = 0;
System.out.println("Jump 2 : ");
for(int i=0; i<arrayJumper.length; i++){
System.out.print("Enter for the jumper " + arrayJumper[i] + " the second jump please : ");
int jump = input.nextInt();
while(jump <= 9 || jump >=111){
System.out.print("Error ! The jump should to be between 10 and 100 please : ");
jump = input.nextInt();
}
arrayJump[iJump++] = jump;
}
}
}
Thank you very much for your help.
You are only sorting arrayJump --> You need to sort both arrayJumper and arrayJump`
...
if(arrayJump[j-1] > arrayJump[j]){
tempo = arrayJump[j-1];
arrayJump[j-1] = arrayJump[j];
arrayJump[j] = tempo;
tempName = arrayJumper[j-1];
arrayJumper[j-1] = arrayJumper[j];
arrayJumper[j] = tempName;
}

applying lambda expression in java

Here's my code.I'm not yet familliar with lambda expressions in java 8.
I'd like to apply a lambda expression here doing a random generation of healthy and unhealthy horses.
Then I'll print and run only the healthy horses. How can I do that?
import java.util.Scanner;
import java.util.Random;
public class HorseRace {
static int numHorse = 0;
static int healthyHorse = 0;
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
Horse[] horseArray = new Horse[numHorse];
while (counter < horseArray.length) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
horseArray[counter] = new Horse(warCry);
horseArray[counter].setName(horseName);
System.out.println(horseArray[counter]);
System.out.println(this);
System.out.println(healthyHorse);
//unhealthyHorse++;
}
counter++;
}
System.out.println(horseArray.length);
System.out.println("...Barn to Gate...");
for (int i = 0; i < healthyHorse; i++) {
horseArray[i].start();
}
}
}
I have refactored some of the code and used Lambda expressions wherever possible.
public class HorseRace {
public static void main(String[] args) {
//int unhealthyHorse = 0;
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int counter = 0;
int numHorse;
do {
System.out.print("Enter number of horses: ");
while (!input.hasNextInt()) {
input.next();
}
numHorse = input.nextInt();
} while (numHorse < 2);
input.nextLine();
List<Horse> horses = new ArrayList<>();
while (counter < numHorse) {
System.out.print("Name of horse " + (counter + 1) + ": ");
String horseName = input.nextLine();
String warCry = "*****************" + horseName + " says Yahoo! Finished!";
int healthCondition = randomGenerator.nextInt(2);
if (healthCondition == 1) {
Horse horse = new Horse(warCry);
horse.setName(horseName);
horses.add(horse);
}
counter++;
}
horses.forEach(horse -> {
System.out.println(horse);
System.out.println(0);
});
System.out.println(horses.size());
System.out.println("...Barn to Gate...");
horses.forEach(Horse::start);
}
}
Lambda expression is used as below:

How to use 2D arrays with other classes

I have an assignment, I was wondering how I could go about using 2D arrays with another class, I have a class called Die that looks like this:
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now in a main method i have to do the following
I have all the other parts done, I just cant seem to figure out this part.
My current code(Not started this part) is below
import java.util.Arrays;
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
String[] playerNames = new String[playerCount];
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
playerNames[i] = scan.nextLine();
}
int randomNum = (int)(Math.random() * (30-10)) +10;
}
}
Do any of you java geniuses have any advice for me to begin?
Thanks!
Here is your main method, you just need to update your main method with this one,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt();
scan.nextLine();
HashMap<String, ArrayList<Die>> hashMap = new HashMap<String, ArrayList<Die>>();
int again = 1;
for(int i = 0; i < playerCount; i++)
{
System.out.print("What is your name: ");
hashMap.put(scan.nextLine(),new ArrayList<Die>());
}
for(String key : hashMap.keySet()){
System.out.println(key + "'s turn....");
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
hashMap.get(key).add(d);
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(hashMap.get(key).size()>4){System.out.println("Sorry, Maximum 5-Try you can...!!!");break;}
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
hashMap.get(key).add(dd);
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
for(String key : hashMap.keySet()){
System.out.println(key + " - " + hashMap.get(key));
}
}
EDITED
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++){
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
String choice = scan.next();
while(choice != null && choice.equalsIgnoreCase("YES")){
if(totalRollDie < 5){ // if user want one more time to roll die then first check whether alread user has rolled 5-time or not.
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ; // rolled and print whatever value get..
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.next();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++){
finalDie[i][var] = tempDie[var]; // store Die object into finalDie array which can random number for all user..
}
}
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i]){
System.out.println(de);
}
}
tempDie = null;
}

How to fix my Array class

I am trying to figure out how to get my array to run correctly, I know I have to change the array value to an input but I cannot get the program to compile if any one can help that be great.
I am trying to have the program take input for grades and names of students and in the end output their name and grade.
Edit sorry this is my first it posting i have an error
Student.java:60: error: class, interface, or enum expected I am in java 101 so this is why it is such low level java, we only know the basics
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
and my second class is
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
} <--- error here
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
Add return statement in your multiplegradeinputs() method:
public String multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
return null; //Add this line
}
Or change your methods to void return type if they dont return anything.
Class names have to be capitalized in java, so instead of
public class students
you should write
public class Students
Also instead of writing
keyboard.nextInt();
You should write
Integer.parseInt(keyboard.nextLine());
This is mainly because java is full of bugs and technical specifications that you won't find easily. Let me know if this fixes it for you, since you didn't post the exact error message you got.
As for the error that you pointed out, it's because your function expects a String as a return value no matter what, so either change that to void if you can or return a null string. To do that just add the following line at the very end of the method.
return null;
You should create a Student object which holds the properties of the student, e.g. Name and Grades. You should then store all the student objects in some kind of data structure such as an array list in the students class.
Adding to the answer provided by #hitz
You have a bug in the for loops:
for(int i = 1; i <multiplegradeinputs.length; i++)
for(int i = 1; i < multipleStudent.length; i++)
You will never populated multiplegradeinputs[0] and multipleStudent[0] because you start the loop at index == 1 and thus you will have only 9 student names stored instead of 10.
Change to:
for(int i = 0; i <multiplegradeinputs.length; i++)
for(int i = 0; i < multipleStudent.length; i++)
Remember even though the length in 10, the indices always start with 0 in Java and in your case will end with 9.
import java.util.Scanner;
public class Student
{
Scanner scan = new Scanner(System.in);
private String name;
private int grade;
private int[] multiplegradeinputs = new int[10];
private String[] multipleStudent = new String[10];
public Student()
{
}
public Student(String n, int g)
{
name = n;
grade = g;
}
public String setMultipleStudents()
{
String n = "";
for(int i = 1; i < multipleStudent.length; i++)
{
System.out.println("Enter student #" + i +" name: " );
n = scan.nextLine();
multipleStudent[i] = n;
}
return null;
}
public void multiplegradeinputs()
{
for(int i = 1; i <multiplegradeinputs.length; i++)
{
System.out.println("Enter the Grade of the student#" + i +" : ");
grade = scan.nextInt();
multiplegradeinputs[i] = grade;
}
}
public String toString()
{
String temp = "";
for(int i = 1; i < multipleStudent.length; i++)
{
temp += multipleStudent[i] + " ";
}
return temp;
}
}
this is the 2nd class
import java.util.Scanner;
public class students
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many students?: ");
int numofstudents = keyboard.nextInt();
Student s = new Student();
s.setMultipleStudents();
s.toString();
System.out.println("Enter the Grade for the student: ");
int gradeofstudnets = keyboard.nextInt();
}
}
You are missing a return value in the multiplegradeinputs() method.

Categories

Resources