Scanner automatically assigned first input to an empty string, why is that? - loops

I am very much a beginner so forgive me if I made an obvious mistake. I tried to create a HashMap of a student list by getting input from user via scanner but somehow the scanner skipped the first key and automatically assigned it to an empty string?
Here's my code in details:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputvalue = new Scanner(System.in);
HashMap<Integer, String> studentName = new HashMap<Integer, String>();
String student;
int counter = 1;
int classSize;
System.out.println("Enter class size: ");
classSize = inputvalue.nextInt();
do {
System.out.println("Enter " + counter + " student name: ");
student = inputvalue.nextLine();
studentName.put(counter, student);
counter++;
} while(counter <= classSize);
System.out.println(studentName);
}
I tried using a for loop instead but it didn't work either. Please elaborate to me what made the scanner skip first key and how to fix this bug. Thank you so much in advanced

Related

string accept error name accept part getting skipped

This is the my code and the problem is using array i am taking names and their marks input and want to print then serially but the name accepting part is not working it is taking number inputs but not the names
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
I used to encounter this error early on in my Java journey. The problem is with the Scanner class, probably a bug.
The solution that I used was to create 2 scanner class objects. One for the numeric values and the other for String values. Here is the modified code:-
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
Scanner sc1 = new Scanner(System.in); // new scanner object for Strings
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc1.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
While this helps, it would be better to switch to BufferedReader and BufferedWriter class :)

How can I create a loop to randomly assign values to each characteristic of an array of class instances

So I am creating a card game that requires different cards, so I created a card class in which I declared the string value names and other integer values that are the powers eg. Intelligence
public static class hero{
static String name;
static int strength;
static int intellect;
static int flight;
static int tech;
}
So I created an array of instances of these classes.
Their names are read from a text file and assigned to the name value.
Q1) I am having trouble with reading through the file and assigning the string to the name value of each instance of the class.
This is what I've done so far
public static void readLines(File f)throws IOException{
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
fr.close();
}
static File f = new File("C:/Users/jeff/Desktop/test/names.txt");
try{
readLines(f);
} catch (IOException e){
e.printStackTrace();
}
Q2)The part I am also having trouble with is the part where I need to create a loop to randomly assign values to each power of each instance of a class.
Here's what I've done so far
{
hero [] cards = new hero[cardNumber];
for(int i=4;i<cardNumber;i++){ cards[i]=new hero();}
Random rand = new Random();
for(int i=0; i<cards.length; ++i)
{
cards[i].strength = rand.nextInt(25) + 1;
cards[i].intellect = rand.nextInt(25) + 1;
cards[i].flight = rand.nextInt(25) + 1;
cards[i].tech = rand.nextInt(25) + 1;
}
But when I print out the values all the instances have the same value for their powers.
Eg Card 12 Intelligence = 6
And Card 14 Intelligence = 6
Can anyone please help me with these issues, and any guidance will be highly appreciated
Thank you

Java loops using a Scanner class and I can use breaks

I am trying to figure out how to use the scanner class with a loop. I cannot use break as part of my code. I am unsure how close I am, but any help would be much appreciated.
import java.util.Scanner;
public static void main(String[] args) {
Scanner i = new Scanner(System.in);
System.out.print("Please enter a number between 1 and 10: ");
int number = i.nextInt();
boolean value = number>=1 && number <=10;
while (number >=1 && number <=10){
System.out.println ("Good Job!");
}
if (number <=1 && number >=10 )
continue;
{System.out.print ("You have entered an incorrect number. Please try again");
System.out.println("Please try again:");
Scanner r = new Scanner(System.in);
return;
}
The Scanner class can be used like this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// now loop while the scanner is available
while(scanner.hasNext()) {
// print out every single number input from standard input
System.out.println("Scanner inputed from stdin is " + Integer.toString(scanner.nextInt());
}
}
You can do like this:
import java.util.Scanner;
import java.util.Stack;
public class ScannerDemo {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String next = scan.next();
if("quit".equals(next)) break;
System.out.println("Element: " + next);
}
scan.close();
}
}
Press quit to exit.

How to find a state in an array

I need help with how to find and display the state information the user chose to the screen. I have five files which i have put into arrays. The five arrays contain information of a state(State Name, state capital,state nickname, State flower, state population.)
My program should allow the user of the program to enter a state name, and should display the information about that state (nickname, capital, flower, and population) to the screen.
Each input file contains the information in alphabetical order by state name. So line 1 of the state name file is Alabama, line 1 of the capital file is Montgomery (the capital of Alabama), line 1 of the flower file is the state flower for Alabama, line 1 of the nickname file is the nickname of Alabama, and line 1 of the population file is the population o``f Alabama. Line 2 of each file is info for Alaska, line 3 is for Arizona, etc.
This is my code so far.
public static void main(String[] args) throws FileNotFoundException {
String capital, stateFlowers, stateNickName, statesNames;
int statePopulation;
Scanner keyboard = new Scanner (System.in);
String userStateChoise;
File capitals = new File("capitals.txt");
File flores = new File("flowers.txt");
File nickName = new File("nicknames.txt");
File populacion = new File("population.txt");
File state_Name = new File("stateNames.txt");
System.out.println("Enter a State Name");
userStateChoise = keyboard.nextLine();
if (!capitals.exists()) {
System.out.println("The capitals input file was not found");
System.exit(0);
}
if (!flores.exists()) {
System.out.println("The flores input file was not found");
System.exit(0);
}
if (!nickName.exists()) {
System.out.println("The nickName input file was not found");
System.exit(0);
}
if (!populacion.exists()) {
System.out.println("The populacion input file was not found");
System.exit(0);
}
if (!state_Name.exists()) {
System.out.println("The stateName input file was not found");
System.exit(0);
}
Scanner inputFile = new Scanner(capitals);
Scanner flower = new Scanner(flores);
Scanner nickNames = new Scanner(nickName);
Scanner populations = new Scanner(populacion);
Scanner names = new Scanner(state_Name);
// ArrayList myCapitals = new ArrayList();
// ArrayList<String> stateNames = new ArrayList();
while (inputFile.hasNext() && flower.hasNext() && nickNames.hasNext()
&& populations.hasNext() && names.hasNext())
{
// reading all states from the input file
//reading all cities from the input file
capital = inputFile.nextLine();
stateFlowers = flower.nextLine();
stateNickName = nickNames.nextLine();
statePopulation = populations.nextInt();
statesNames = names.nextLine();
String[] stateCapitalArray = {capital};
String[] stateflowersArray = {stateFlowers};
String[] stateNickNameArray = {stateNickName};
int [] statePopulationArray = {statePopulation};
String[] stateNamesArray = {statesNames};
// I used for loops to go through each item in the array and to display it to the screen
for (int index = 0; index < stateNamesArray.length; index++)
{
System.out.println("State name : " +stateNamesArray[index]);
}
for (int index = 0; index < stateflowersArray.length; index++)
{
System.out.println("State flower : " + stateflowersArray[index]);
}
for (int index = 0; index < stateCapitalArray.length; index++)
{
System.out.println("The capital : " + stateCapitalArray[index]);
}
for (int index = 0; index < stateNickNameArray.length; index++)
{
System.out.println("State nickName : " + stateNickNameArray[index]);
}
for (int index = 0; index < statePopulationArray.length; index++)
{
System.out.println("State pupoluation : " + statePopulationArray[index]);
System.out.println("\n\n\n");
}
}
inputFile.close();
flower.close();
nickNames.close();
// populations.close();
}
}
Besides the awkward method of collecting and storing the information and getting user input, the most glaring error I see is how you're building your array. Every time you read a new line you're reinitializing each array with one thing instead of adding each thing to each array.
You'll end up with arrays of the last item from every file. The arrays should be created and initialized outside of the while loop and each item added to them as you read them.

Processing: assign a value to each object in an array?

Sorry this is probably a dumb question. I'm kinda new to coding and I'm using Processing, which is based off Java.
I have an array of 5 rectangle objects in my main program
for (int i = 0; i < portals.length; i++)
{
portals[i] = new Portals();
}
when displayed, I call this method from my Portals class
void display()
{
rectMode(CENTER);
rect(xLoc, yLoc, rad, 30);
}
the xLoc and yLoc are determined randomly. How would you go about assigning a number (like an identity) to each object in the array so that I can refer to that specific rectangles's location and where would I put it in my code?
You can have a filed in the class that makes it identifiable. Like:
public class Portals {
int xLoc;
int yLoc;
String name;
...
public Portals(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Then you can try to access by name in array
for (int i = 0; i < portals.length; i++)
{
portals[i] = new Portals("Name");
}
for (Portals p : portals){
if ("Name".equals(p.getname()) {
// do somthing
}
}
Or you can use a Map. But that may be more advanced than your knowledge, so I won't give code. But that's another suggestion.
Edit: with Map
Map<String, Portals> map = new HashMap<String, Portals>();
Key Value
map.put("nameForPortal", new Portals());
map.put("anotherNameForPortal", new Portals());
// To access the portal, you can get by the key
Portals p = map.get("nameForPortal");

Resources