當前位置: 首頁>>代碼示例>>Java>>正文


Java Scanner.hasNextInt方法代碼示例

本文整理匯總了Java中java.util.Scanner.hasNextInt方法的典型用法代碼示例。如果您正苦於以下問題:Java Scanner.hasNextInt方法的具體用法?Java Scanner.hasNextInt怎麽用?Java Scanner.hasNextInt使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.Scanner的用法示例。


在下文中一共展示了Scanner.hasNextInt方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: scannerDemo1

import java.util.Scanner; //導入方法依賴的package包/類
public static void scannerDemo1() {
	Scanner scan = new Scanner(System.in);
	// 從鍵盤接收數據
	int i = 0;
	float f = 0.0f;
	System.out.print("輸入整數:");
	if (scan.hasNextInt()) {
		// 判斷輸入的是否是整數
		i = scan.nextInt();
		// 接收整數
		System.out.println("整數數據:" + i);
	} else {
		// 輸入錯誤的信息
		System.out.println("輸入的不是整數!");
	}
	System.out.print("輸入小數:");
	if (scan.hasNextFloat()) {
		// 判斷輸入的是否是小數
		f = scan.nextFloat();
		// 接收小數
		System.out.println("小數數據:" + f);
	} else {
		// 輸入錯誤的信息
		System.out.println("輸入的不是小數!");
	}
}
 
開發者ID:leon66666,項目名稱:JavaCommon,代碼行數:27,代碼來源:ScannerDemo.java

示例2: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
    //get input
    Scanner sc = new Scanner(System.in).useDelimiter(" ");
    ArrayList<Integer> input = new ArrayList<>();
    //add input to ArrayList
    while (sc.hasNextInt()) {
        input.add(sc.nextInt());
    }
    //sort the list
    Collections.sort(input);
    //initialize closest values, with the first two elements in the list
    int closest = input.get(1)-input.get(0);
    //check all elements in the list
    for(int i = 2; i < input.size(); i++) {
        //change closest if we find two elements with a shorter distance.
        closest = Math.min(closest, input.get(i)-input.get(i-1));
    }
    //print the shortest distance
    System.out.println(closest);
}
 
開發者ID:BaReinhard,項目名稱:Hacktoberfest-Data-Structure-and-Algorithms,代碼行數:21,代碼來源:Closest.java

示例3: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter your age in years: ");
    double age = input.nextDouble();
    System.out.print("Enter your maximum heart rate: ");
    double rate = input.nextDouble();
    double fb = (rate - age) * 0.65;
    System.out.println("Your ideal fat-burning heart rate is " + fb);
    
    System.out.print("\nPlease enter an Integer: ");
    while(!input.hasNextInt()) {
        input.nextLine();
        System.out.print("Invalid integer; please enter an integer: ");
    }
    int i = input.nextInt();
    System.out.println("Done");
}
 
開發者ID:Driveron,項目名稱:Notes,代碼行數:18,代碼來源:InputExample.java

示例4: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    while (in .hasNextInt()) {
        int n = in .nextInt();
        int p = in .nextInt();
        MyCalculator my_calculator = new MyCalculator();
        try {
            System.out.println(my_calculator.power(n, p));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
 
開發者ID:rshaghoulian,項目名稱:HackerRank_solutions,代碼行數:14,代碼來源:Solution.java

示例5: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
    Scanner x = new Scanner(System.in);
    while (x.hasNextInt()) {
        int d = x.nextInt();
        if (d != 0) {
            func(d);
        } else {
            System.exit(0);
        }
    }
}
 
開發者ID:bakhodirsbox,項目名稱:AlgoCS,代碼行數:12,代碼來源:Maximum_1079.java

示例6: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
	ProgressFrame pf = new ProgressFrame();
	pf.showProgress();
	
	Scanner s = new Scanner(System.in);
	while (s.hasNextInt()) {
		pf.setProgress(s.nextInt()/100d, "test");
	}
	s.close();
	System.exit(0);
}
 
開發者ID:CalebKussmaul,項目名稱:GIFKR,代碼行數:12,代碼來源:ProgressFrame.java

示例7: main

import java.util.Scanner; //導入方法依賴的package包/類
/**
    * this class is the main function of the program
    * it gets input of the number of the resources and the costumer threads
    * and it creates the universe where the thread's actions take place
    *
    * @param args
    */
   public static void main(String[] args) {
   	//taking two inputs and checks if the second one
   	//which are the number of the costumers are bigger than the number
   	//of the resources
   	sc = new Scanner(System.in);
       System.out.print("Enter number of resources: ");
       while (!sc.hasNextInt()) sc.next();
       int resourcesNum = sc.nextInt();
       int costumersNum;
       System.out.print("Enter number of costumers: ");
       do {
           while (!sc.hasNextInt()) sc.next();
           costumersNum = sc.nextInt();
       } while (costumersNum < resourcesNum);
       System.out.println(resourcesNum + " " + costumersNum);
   	
//after taking the inputs
       //create the universe with these parameters
   	try{
   		Rap_universe universe = new Rap_universe(resourcesNum, costumersNum);
           universe.start();
   	}catch (Exception e) {
   		System.err.println("InterruptedException occured");
	}
       
   }
 
開發者ID:vamartid,項目名稱:R.A.P.,代碼行數:34,代碼來源:Rap.java

示例8: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args)
{
	int intergral;
	Scanner sc = new Scanner(System.in);
	System.out.print("請輸入會員積分:");
	
	if (sc.hasNextInt() ) 
	{
		intergral = sc.nextInt();
		if (intergral < 0) 
		{
			System.out.print("請輸入正確的會員積分");
		}
		else if (intergral < 2000) 
		{
			System.out.print("該會員享受的折扣是:0.9");
		}
		else if (intergral < 4000) 
		{
			System.out.print("該會員享受的折扣是:0.8");
		}
		else if (intergral < 8000) 
		{
			System.out.print("該會員享受的折扣是:0.7");
		}
		else 
		{
			System.out.print("該會員享受的折扣是:0.6");
		}

	}
	else   
	{
		System.out.print("請輸入正確的會員積分");
	}
	sc.close();


}
 
開發者ID:JAVA201708,項目名稱:Homework,代碼行數:40,代碼來源:Discount.java

示例9: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args)
{
	int integral;
	double discount;
	Scanner sc = new Scanner(System.in);
	System.out.print("請輸入會員積分:");
	if (sc.hasNextInt())
	{
		integral = sc.nextInt();
		if(integral >= 8000)
		{
			discount = 0.6;
			System.out.println("該會員享受的折扣是:" + discount);
		}
		else if(integral < 8000 && integral >= 4000)
		{
			discount = 0.7;
			System.out.println("該會員享受的折扣是:" + discount);
		}
		else if(integral < 4000 && integral >= 2000)
		{
			discount = 0.8;
			System.out.println("該會員享受的折扣是:" + discount);
		}
		else
		{
			discount = 0.9;
			System.out.println("該會員享受的折扣是:" + discount);
		}
	}
	else
	{
		System.out.println("請輸入正確的數字!");
	}
	sc.close();
}
 
開發者ID:JAVA201708,項目名稱:Homework,代碼行數:37,代碼來源:MemberDiscount.java

示例10: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
	// TODO Auto-generated method stub
	//DECLARACIÓN DE VARIABLES
	Scanner teclado = new Scanner(System.in);
	int num=0;
	double result=0;
	boolean control=true;
	
	//CONTROL DEL VALOR INTRODUCIDO
	while (control) {
		System.out.println("Hola, introduce un valor");
		if (teclado.hasNextInt()) {
			num = teclado.nextInt();
			//CONTROL VALOR POSITIVO
			if (num>=0) {
				//OPERACIÓN RAÍZ CUADRADA
				result = Math.sqrt(num);
				System.out.println("El resultado es "+result);
				control = false;
			}else {
				System.out.println("El valor introducido tiene que ser positivo");
			}	
		}else {
			System.out.println("El valor introducido tiene que ser numérico.");
			teclado.next();
		}
	}
	teclado.close();
}
 
開發者ID:xaviercamps,項目名稱:Initial,代碼行數:30,代碼來源:ValidarDatos.java

示例11: Instructions

import java.util.Scanner; //導入方法依賴的package包/類
Instructions(String programFilename) throws FileNotFoundException{
    File file = new File(programFilename);
    Scanner scanner = new Scanner(file);
    String nextLine;
    instructions = new LinkedList<CopyJumpInstruction>();
    while(scanner.hasNextInt()){
        instructions.add(
                new CopyJumpInstruction(
                    new CopyInstruction(scanner.nextInt(), scanner.nextInt()),
                    new JumpInstruction(scanner.nextInt(), scanner.nextInt())
                )
        );
    }
}
 
開發者ID:arkenidar,項目名稱:copyjumpvm,代碼行數:15,代碼來源:Instructions.java

示例12: main

import java.util.Scanner; //導入方法依賴的package包/類
public static void main(String[] args) {
 Scanner in = new Scanner(System.in);

 while ( in .hasNextInt()) {
  int n = in .nextInt();
  int p = in .nextInt();
  MyCalculator my_calculator = new MyCalculator();
  try {
   System.out.println(my_calculator.power(n, p));
  } catch (Exception e) {
   System.out.println(e);
  }
 }
}
 
開發者ID:hell-sing,項目名稱:hacker-rank,代碼行數:15,代碼來源:Exception_Handling.java

示例13: input

import java.util.Scanner; //導入方法依賴的package包/類
/**
 * 讀取輸入
 * @return
 */
public static Comparable[] input(){
    Scanner scanner = new Scanner(Sort.class.getClassLoader().getResourceAsStream("tinysort.txt"));
    int count = 0;
    List<Integer> arrlist = new ArrayList<>();
    while (scanner.hasNextInt()){
        arrlist.add(scanner.nextInt());
        count++;
    }
    scanner.reset();
    Integer[] arr = new Integer[arrlist.size()];
    arrlist.toArray(arr);
    return arr;
}
 
開發者ID:wz12406,項目名稱:accumulate,代碼行數:18,代碼來源:Sort.java

示例14: evaluate

import java.util.Scanner; //導入方法依賴的package包/類
public static int evaluate(String expression)
{
	Scanner sc = new Scanner(expression);
	StackInterface<Integer> stack = new LinkedStack<Integer>();  

	int value;
	String operator;
	int operand1, operand2;
	int result = 0;

	while (sc.hasNext())
	{
		if (sc.hasNextInt())
		{
			// Process operand.
			value = sc.nextInt();
			if (stack.isFull())
				throw new PostFixException("Too many operands-stack overflow");
			stack.push(value);
		}
		else
		{
			// Process operator.
			operator = sc.next();

			// Check for illegal symbol
			if (!(operator.equals("/") || operator.equals("*") ||
					operator.equals("+") || operator.equals("-")))
				throw new PostFixException("Illegal symbol: " + operator);

			// Obtain second operand from stack.
			if (stack.isEmpty())
				throw new PostFixException("Not enough operands-stack underflow");
			operand2 = stack.peek();
			stack.pop();

			// Obtain first operand from stack.
			if (stack.isEmpty())
				throw new PostFixException("Not enough operands-stack underflow");
			operand1 = stack.peek();
			stack.pop();

			// Perform operation.
			if (operator.equals("/"))
				result = operand1 / operand2;
			else
				if(operator.equals("*"))
					result = operand1 * operand2;
				else
					if(operator.equals("+"))
						result = operand1 + operand2;
					else
						if(operator.equals("-"))
							result = operand1 - operand2;

			// Push result of operation onto stack.
			stack.push(result);
		}
	}


	// Obtain final result from stack. 
	if (stack.isEmpty())
		throw new PostFixException("Not enough operands-stack underflow");
	result = stack.peek();
	stack.pop();

	// Stack should now be empty.
	if (!stack.isEmpty())
		throw new PostFixException("Too many operands-operands left over");

	// Return the final.
	return result;
}
 
開發者ID:YC-S,項目名稱:CS401,代碼行數:75,代碼來源:PostFixEvaluator.java

示例15: run

import java.util.Scanner; //導入方法依賴的package包/類
@Override
public boolean run(DiscordBot bot, GuildMessageReceivedEvent event, String args) {
    Scanner messageIterator = new Scanner(args);

    Member member = event.getMember();
    Message message = event.getMessage();
    TextChannel channel = event.getChannel();
    Guild guild = event.getGuild();
    Member selfMember = guild.getSelfMember();

    if (!member.hasPermission(Permission.MESSAGE_MANAGE)) {
        DiscordUtils.failMessage(bot, message, "You don't have enough permissions to execute this command! Required permission: Manage Messages");
        return false;
    }

    if (!selfMember.hasPermission(Permission.MESSAGE_MANAGE)) {
        DiscordUtils.failMessage(bot, message, "I don't have enough permissions to do that!");
        return false;
    }

    if (!messageIterator.hasNextInt()) {
        DiscordUtils.failReact(bot, message);
        return true;
    }

    int messageCount = messageIterator.nextInt();

    if (messageCount < 1) {
        DiscordUtils.failMessage(bot, message, "You can't delete zero or negative messages.");
        return false;
    } else if (messageCount > 100) {
        DiscordUtils.failMessage(bot, message, "You can't delete more than 100 messages at once.");
        return false;
    }

    String targetArgument;
    User targetUser = null;

    if (!messageIterator.hasNext()) {
        targetArgument = "";
    } else if (messageIterator.hasNext(DiscordUtils.USER_MENTION_PATTERN)) {
        targetUser = message.getMentionedUsers().get(0);
        targetArgument = "user";
    } else {
        targetArgument = messageIterator.next();
    }

    List<Message> messages;
    switch (targetArgument) {
        case "":
            messages = fetchMessages(channel, messageCount, true, false, false, null);
            break;
        case "bot":
            messages = fetchMessages(channel, messageCount, false, true, false, null);
            break;
        case "user":
            if (targetUser != null) {
                messages = fetchMessages(channel, messageCount, true, false, true, targetUser);
                break;
            }
        default:
            DiscordUtils.failMessage(bot, message, "Invalid target, please try mentioning a user or writing `bot`.");
            return false;
    }

    Pair<List<Message>, List<Message>> seperatedMessages = seperateMessages(messages);
    bulkDelete(seperatedMessages, channel);
    DiscordUtils.successReact(bot, message);

    return false;
}
 
開發者ID:Samoxive,項目名稱:SafetyJim,代碼行數:72,代碼來源:Clean.java


注:本文中的java.util.Scanner.hasNextInt方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。