import java.util.Scanner;
public class NoteIt {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
int Answer;
int i=2;
System.out.print("\nPlease Enter your Name: ");
String Name = s.nextLine();
System.out.println("Welcome to Note-It "+Name+", We hope you'll enjoy our application. ");
String[][] Main = new String[2][2];
Main[0][0]="Create new Note";
Main[1][0]="View My Notes";
while(true) {
System.out.println("\nPlease select what to do: \n");
for (int n = 0; n < 2; n++) {
System.out.println((n + 1) + ") " + Main[n][0]);
}
System.out.print("\nPlease enter your response: ");
Answer = s.nextInt();
if (Answer == 1) {
i++;
Main = new String[i][2];
System.out.print("\nTitle: ");
Main[i - 1][0] = s.next();
System.out.print("Body: ");
Main[i - 1][1] = s.next();
} else if (Answer == 2) {
for (int k = 2; k < i; k++) {
System.out.println(k - 1 + Main[k][0]);
}
}
}
}
}
why did array main become null after one while loop?? When I run the program once everything is perfect, but in the second loop "create new note" and "view your notes", both become null.
Main = new String[i][2];
Here you created a new Array
If you want to Resize the array you have 2 options
Either use java.util.ArrayList or java.util.Vector instead of native array
Or Create a new array and copy old data into new array
Try this code made some minor adjustments
import java.util.Scanner;
public class Main {
public static void main(String[]args) {
Scanner s = new Scanner(System.in);
int Answer;
int i=1;
System.out.print("\nPlease Enter your Name: ");
String Name = s.nextLine();
System.out.println("Welcome to Note-It "+Name+", We hope you'll enjoy our application. ");
String[][] Main = new String[10][2];
//String[] Main1 = new String[2];
Main[0][0]="Create new Note";
Main[0][1]="View My Notes";
/**for( int j=0;j<2;j++ )
Main[j]= new String[2];*/
while(true) {
System.out.println("\nPlease select what to do: \n");
for (int n = 0; n < 2; n++) {
System.out.println((n + 1) + ") " + Main[0][n]);
}
System.out.print("\nPlease enter your response: ");
Answer = s.nextInt();
s.nextLine();
if (Answer == 1) {
i++;
System.out.print("\nTitle: ");
Main[i - 1][0] = s.nextLine();
System.out.print("Body: ");
Main[i - 1][1] = s.nextLine();
} else if (Answer == 2) {
for (int k = 1; k <i; k++) {
System.out.println(1 + Main[k][0]);
}
}
}
}
}
There might be some elements not upto your requirement please change them according to your preferences. Also have fixed the skipping of body.
First, check how the 2D array works. You have declared new String[2][2]. Then it works [0][0], [0][1],[1][0],[1][1].
Then check with you value assigning points.
Related
So, this below is my code:
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
while((res.toUpperCase()).equals("YES")) {
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
for(int i=1; i<50; i++) {
names[i] = n;
}
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
for(int j=0; j<50; j++) {
rolls[j] = r;
}
}
for(int a=0; a<50; a++) {
System.out.println(names[a]);
System.out.println(rolls[a]);
}
}
}
What I want is to happen is that, the program should keep registering students name and roll no. until the array is full or the user ends it. How do I do it ? I got that far
You need to have the "continue" question in the while loop, and you don't need the for loop every time you insert a name.
public class StudentRun {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[50];
int[] rolls = new int[50];
int index = 0;
while(true) {
System.out.print("Do you want to register a student ?(yes/no): ");
String res = sc.nextLine();
if(res.toUpperCase().equals("NO") || index == 50)
break;
System.out.print("Enter the student's name: ");
String n = sc.nextLine();
names[index] = n;
System.out.print("Enter their roll number: ");
int r = sc.nextInt();
rolls[index] = r;
index++;
}
for(int i=0; i<50; i++) {
System.out.println(names[i]);
System.out.println(rolls[i]);
}
}
}
A common approach when using fixed sized arrays is to use a separate int variable to track the current index position for a new item, as well as the total used slots in the array:
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int size = 50;
String[] names = new String[size];
int[] rolls = new int[size];
int counter = 0;
String res = "";
do {
System.out.print("Do you want to register a student ?(yes/no): ");
res = sc.nextLine().toUpperCase();
if (res.equals("YES")) {
System.out.print("Enter the student's name: ");
names[counter] = sc.nextLine();
System.out.print("Enter their roll number: ");
rolls[counter] = sc.nextInt();
sc.nextLine(); // clear enter out of buffer;
counter++;
}
} while (counter < size && res.equals("YES"));
for(int a=0; a<counter; a++) {
System.out.print(names[a] + " : ");
System.out.println(rolls[a]);
}
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I was writing code to display name of friends using string in java by getting input. But index 0 is not getting a entry
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = Integer.parseInt(input.nextLine());
String[] friends = new String[a];
for (int i = 0; i < a; i++) {
System.out.print("Enter the name of your friend " + (i + 1) + ":");
friends[i] = input.nextLine();
}
for (int j = 0; j < a; j++) {
System.out.println("Name of your friend " + (j + 1) + "is " + friends[j].toUpperCase());
}
}
You need to consume the end of the line that contains the input integer, as explained in comments.
import java.util.Scanner;
public class stringclass {
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of friends: ");
int a = input.nextInt();
// This is what you want
input.nextLine();
String [] friends = new String[a];
int count=1;
for(int i=0;i<a;i++){
System.out.println("Enter the name of your friend "+count +":");
friends[i] = input.nextLine();
count++;
}
int count1=1;
for (int j=0;j<a;j++){
System.out.println("Name of your friend "+count1+ "is "+friends[j].toUpperCase());
count1++;
}
}
}
I'm a beginner and I've been really stuck on this problem. I'm not really sure how I can display the number of customer(in an arraySize) (customer #1, customer #2...) and ask for their name in a for loop.
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + arraySize + ": "
}
I've tried dinerArray.length and then i, arraySize with i, (i=0;i<=arraySize;i++) with arraySize/i.. but nothing seems to work. It would either only print once with customer#0 or print nothing at all
You need to change arraySize to i. That way it will produce customer#1,customer#2 etc....
String [] dinerArray;
//initialize our array
dinerArray = new String[arraySize];
for (int i = 1; i == arraySize; i++)
{
System.out.println("enter the name of customer#" + i+ ": ");
}
If you just want to read them from the console, you can use a Scanner:
Scanner input = new Scanner(System.in);
int arraySize = 10;
String[] dinerArray = new String[arraySize];
for(int i = 0; i < arraySize; ++i)
{
System.out.print("Enter the name of customer#" + (i + 1) + ": ");
dinerArray[i] = input.nextLine();
}
input.close();
im no Java dev but this is pretty basic.
The problem is that your for loop is just running if i is equal to arraySize, but this never happen.
So, try to change your '==' to a '<='
My solution:
Scanner scan = new Scanner(System.in);
int arraySize = 5;
String[] dinerArray = new String[arraySize];
for(int i = 1; i <= dinerArray.length; i++) {
ystem.out.print("pleas enter name for customer#" + i);
dinerArray[i - 1] = scan.nextLine();
}
Im not sure about the scanner think.
I am working on a program that allows a user to add values to a 2d array and then search the array and display the value. The information is being stored properly, but all I can get to display is the animal name and not the food. Before I get grilled I've searched and implemented a bunch of different methods trying to get the correct output. I'm sure my error is pretty simple if someone could just help me understand, thanks!
/*This program will allow a user to enter information into the zoo
or search by animal for the type of food it eats*/
import java.util.Scanner;
class zoo {
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
//prompt the user to search or quit
System.out.println("Please enter the name of the animal to search for or Q to quit: ");
String animalName = in.nextLine();
animalName = animalName.toUpperCase();
if(animalName.equals("Q")){
System.out.println("Thanks for using the program!");
}
else {
searchArray(animalName);
}
return animalFood;
}
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
arrayItem = animalFood[i][j];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
}
else {
//nothing found
}
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
//constructor
public zoo() {
}
//overloaded constructor
public zoo(int x) {
int number = x;
animalFood = addArray(x);
}
//method to get users choice
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
System.out.println("Please make a choice in the menu below");
System.out.println("-------------------------\n");
System.out.println("1 - Add animals and the food they eat.");
System.out.println("2 - Search for an animal in the zoo.");
System.out.println("3 - Exit the program");
selection = input.nextInt();
return selection;
}
//main method
public static void main(String[] args) {
//create a new object
zoo myZoo = new zoo();
//variables and scanner
int userChoice;
int numberAnimals;
String animalName = "";
Scanner input = new Scanner(System.in);
//call the menu
userChoice = menu();
//actions based on user choice
if (userChoice == 1) {
System.out.println("How many animals would you like to enter information for?");
numberAnimals = input.nextInt();
myZoo.addArray(numberAnimals);
}
if (userChoice == 2) {
System.out.println("Please enter the name of the animal to search for: ");
animalName = input.nextLine();
myZoo.searchArray(animalName);
}
if (userChoice == 3) {
System.out.println("Thank you for using the program!");
}
}
}
It looks to me like your problem is in searchArray. Your nested for loops are iterating over the size of only one dimension of the array:
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
...
}
}
Replace animalFood.length with animalFood[i].length, like you did correctly in the addArray method.
EDIT
It also looks like your output method is incorrect.
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
In this line, animalFood[j] should be animalFood[i][j]. The strange output you're seeing is Java's attempt at converting an array into a String.
2nd Edit
After examining the addArray method, it seems I've made an incorrect assumption about your array. It appears your array is structured such that each index has 2 items, the animal, and its food. So it looks like so:
animalFood[0][0] = 'Cat'
animalFood[0][1] = 'Cat food'
animalFood[1][0] = 'Dog'
animalFood[1][1] = 'Dog food'
etc.
If this is the case, then you're going to want to change your loop to only iterate over the outer index. This means removing the inner for loop inside of searchArray. Then, you're only going to compare the first index of the inner array to the item you want to match, and if there's a match, then the food will be the second index. I'll leave implementation up to you (since this looks like a homework question). If something I've said here sounds wrong, let me know.
okay so i have this code and i would like to store the values of an array of integers intwholef[x] and store those values in the array wholelist[y]. the only problem is that the way i have it set up is that im taking the first three values of the array and storing them in intwholef[x] and then x is resetting as it passes on the the next line. a graphical representation is below
This is the contents of the file stored in an array of strings
intwholef[0] = 1 3 10
intwholef[1] = 2 4 15
intwholef[2] = 3 6 8
intwholef[3] = 4 7 3
intwholef[4] = 5 9 12
now what i WANT is those values to be stored like this.
wholelist[] = 1,3,10,2,4,15,3,6,8,4,7,3,5,9,12
and be accessible like
wholelist[2] * wholelist[5] = 150;
the problem that im running into is that im not able to save the values in a list like this, any ideas?
here is the whole code, the part im talking about is at the bottom
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class project1
{
#SuppressWarnings("null")
public static void main(String[] args)
{
System.out.println("These are your following choices: ");
System.out.println("1. First-Come First-Served (FCFS): ");
System.out.println("2. Shortest Job Next (SJN): ");
System.out.println("3. Shortest Remaining Time (SRT): ");
System.out.println("4. Round Robin (RR) with time quantum = 4 ms: ");
System.out.println("please enter your choice by entering 1, 2, 3, 4");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
if(choice ==1)
{
System.out.println("your choice was first come first serve");
}
else if(choice == 2)
{
System.out.println("your choice was shortest job next");
}
else if(choice == 3)
{
System.out.println("your choice was shortest job remaining");
}
else if(choice == 4)
{
System.out.println("your choice was round robin (rr) with time quantum = 4 ms");
}
else
{
System.out.println("you entered an invalid choice");
}
BufferedReader file = null;
System.out.println("Please enter the file path for your input");
Scanner fp = new Scanner(System.in);
String input = fp.nextLine();
String fileloc;
String[] wholef = null;
int fline = 0;
try
{
file = new BufferedReader(new FileReader(input));
fileloc = file.readLine();
fline = Integer.parseInt(fileloc); // this stands for file contents from the file to be read
wholef = new String[fline];
int i = 0;
while((fileloc = file.readLine()) != null)
{
wholef[i] = fileloc;
System.out.print("the contents of this file are: ");
System.out.println(fileloc);
i++;
}
System.out.println("This is the contents of the file stored in an array of strings");
for(int n = 0; n < fline; n++)
{
System.out.println(wholef[n]);
}
} catch (IOException er)
{
er.printStackTrace();
}
finally
{
try
{
if(file != null)
{
file.close();
}
} catch(IOException erx)
{
erx.printStackTrace();
}
}
System.out.println("This is the size of the contents of the file");
for(int n = 0; n < fline; n++)
{
System.out.println(wholef[n].length());
}
System.out.println("this is the input file converted and stored into an array of integers");
String[] parts = null;
int[] intwholef = null;
int[] wholelist =null;
for(int x = 0; x < fline; x++)
{
parts = wholef[x].split(" ");
intwholef= new int[parts.length];
for(int n = 0; n < parts.length; n++)
{
intwholef[n] = Integer.parseInt(parts[n]);
System.out.println(/*"intwholef[" + n + "] = " + */intwholef[n]);
for(int m = 0; m < parts.length; m++)
{
//wholelist[m]= intwholef[n];
}
}
}
System.out.println("this is the list of number from the conversion dumped into a singular array list");
for(int i = 0; i < 15; i++)
{
System.out.println("intwholef[" + i + "] = " + wholelist[i]);
}
/*
System.out.println("operations done with array of ints");
for(int i = 0; i < 20; i++)
{
System.out.println(intwholef[i]);
}
//System.out.println(intwholef[0] * intwholef[3]);
*/
}
}
I suggest you use a List (like ArrayList) instead of an array as the size of it can change. As such:
ArrayList wholeList = new ArrayList<Integer>();
for(int x = 0; x < fline; x++)
{
parts = wholef[x].split(" ");
for(int n = 0; n < parts.length; n++)
{
wholeList.add(Integer.parseInt(parts[n]));
}
}
Then you can access the different values with wholeList.get(index).
You can do it simply using an ArrayList. If you want to end up with an Array, use the toString method. Split the string with \\s, so that any whitespace can serve as delimiter. Also, you only need only loop, like this:
int[] myArray = new int[10];
List<Integer> list = new ArrayList<Integer>();
while ((fileloc = file.readLine()) != null) {
for (String s : fileloc.split("\\s+")) {
list.add(Integer.parseInt(s));
}
System.out.println(Arrays.toString(myArray));
}
int[] wholelist = list.toArray();