Java loops using a Scanner class and I can use breaks - loops

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.

Related

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

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

Java - Creating a menu method - Lots of trouble

I am tasked with making a word game that has 2 options, plus an exit option. I must make a separate method for each option and am currently working on the method that displays the menu options and gets the users input, then returns that input to the called methods.
This is where I'm at so far. My goal with this code is to get a user to select option 1, 2 or 3 with error checking to force the user to input 1, 2 or 3. Current problems are that inputting option 1, 2 or 3, will print the statement, followed by an extra print statement from both option 1, 2 and 3. Inputting a number outside of 1, 2 and 3 doesn't print the error statement, but does allow the user to input again. Also inputting anything other than a number will endlessly run the loop.
import java.util.Scanner;
public class Small_Programming_Assignment {
public static void main(String[] args) {
getSelection();
substringProblem();
pointsProblem();
}
public static void getSelection() {
int selection = -1;
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
selection = scanner.nextInt();
while (selection < 1 || selection > 3) {
System.out.println("Enter your selection: ");
if(scanner.hasNextInt())
selection = scanner.nextInt();
}
switch(selection) {
case 1:
substringProblem();
break;
case 2:
pointsProblem();
break;
case 3:
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option. Try again. ");
}
}
public static void substringProblem() {
System.out.println("Game 1");
}
public static void pointsProblem() {
System.out.println("Game 2");
}
}
2 problems.
public static void main(String[] args) {
getSelection();
// substringProblem();
// pointsProblem();
}
public static void getSelection() {
int selection = -1;
// Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selection: ");
// selection = scanner.nextInt();
boolean running = true;
// make sure running until the input is 3
while (running) {
Scanner scanner = new Scanner(System.in);
selection = scanner.nextInt();
while (selection < 1 || selection > 3) {
System.out.println("Enter your selection: ");
if(scanner.hasNextInt())
selection = scanner.nextInt();
}
switch(selection) {
case 1:
substringProblem();
break;
case 2:
pointsProblem();
break;
case 3:
System.out.println("Goodbye");
// stop
running = false;
break;
default:
System.out.println("Invalid option. Try again. ");
}
}
}

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 :)

Implementing arrays for a Palindrome program

I am working on creating a program that reads strings in from a data file calles "palindromes.txt" and which stores the strings in a one-dimensional array. The program is supposed to inspect each of the strings and detrmine whether or not each one is a pallindrome. It's supposed to show output on the screen and into a file called "output.txt".
The problem i'm having is that I can't figure out how to get the input/output correct and i'm not sure the best way to utilize the arrays.
Very new to this, please advise if you can. :)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Palindromes2
{
public static boolean isPalindrome(String dirtystr)
{
dirtystr = dirtystr.toLowerCase().replaceAll("[^a-zA-Z]+","");
int length = dirtystr.length(), middle = length / 2;
for (int x = 0; x < middle; x++)
if (dirtystr.charAt(x) != dirtystr.charAt(length - x - 1))
return false;
return true;
}
public static void main(String[] args) throws IOException
{
File inputFile = new File("output.txt");
try (Scanner scanner = new Scanner(inputFile))
{
while (scanner.hasNextLine())
{
String dirtystr = scanner.nextLine();
if (isPalindrome(dirtystr))
{
System.out.println(dirtystr + " IS a palindrome.");
}
else
{
System.out.println(dirtystr + " is NOT a palindrome.");
}
}
}
}
}

How to return a value of a variable so that another class can use that value to access a value in an array

I am trying to return a variable 'i' which stores the position of a value in an array.I want to return the value of 'i' so that the other classes can use the value to access another value in an array(this might sound a little dumb).How do I do that ?
import java .io.*;
public class Login{
public int i;
public void Menu1()throws IOException
{
int flag=0;
int goal=0;
String p;
String Username[]={"Mohit","Rahul","Mehul","Kevin","Tony"};
String MNumber[]={"8720765181","8659133560","9869206216","9767445692","9967129878"};
String Password[]={"1234","5678","9012","3456","7890"};
int Balance[]={20,124,256,67,512};
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
do
{
System.out.println("Enter your Username");
String username=br.readLine();
for(i=0;i<5;i++)
{
if(username.equals(Username[i])){
flag=1;
break;
}}
if(flag==1)
{
System.out.println("Enter your password");
p=br.readLine();
if(p.equals(Password[i]))
{
goal=1;
}
if(goal==1)
{
System.out.println("Password matched");
System.out.println("Welcome Mr."+Username[i]+".Your Registired Mobile number is "+MNumber[i]);
System.out.println("It has a balance of Rs."+Balance[i]+" which will expire on 20th August 2025");
goal=1;
Second_Menu sm=new Second_Menu();
sm.main();
}
else
System.out.println("Incorrect password,please retry");
}
else
System.out.println("incorrect username,please retry");
}while(goal!=1);
}
}
This is the class in which I want to call the value.
import java.io.*;
public class Recharge
{
public void recharge()throws IOException {
int Balance[]={20,124,256,67,512};
int chcea;
double recAmt=0;
double u;
int i=0;
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Choose an option");
System.out.println("1.Recharge your account");
System.out.println("2.Return to Main Menu");
chcea=Integer.parseInt(br.readLine());
System.out.println("You choose option number "+chcea+".Proceed(y or n)");
String answ=br.readLine();
switch(answ)
{
case "y":
switch(chcea)
{
case 1:System.out.println("For the first time India a Mobile Service Provider gives you the freedom to recharge with a coustom amount");
System.out.println("Please enter a recharge amount");
recAmt=Double.parseDouble(br.readLine());
System.out.println("Your entered amount is Rs."+recAmt+".Proceed(y or n)");
String optyn=br.readLine();
switch(optyn)
{
case "y":System.out.print("Please wait");
for(int wait=0;wait<=5;wait++);
{for(int tmp=0;tmp<=999999999;tmp++){}
System.out.print(".");
}
System.out.println("Your account has been successfully recharged.");
System.out.println("Your new Balance is Rs."+(Balance[i]+recAmt));
break;
case "n":break;
default:System.out.println("Please enter a valid choice");
break;
}
case 2 :Second_Menu sm= new Second_Menu();
sm.main();
break;
}
case"n":break;
}
}
}
I want to return the value of 'i' from the first class so that the second class can use it to access the value in the array 'Balance[]' for the right user.I also want that after recharge the value of balance of that user(i) changes to the new recharged amount.
if you make the int i public other classes can use it and if you make it static, if a constructor or something changes it, it changes the value for the whole program
try to make the int i a
public static int i

Resources